BSTerrainMesh.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyrightD
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Text;
  30. using OpenSim.Framework;
  31. using OpenSim.Region.Framework;
  32. using OpenSim.Region.CoreModules;
  33. using OpenSim.Region.Physics.Manager;
  34. using Nini.Config;
  35. using log4net;
  36. using OpenMetaverse;
  37. namespace OpenSim.Region.Physics.BulletSNPlugin
  38. {
  39. public sealed class BSTerrainMesh : BSTerrainPhys
  40. {
  41. static string LogHeader = "[BULLETSIM TERRAIN MESH]";
  42. private float[] m_savedHeightMap;
  43. int m_sizeX;
  44. int m_sizeY;
  45. BulletShape m_terrainShape;
  46. BulletBody m_terrainBody;
  47. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize)
  48. : base(physicsScene, regionBase, id)
  49. {
  50. }
  51. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */)
  52. : base(physicsScene, regionBase, id)
  53. {
  54. }
  55. // Create terrain mesh from a heightmap.
  56. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap,
  57. Vector3 minCoords, Vector3 maxCoords)
  58. : base(physicsScene, regionBase, id)
  59. {
  60. int indicesCount;
  61. int[] indices;
  62. int verticesCount;
  63. float[] vertices;
  64. m_savedHeightMap = initialMap;
  65. m_sizeX = (int)(maxCoords.X - minCoords.X);
  66. m_sizeY = (int)(maxCoords.Y - minCoords.Y);
  67. if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap,
  68. m_sizeX, m_sizeY,
  69. (float)m_sizeX, (float)m_sizeY,
  70. Vector3.Zero, 1.0f,
  71. out indicesCount, out indices, out verticesCount, out vertices))
  72. {
  73. // DISASTER!!
  74. PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap", ID);
  75. PhysicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase);
  76. // Something is very messed up and a crash is in our future.
  77. return;
  78. }
  79. PhysicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,indices={1},indSz={2},vertices={3},vertSz={4}",
  80. ID, indicesCount, indices.Length, verticesCount, vertices.Length);
  81. m_terrainShape = new BulletShape(BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr,
  82. indicesCount, indices, verticesCount, vertices),
  83. BSPhysicsShapeType.SHAPE_MESH);
  84. if (!m_terrainShape.HasPhysicalShape)
  85. {
  86. // DISASTER!!
  87. PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape", ID);
  88. physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase);
  89. // Something is very messed up and a crash is in our future.
  90. return;
  91. }
  92. Vector3 pos = regionBase;
  93. Quaternion rot = Quaternion.Identity;
  94. m_terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2( m_terrainShape.ptr, ID, pos, rot));
  95. if (!m_terrainBody.HasPhysicalBody)
  96. {
  97. // DISASTER!!
  98. physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase);
  99. // Something is very messed up and a crash is in our future.
  100. return;
  101. }
  102. // Set current terrain attributes
  103. BulletSimAPI.SetFriction2(m_terrainBody.ptr, BSParam.TerrainFriction);
  104. BulletSimAPI.SetHitFraction2(m_terrainBody.ptr, BSParam.TerrainHitFraction);
  105. BulletSimAPI.SetRestitution2(m_terrainBody.ptr, BSParam.TerrainRestitution);
  106. BulletSimAPI.SetCollisionFlags2(m_terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT);
  107. // Static objects are not very massive.
  108. BulletSimAPI.SetMassProps2(m_terrainBody.ptr, 0f, Vector3.Zero);
  109. // Put the new terrain to the world of physical objects
  110. BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr, pos, rot);
  111. // Redo its bounding box now that it is in the world
  112. BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_terrainBody.ptr);
  113. m_terrainBody.collisionType = CollisionType.Terrain;
  114. m_terrainBody.ApplyCollisionMask();
  115. // Make it so the terrain will not move or be considered for movement.
  116. BulletSimAPI.ForceActivationState2(m_terrainBody.ptr, ActivationState.DISABLE_SIMULATION);
  117. }
  118. public override void Dispose()
  119. {
  120. if (m_terrainBody.HasPhysicalBody)
  121. {
  122. BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr);
  123. // Frees both the body and the shape.
  124. BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_terrainBody.ptr);
  125. }
  126. }
  127. public override float GetTerrainHeightAtXYZ(Vector3 pos)
  128. {
  129. // For the moment use the saved heightmap to get the terrain height.
  130. // TODO: raycast downward to find the true terrain below the position.
  131. float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
  132. int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X;
  133. try
  134. {
  135. ret = m_savedHeightMap[mapIndex];
  136. }
  137. catch
  138. {
  139. // Sometimes they give us wonky values of X and Y. Give a warning and return something.
  140. PhysicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}",
  141. LogHeader, TerrainBase, pos);
  142. ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
  143. }
  144. return ret;
  145. }
  146. // The passed position is relative to the base of the region.
  147. public override float GetWaterLevelAtXYZ(Vector3 pos)
  148. {
  149. return PhysicsScene.SimpleWaterLevel;
  150. }
  151. // Convert the passed heightmap to mesh information suitable for CreateMeshShape2().
  152. // Return 'true' if successfully created.
  153. public static bool ConvertHeightmapToMesh(
  154. BSScene physicsScene,
  155. float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap
  156. float extentX, float extentY, // zero based range for output vertices
  157. Vector3 extentBase, // base to be added to all vertices
  158. float magnification, // number of vertices to create between heightMap coords
  159. out int indicesCountO, out int[] indicesO,
  160. out int verticesCountO, out float[] verticesO)
  161. {
  162. bool ret = false;
  163. int indicesCount = 0;
  164. int verticesCount = 0;
  165. int[] indices = new int[0];
  166. float[] vertices = new float[0];
  167. // Simple mesh creation which assumes magnification == 1.
  168. // TODO: do a more general solution that scales, adds new vertices and smoothes the result.
  169. // Create an array of vertices that is sizeX+1 by sizeY+1 (note the loop
  170. // from zero to <= sizeX). The triangle indices are then generated as two triangles
  171. // per heightmap point. There are sizeX by sizeY of these squares. The extra row and
  172. // column of vertices are used to complete the triangles of the last row and column
  173. // of the heightmap.
  174. try
  175. {
  176. // One vertice per heightmap value plus the vertices off the top and bottom edge.
  177. int totalVertices = (sizeX + 1) * (sizeY + 1);
  178. vertices = new float[totalVertices * 3];
  179. int totalIndices = sizeX * sizeY * 6;
  180. indices = new int[totalIndices];
  181. float magX = (float)sizeX / extentX;
  182. float magY = (float)sizeY / extentY;
  183. physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3},magX={4},magY={5}",
  184. BSScene.DetailLogZero, totalVertices, totalIndices, extentBase, magX, magY);
  185. float minHeight = float.MaxValue;
  186. // Note that sizeX+1 vertices are created since there is land between this and the next region.
  187. for (int yy = 0; yy <= sizeY; yy++)
  188. {
  189. for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we go around sizeX + 1 times
  190. {
  191. int offset = yy * sizeX + xx;
  192. // Extend the height with the height from the last row or column
  193. if (yy == sizeY) offset -= sizeX;
  194. if (xx == sizeX) offset -= 1;
  195. float height = heightMap[offset];
  196. minHeight = Math.Min(minHeight, height);
  197. vertices[verticesCount + 0] = (float)xx * magX + extentBase.X;
  198. vertices[verticesCount + 1] = (float)yy * magY + extentBase.Y;
  199. vertices[verticesCount + 2] = height + extentBase.Z;
  200. verticesCount += 3;
  201. }
  202. }
  203. verticesCount = verticesCount / 3;
  204. for (int yy = 0; yy < sizeY; yy++)
  205. {
  206. for (int xx = 0; xx < sizeX; xx++)
  207. {
  208. int offset = yy * (sizeX + 1) + xx;
  209. // Each vertices is presumed to be the upper left corner of a box of two triangles
  210. indices[indicesCount + 0] = offset;
  211. indices[indicesCount + 1] = offset + 1;
  212. indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column
  213. indices[indicesCount + 3] = offset + 1;
  214. indices[indicesCount + 4] = offset + sizeX + 2;
  215. indices[indicesCount + 5] = offset + sizeX + 1;
  216. indicesCount += 6;
  217. }
  218. }
  219. ret = true;
  220. }
  221. catch (Exception e)
  222. {
  223. physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}",
  224. LogHeader, physicsScene.RegionName, extentBase, e);
  225. }
  226. indicesCountO = indicesCount;
  227. indicesO = indices;
  228. verticesCountO = verticesCount;
  229. verticesO = vertices;
  230. return ret;
  231. }
  232. }
  233. }