'How can I translate my mesh polygonizer code into a compute shader?

I have am trying to create a mesh with marching cubes. Currently I am generating the volume and vertex data in a compute shader, then reading the vertex data back into the CPU and triangulating the vertices.

This is my vertex data struct :

 private struct Triangle
 {
    public float3 v1;public float3 v2;
    public float3 v3;
    public float3 n;
 }

This is my triangulation code:

   void AddTriangle(Triangle tri) // this method is called on every Triangle in the Triangle[] I get form the compute shader
                {
                    if (tri.n.x == 0 && tri.n.y == 0 && tri.n.z == 0) return; // this triangle is empty

                    AddVertex(tri.v1); 
                    AddVertex(tri.v2);
                    AddVertex(tri.v3);

                    void AddVertex(Vector3 vertex)
                    {
                        int foundIndex = -1; // index of vertex if its already in vertex list
                        for (int i = 0; i < vertices.Count; i++)
                        {
                            if (vertex == vertices[i])
                            {
                                foundIndex = i; // vertex is already in the list
                                break;
                            }
                        }

                        if (foundIndex == -1) // vertex is not already in list
                        {
                            vertices.Add(vertex); // add vertex to list
                            triangles.Add(vertices.Count - 1); // add triangle to list
                            normals.Add(tri.n); // add normal to list
                        }
                        else // if vertex is already in the list
                        {
                            triangles.Add(foundIndex); // "connect" to the vertex that is alrady in list
                        }
                    }
                }

Is there any way I could translate this into a compute shader? I'm using unity if anyone is wondering. Here is an image of what its creating currently : Result



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source