title: Unity: Compute Shader to calculate closest point to each vertex
body: <p>I have a mesh, and an array of points. I want to calculate, for each vertex, the index of the closest point in the array.
  I have a routine that works:</p>
  
  <pre><code>        for (int i=0;i&lt;vertexPositions.Length;i++)
      {
          float minDist = 100000.0f;
          int index=0;
          float dist;
          for (int a=0;a&lt;pointPositions.Length;a++)
          {
              dist = (vertexPositions[i] - pointPositions[a]).sqrMagnitude;
              if (dist&lt;minDist)
              {
                  minDist = dist;
                  index = a;
              }
          }
          vertexParameter[i] = index;
      }
  </code></pre>
  
  <p>The <code>vertexParameter</code> array contains the desired result. This routine is very slow if there are many vertices, so I wanted to make a Compute Shader that does the exact same thing. But I'm a beginner at Compute Shaders…</p>
  
  <p>This is my Compute Shader code:</p>
  
  <pre><code>#pragma kernel ClosestPoint
  
  struct vertexData
  {
      float3 position;
      int parameter;
  };
  struct pointData
  {
      float3 position;
      float parameter;
  };
  
  RWStructuredBuffer&lt;vertexData&gt; vertex;
  StructuredBuffer&lt;pointData&gt; point;
  
  
  [numthreads(32, 1, 1)]
  void ClosestPoint(uint3 id : SV_DispatchThreadID)
  {
      int index;
      float dist;
      float minDist = 1000.0f;
      for (uint i = 0; i &lt; point.Length; i++)
      {
          dist = distance(point[i].position, vertex[id.x].position);
          if (dist &lt; minDist)
          {
              minDist = dist;
              index =  i;
          }
  
      }
      vertex[id.x].parameter =  index;
  }
  </code></pre>
  
  <p>I don't know why, but this code gives erroneous results. The results change if I modify the ThreadGroups in the Dispatch call, so I suppose it might be due to some synchronization issues…?</p>
  
  <p>In case it's needed, this is the script code that calls the shader:</p>
  
  <pre><code>        vertex = new ComputeBuffer(vertices.Length, System.Runtime.InteropServices.Marshal.SizeOf(typeof(vertexData)));
      vertex.SetData(vertices);
  
  
      point= new ComputeBuffer(points.Length, System.Runtime.InteropServices.Marshal.SizeOf(typeof(pointData)));
      point.SetData(points);
  
      shader.SetBuffer(kernelHandle, "vertex", vertex);
      shader.SetBuffer(kernelHandle, "point", point);
      shader.Dispatch(kernelHandle, 1, 1, 1);
      vertex.GetData(vertices);
      for (int i = 0; i &lt; vertexParameter.Length; i++)
      {
          vertexParameter[i] = vertices[i].parameter;
      }
      vertex.Release();
      point.Release();
  </code></pre>