Ejemplo n.º 1
0
    void Generate()
    {
        vertices.Clear();
        triangles.Clear();
        int triangleNum = 0;

        for (int x = 0; x < resolution; x++)
        {
            for (int y = 0; y < resolution; y++)
            {
                for (int z = 0; z < resolution; z++)
                {
                    int caseNum = 0;
                    for (int i = 0; i < 8; i++)
                    {
                        float value = densityData[x + cubeVertOffsets[i].x, y + cubeVertOffsets[i].y, z + cubeVertOffsets[i].z];
                        if (invert ? value <surfaceLevel : value> surfaceLevel)
                        {
                            caseNum += (int)Mathf.Pow(2, i);
                        }
                    }

                    int[] triangulationCase = triangulation[caseNum];
                    foreach (int edgeIndex in triangulationCase)
                    {
                        if (edgeIndex == -1)
                        {
                            break;
                        }

                        int indexA = cornerIndexAFromEdge[edgeIndex];
                        int indexB = cornerIndexBFromEdge[edgeIndex];

                        if (smooth)
                        {
                            Int3 v3IndexA = new Int3(x, y, z) + cubeVertOffsets[indexA];
                            Int3 v3IndexB = new Int3(x, y, z) + cubeVertOffsets[indexB];

                            float densityA = densityData[v3IndexA.x, v3IndexA.y, v3IndexA.z];
                            float densityB = densityData[v3IndexB.x, v3IndexB.y, v3IndexB.z];
                            float lerp     = (surfaceLevel - densityB) / (densityA - densityB);

                            Vector3 vertPos = Vector3.Lerp(v3IndexB.ToV3(), v3IndexA.ToV3(), lerp);

                            vertices.Add(vertPos);
                            triangles.Add(triangleNum++);
                        }
                        else
                        {
                            Vector3 vertA   = cubeVertOffsets[indexA].ToV3();
                            Vector3 vertB   = cubeVertOffsets[indexB].ToV3();
                            Vector3 vertPos = (vertA + vertB) / 2;

                            vertices.Add(new Vector3(x, y, z) + vertPos);
                            triangles.Add(triangleNum++);
                        }
                    }
                }
            }
        }
    }