Universe.Physics.BulletSPlugin.BSTerrainMesh.ConvertHeightmapToMesh C# (CSharp) Method

ConvertHeightmapToMesh() public static method

public static ConvertHeightmapToMesh ( BSScene physicsScene, float heightMap, int sizeX, int sizeY, System.Vector3 extentBase, int &indicesCountO, int &indicesO, int &verticesCountO, float &verticesO ) : bool
physicsScene BSScene
heightMap float
sizeX int
sizeY int
extentBase System.Vector3
indicesCountO int
indicesO int
verticesCountO int
verticesO float
return bool
        public static bool ConvertHeightmapToMesh(BSScene physicsScene,
            float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap
            Vector3 extentBase, // base to be added to all vertices
            out int indicesCountO, out int[] indicesO,
            out int verticesCountO, out float[] verticesO)
        {
            bool ret = false;

            int indicesCount = 0;
            int verticesCount = 0;
            int[] indices = new int[0];
            float[] vertices = new float[0];

            // Simple mesh creation which assumes magnification == 1.
            // TODO: do a more general solution that scales, adds new vertices and smoothes the result.

            // Create an array of vertices that is sizeX+1 by sizeY+1 (note the loop
            //    from zero to <= sizeX). The triangle indices are then generated as two triangles
            //    per heightmap point. There are sizeX by sizeY of these squares. The extra row and
            //    column of vertices are used to complete the triangles of the last row and column
            //    of the heightmap.
            try
            {
                // One vertice per heightmap value plus the vertices off the side and bottom edge.
                int totalVertices = (sizeX + 1) * (sizeY + 1);
                vertices = new float[totalVertices * 3];
                int totalIndices = sizeX * sizeY * 6;
                indices = new int[totalIndices];

                if (physicsScene != null)
                    physicsScene.DetailLog(
                        "{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3}",
                        BSScene.DetailLogZero, totalVertices, totalIndices, extentBase);
                float minHeight = float.MaxValue;
                // Note that sizeX+1 vertices are created since there is land between this and the next region.
                for (int yy = 0; yy <= sizeY; yy++)
                {
                    for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we go around sizeX + 1 times
                    {
                        int offset = yy * sizeX + xx;
                        // Extend the height with the height from the last row or column
                        if (yy == sizeY) offset -= sizeX;
                        if (xx == sizeX) offset -= 1;
                        float height = heightMap[offset];
                        minHeight = Math.Min(minHeight, height);
                        vertices[verticesCount + 0] = (float)xx + extentBase.X;
                        vertices[verticesCount + 1] = (float)yy + extentBase.Y;
                        vertices[verticesCount + 2] = height + extentBase.Z;
                        verticesCount += 3;
                    }
                }
                verticesCount = verticesCount / 3;

                for (int yy = 0; yy < sizeY; yy++)
                {
                    for (int xx = 0; xx < sizeX; xx++)
                    {
                        int offset = yy * (sizeX + 1) + xx;
                        // Each vertices is presumed to be the upper left corner of a box of two triangles
                        indices[indicesCount + 0] = offset;
                        indices[indicesCount + 1] = offset + 1;
                        indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column
                        indices[indicesCount + 3] = offset + 1;
                        indices[indicesCount + 4] = offset + sizeX + 2;
                        indices[indicesCount + 5] = offset + sizeX + 1;
                        indicesCount += 6;
                    }
                }

                ret = true;
            }
            catch (Exception e)
            {
                if (physicsScene != null)
                    physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}",
                        LogHeader, physicsScene.RegionName, extentBase, e);
            }

            indicesCountO = indicesCount;
            indicesO = indices;
            verticesCountO = verticesCount;
            verticesO = vertices;

            return ret;
        }

Usage Example

        // Create terrain mesh from a heightmap.
        public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap,
                             Vector3 minCoords, Vector3 maxCoords)
            : base(physicsScene, regionBase, id)
        {
            int indicesCount;

            int[] indices;
            int   verticesCount;

            float[] vertices;

            m_savedHeightMap = initialMap;

            m_sizeX = (int)(maxCoords.X - minCoords.X);
            m_sizeY = (int)(maxCoords.Y - minCoords.Y);

            bool meshCreationSuccess = false;

            if (BSParam.TerrainMeshMagnification == 1)
            {
                // If a magnification of one, use the old routine that is tried and true.
                meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene,
                                                                           initialMap, m_sizeX, m_sizeY, // input size
                                                                           Vector3.Zero,                 // base for mesh
                                                                           out indicesCount, out indices, out verticesCount, out vertices);
            }
            else
            {
                // Other magnifications use the newer routine
                meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh2(PhysicsScene,
                                                                            initialMap, m_sizeX, m_sizeY, // input size
                                                                            BSParam.TerrainMeshMagnification,
                                                                            physicsScene.TerrainManager.WorldMax,
                                                                            Vector3.Zero, // base for mesh
                                                                            out indicesCount, out indices, out verticesCount, out vertices);
            }
            if (!meshCreationSuccess)
            {
                // DISASTER!!
                PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap,id={1}",
                                       BSScene.DetailLogZero, ID);
                PhysicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader,
                                                TerrainBase);
                // Something is very messed up and a crash is in our future.
                return;
            }

            PhysicsScene.DetailLog("{0},BSTerrainMesh.create,meshid,id={1},indices={2},indSz={3},vertices={4},vertSz={5}",
                                   BSScene.DetailLogZero, ID, indicesCount, indices.Length, verticesCount, vertices.Length);

            m_terrainShape = PhysicsScene.PE.CreateMeshShape(PhysicsScene.World, indicesCount, indices, verticesCount,
                                                             vertices);

            if (!m_terrainShape.HasPhysicalShape)
            {
                // DISASTER!!
                PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape,id={1}", BSScene.DetailLogZero,
                                       ID);
                PhysicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase);
                // Something is very messed up and a crash is in our future.
                return;
            }

            Vector3    pos = regionBase;
            Quaternion rot = Quaternion.Identity;

            m_terrainBody = PhysicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot);
            if (!m_terrainBody.HasPhysicalBody)
            {
                // DISASTER!!
                PhysicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase);
                // Something is very messed up and a crash is in our future.
                return;
            }

            physicsScene.PE.SetShapeCollisionMargin(m_terrainShape, BSParam.TerrainCollisionMargin);

            // Set current terrain attributes
            PhysicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction);
            PhysicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction);
            PhysicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution);
            PhysicsScene.PE.SetContactProcessingThreshold(m_terrainBody, BSParam.TerrainContactProcessingThreshold);
            PhysicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT);

            // Static objects are not very massive.
            PhysicsScene.PE.SetMassProps(m_terrainBody, 0.1f, Vector3.Zero);

            // Put the new terrain to the world of physical objects
            PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, m_terrainBody);

            // Redo its bounding box now that it is in the world
            PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, m_terrainBody);

            m_terrainBody.collisionType = CollisionType.Terrain;
            m_terrainBody.ApplyCollisionMask(PhysicsScene);

            if (BSParam.UseSingleSidedMeshes)
            {
                PhysicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial,id={1}", BSScene.DetailLogZero, id);
                PhysicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK);
            }

            // Make it so the terrain will not move or be considered for movement.
            PhysicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION);
        }