Beispiel #1
0
    private static void PolygonizeCell(Vector3i pos, sbyte[] density, MeshBuilder mesh, int lod)
    {
        byte directionMask = (byte)((pos.x > 0 ? 1 : 0) | ((pos.z > 0 ? 1 : 0) << 1) | ((pos.y > 0 ? 1 : 0) << 2));

        byte caseCode = GetCaseCode(density);

        if ((caseCode ^ ((density[7] >> 7) & 0xFF)) == 0) //for this cases there is no triangulation
        {
            return;
        }

        byte regularCellClass = Tables.RegularCellClass[caseCode];

        ushort[] vertexLocations = Tables.RegularVertexData[caseCode];

        Tables.RegularCell c = Tables.RegularCellData[regularCellClass];
        long vertexCount     = c.GetVertexCount();
        long triangleCount   = c.GetTriangleCount();

        byte[] indexOffset   = c.GetIndices();  // index offsets for current cell
        int[]  mappedIndices = new int[indexOffset.Length];

        for (int i = 0; i < vertexCount; ++i)
        {
            byte edge       = (byte)(vertexLocations[i] >> 8);
            byte reuseIndex = (byte)(edge & 0xF);               // vertex id which should be created or reused 1,2 or 3
            byte rDir       = (byte)(edge >> 4);                // the direction to go to reach a previous cell for reusing

            byte v0 = (byte)((vertexLocations[i] >> 4) & 0x0F); // first corner index
            byte v1 = (byte)((vertexLocations[i]) & 0x0F);      // second corner index

            sbyte d0 = density[v0];
            sbyte d1 = density[v1];

            Debug.Assert(v1 > v0);

            int   t  = (d1 << 8) / (d1 - d0);
            int   u  = 0x0100 - t;
            float t0 = t / 256f;
            float t1 = u / 256f;

            int index = -1;

            // todo: try the caching stuff later

            if (index == -1)
            {
                Vector3 p0 = new Vector3(
                    pos.x + Tables.vertexOffset[v0, 0],
                    pos.y + Tables.vertexOffset[v0, 1],
                    pos.z + Tables.vertexOffset[v0, 2]);
                Vector3 p1 = new Vector3(
                    pos.x + Tables.vertexOffset[v1, 0],
                    pos.y + Tables.vertexOffset[v1, 1],
                    pos.z + Tables.vertexOffset[v1, 2]);

                mesh.AddVertex(InterpolateVoxelVector(t, p0, p1));
            }

            mappedIndices[i] = index;
        }
    }