BSTerrainMesh.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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.PhysicsModules.SharedBase;
  33. using Nini.Config;
  34. using log4net;
  35. using OpenMetaverse;
  36. namespace OpenSim.Region.PhysicsModule.BulletS
  37. {
  38. public sealed class BSTerrainMesh : BSTerrainPhys
  39. {
  40. static string LogHeader = "[BULLETSIM TERRAIN MESH]";
  41. private float[] m_savedHeightMap;
  42. int m_sizeX;
  43. int m_sizeY;
  44. BulletShape m_terrainShape;
  45. BulletBody m_terrainBody;
  46. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize)
  47. : base(physicsScene, regionBase, id)
  48. {
  49. }
  50. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */)
  51. : base(physicsScene, regionBase, id)
  52. {
  53. }
  54. // Create terrain mesh from a heightmap.
  55. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap,
  56. Vector3 minCoords, Vector3 maxCoords)
  57. : base(physicsScene, regionBase, id)
  58. {
  59. int indicesCount;
  60. int[] indices;
  61. int verticesCount;
  62. float[] vertices;
  63. m_savedHeightMap = initialMap;
  64. m_sizeX = (int)(maxCoords.X - minCoords.X);
  65. m_sizeY = (int)(maxCoords.Y - minCoords.Y);
  66. bool meshCreationSuccess = false;
  67. if (BSParam.TerrainMeshMagnification == 1)
  68. {
  69. // If a magnification of one, use the old routine that is tried and true.
  70. meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh(m_physicsScene,
  71. initialMap, m_sizeX, m_sizeY, // input size
  72. Vector3.Zero, // base for mesh
  73. out indicesCount, out indices, out verticesCount, out vertices);
  74. }
  75. else
  76. {
  77. // Other magnifications use the newer routine
  78. meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh2(m_physicsScene,
  79. initialMap, m_sizeX, m_sizeY, // input size
  80. BSParam.TerrainMeshMagnification,
  81. physicsScene.TerrainManager.DefaultRegionSize,
  82. Vector3.Zero, // base for mesh
  83. out indicesCount, out indices, out verticesCount, out vertices);
  84. }
  85. if (!meshCreationSuccess)
  86. {
  87. // DISASTER!!
  88. m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap,id={1}", BSScene.DetailLogZero, ID);
  89. m_physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase);
  90. // Something is very messed up and a crash is in our future.
  91. return;
  92. }
  93. m_physicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}",
  94. BSScene.DetailLogZero, ID, indicesCount, indices.Length, verticesCount, vertices.Length);
  95. m_terrainShape = m_physicsScene.PE.CreateMeshShape(m_physicsScene.World, indicesCount, indices, verticesCount, vertices);
  96. if (!m_terrainShape.HasPhysicalShape)
  97. {
  98. // DISASTER!!
  99. m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape,id={1}", BSScene.DetailLogZero, ID);
  100. m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase);
  101. // Something is very messed up and a crash is in our future.
  102. return;
  103. }
  104. Vector3 pos = regionBase;
  105. Quaternion rot = Quaternion.Identity;
  106. m_terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot);
  107. if (!m_terrainBody.HasPhysicalBody)
  108. {
  109. // DISASTER!!
  110. m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase);
  111. // Something is very messed up and a crash is in our future.
  112. return;
  113. }
  114. physicsScene.PE.SetShapeCollisionMargin(m_terrainShape, BSParam.TerrainCollisionMargin);
  115. // Set current terrain attributes
  116. m_physicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction);
  117. m_physicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction);
  118. m_physicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution);
  119. m_physicsScene.PE.SetContactProcessingThreshold(m_terrainBody, BSParam.TerrainContactProcessingThreshold);
  120. m_physicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT);
  121. // Static objects are not very massive.
  122. m_physicsScene.PE.SetMassProps(m_terrainBody, 0f, Vector3.Zero);
  123. // Put the new terrain to the world of physical objects
  124. m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_terrainBody);
  125. // Redo its bounding box now that it is in the world
  126. m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_terrainBody);
  127. m_terrainBody.collisionType = CollisionType.Terrain;
  128. m_terrainBody.ApplyCollisionMask(m_physicsScene);
  129. if (BSParam.UseSingleSidedMeshes)
  130. {
  131. m_physicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial,id={1}", BSScene.DetailLogZero, id);
  132. m_physicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK);
  133. }
  134. // Make it so the terrain will not move or be considered for movement.
  135. m_physicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION);
  136. }
  137. public override void Dispose()
  138. {
  139. if (m_terrainBody.HasPhysicalBody)
  140. {
  141. m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_terrainBody);
  142. // Frees both the body and the shape.
  143. m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_terrainBody);
  144. m_terrainBody.Clear();
  145. m_terrainShape.Clear();
  146. }
  147. }
  148. public override float GetTerrainHeightAtXYZ(Vector3 pos)
  149. {
  150. // For the moment use the saved heightmap to get the terrain height.
  151. // TODO: raycast downward to find the true terrain below the position.
  152. float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
  153. int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X;
  154. try
  155. {
  156. ret = m_savedHeightMap[mapIndex];
  157. }
  158. catch
  159. {
  160. // Sometimes they give us wonky values of X and Y. Give a warning and return something.
  161. m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}",
  162. LogHeader, TerrainBase, pos);
  163. ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
  164. }
  165. return ret;
  166. }
  167. // The passed position is relative to the base of the region.
  168. public override float GetWaterLevelAtXYZ(Vector3 pos)
  169. {
  170. return m_physicsScene.SimpleWaterLevel;
  171. }
  172. // Convert the passed heightmap to mesh information suitable for CreateMeshShape2().
  173. // Return 'true' if successfully created.
  174. public static bool ConvertHeightmapToMesh( BSScene physicsScene,
  175. float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap
  176. Vector3 extentBase, // base to be added to all vertices
  177. out int indicesCountO, out int[] indicesO,
  178. out int verticesCountO, out float[] verticesO)
  179. {
  180. bool ret = false;
  181. int indicesCount = 0;
  182. int verticesCount = 0;
  183. int[] indices = new int[0];
  184. float[] vertices = new float[0];
  185. // Simple mesh creation which assumes magnification == 1.
  186. // TODO: do a more general solution that scales, adds new vertices and smoothes the result.
  187. // Create an array of vertices that is sizeX+1 by sizeY+1 (note the loop
  188. // from zero to <= sizeX). The triangle indices are then generated as two triangles
  189. // per heightmap point. There are sizeX by sizeY of these squares. The extra row and
  190. // column of vertices are used to complete the triangles of the last row and column
  191. // of the heightmap.
  192. try
  193. {
  194. // One vertice per heightmap value plus the vertices off the side and bottom edge.
  195. int totalVertices = (sizeX + 1) * (sizeY + 1);
  196. vertices = new float[totalVertices * 3];
  197. int totalIndices = sizeX * sizeY * 6;
  198. indices = new int[totalIndices];
  199. if (physicsScene != null)
  200. physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3}",
  201. BSScene.DetailLogZero, totalVertices, totalIndices, extentBase);
  202. float minHeight = float.MaxValue;
  203. // Note that sizeX+1 vertices are created since there is land between this and the next region.
  204. for (int yy = 0; yy <= sizeY; yy++)
  205. {
  206. for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we go around sizeX + 1 times
  207. {
  208. int offset = yy * sizeX + xx;
  209. // Extend the height with the height from the last row or column
  210. if (yy == sizeY) offset -= sizeX;
  211. if (xx == sizeX) offset -= 1;
  212. float height = heightMap[offset];
  213. minHeight = Math.Min(minHeight, height);
  214. vertices[verticesCount + 0] = (float)xx + extentBase.X;
  215. vertices[verticesCount + 1] = (float)yy + extentBase.Y;
  216. vertices[verticesCount + 2] = height + extentBase.Z;
  217. verticesCount += 3;
  218. }
  219. }
  220. verticesCount = verticesCount / 3;
  221. for (int yy = 0; yy < sizeY; yy++)
  222. {
  223. for (int xx = 0; xx < sizeX; xx++)
  224. {
  225. int offset = yy * (sizeX + 1) + xx;
  226. // Each vertices is presumed to be the upper left corner of a box of two triangles
  227. indices[indicesCount + 0] = offset;
  228. indices[indicesCount + 1] = offset + 1;
  229. indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column
  230. indices[indicesCount + 3] = offset + 1;
  231. indices[indicesCount + 4] = offset + sizeX + 2;
  232. indices[indicesCount + 5] = offset + sizeX + 1;
  233. indicesCount += 6;
  234. }
  235. }
  236. ret = true;
  237. }
  238. catch (Exception e)
  239. {
  240. if (physicsScene != null)
  241. physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}",
  242. LogHeader, physicsScene.RegionName, extentBase, e);
  243. }
  244. indicesCountO = indicesCount;
  245. indicesO = indices;
  246. verticesCountO = verticesCount;
  247. verticesO = vertices;
  248. return ret;
  249. }
  250. private class HeightMapGetter
  251. {
  252. private float[] m_heightMap;
  253. private int m_sizeX;
  254. private int m_sizeY;
  255. public HeightMapGetter(float[] pHeightMap, int pSizeX, int pSizeY)
  256. {
  257. m_heightMap = pHeightMap;
  258. m_sizeX = pSizeX;
  259. m_sizeY = pSizeY;
  260. }
  261. // The heightmap is extended as an infinite plane at the last height
  262. public float GetHeight(int xx, int yy)
  263. {
  264. int offset = 0;
  265. // Extend the height with the height from the last row or column
  266. if (yy >= m_sizeY)
  267. if (xx >= m_sizeX)
  268. offset = (m_sizeY - 1) * m_sizeX + (m_sizeX - 1);
  269. else
  270. offset = (m_sizeY - 1) * m_sizeX + xx;
  271. else
  272. if (xx >= m_sizeX)
  273. offset = yy * m_sizeX + (m_sizeX - 1);
  274. else
  275. offset = yy * m_sizeX + xx;
  276. return m_heightMap[offset];
  277. }
  278. }
  279. // Convert the passed heightmap to mesh information suitable for CreateMeshShape2().
  280. // Version that handles magnification.
  281. // Return 'true' if successfully created.
  282. public static bool ConvertHeightmapToMesh2( BSScene physicsScene,
  283. float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap
  284. int magnification, // number of vertices per heighmap step
  285. Vector3 extent, // dimensions of the output mesh
  286. Vector3 extentBase, // base to be added to all vertices
  287. out int indicesCountO, out int[] indicesO,
  288. out int verticesCountO, out float[] verticesO)
  289. {
  290. bool ret = false;
  291. int indicesCount = 0;
  292. int verticesCount = 0;
  293. int[] indices = new int[0];
  294. float[] vertices = new float[0];
  295. HeightMapGetter hmap = new HeightMapGetter(heightMap, sizeX, sizeY);
  296. // The vertices dimension of the output mesh
  297. int meshX = sizeX * magnification;
  298. int meshY = sizeY * magnification;
  299. // The output size of one mesh step
  300. float meshXStep = extent.X / meshX;
  301. float meshYStep = extent.Y / meshY;
  302. // Create an array of vertices that is meshX+1 by meshY+1 (note the loop
  303. // from zero to <= meshX). The triangle indices are then generated as two triangles
  304. // per heightmap point. There are meshX by meshY of these squares. The extra row and
  305. // column of vertices are used to complete the triangles of the last row and column
  306. // of the heightmap.
  307. try
  308. {
  309. // Vertices for the output heightmap plus one on the side and bottom to complete triangles
  310. int totalVertices = (meshX + 1) * (meshY + 1);
  311. vertices = new float[totalVertices * 3];
  312. int totalIndices = meshX * meshY * 6;
  313. indices = new int[totalIndices];
  314. if (physicsScene != null)
  315. physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,inSize={1},outSize={2},totVert={3},totInd={4},extentBase={5}",
  316. BSScene.DetailLogZero, new Vector2(sizeX, sizeY), new Vector2(meshX, meshY),
  317. totalVertices, totalIndices, extentBase);
  318. float minHeight = float.MaxValue;
  319. // Note that sizeX+1 vertices are created since there is land between this and the next region.
  320. // Loop through the output vertices and compute the mediun height in between the input vertices
  321. for (int yy = 0; yy <= meshY; yy++)
  322. {
  323. for (int xx = 0; xx <= meshX; xx++) // Hint: the "<=" means we go around sizeX + 1 times
  324. {
  325. float offsetY = (float)yy * (float)sizeY / (float)meshY; // The Y that is closest to the mesh point
  326. int stepY = (int)offsetY;
  327. float fractionalY = offsetY - (float)stepY;
  328. float offsetX = (float)xx * (float)sizeX / (float)meshX; // The X that is closest to the mesh point
  329. int stepX = (int)offsetX;
  330. float fractionalX = offsetX - (float)stepX;
  331. // physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,xx={1},yy={2},offX={3},stepX={4},fractX={5},offY={6},stepY={7},fractY={8}",
  332. // BSScene.DetailLogZero, xx, yy, offsetX, stepX, fractionalX, offsetY, stepY, fractionalY);
  333. // get the four corners of the heightmap square the mesh point is in
  334. float heightUL = hmap.GetHeight(stepX , stepY );
  335. float heightUR = hmap.GetHeight(stepX + 1, stepY );
  336. float heightLL = hmap.GetHeight(stepX , stepY + 1);
  337. float heightLR = hmap.GetHeight(stepX + 1, stepY + 1);
  338. // bilinear interplolation
  339. float height = heightUL * (1 - fractionalX) * (1 - fractionalY)
  340. + heightUR * fractionalX * (1 - fractionalY)
  341. + heightLL * (1 - fractionalX) * fractionalY
  342. + heightLR * fractionalX * fractionalY;
  343. // physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,heightUL={1},heightUR={2},heightLL={3},heightLR={4},heightMap={5}",
  344. // BSScene.DetailLogZero, heightUL, heightUR, heightLL, heightLR, height);
  345. minHeight = Math.Min(minHeight, height);
  346. vertices[verticesCount + 0] = (float)xx * meshXStep + extentBase.X;
  347. vertices[verticesCount + 1] = (float)yy * meshYStep + extentBase.Y;
  348. vertices[verticesCount + 2] = height + extentBase.Z;
  349. verticesCount += 3;
  350. }
  351. }
  352. // The number of vertices generated
  353. verticesCount /= 3;
  354. // Loop through all the heightmap squares and create indices for the two triangles for that square
  355. for (int yy = 0; yy < meshY; yy++)
  356. {
  357. for (int xx = 0; xx < meshX; xx++)
  358. {
  359. int offset = yy * (meshX + 1) + xx;
  360. // Each vertices is presumed to be the upper left corner of a box of two triangles
  361. indices[indicesCount + 0] = offset;
  362. indices[indicesCount + 1] = offset + 1;
  363. indices[indicesCount + 2] = offset + meshX + 1; // accounting for the extra column
  364. indices[indicesCount + 3] = offset + 1;
  365. indices[indicesCount + 4] = offset + meshX + 2;
  366. indices[indicesCount + 5] = offset + meshX + 1;
  367. indicesCount += 6;
  368. }
  369. }
  370. ret = true;
  371. }
  372. catch (Exception e)
  373. {
  374. if (physicsScene != null)
  375. physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}",
  376. LogHeader, physicsScene.RegionName, extentBase, e);
  377. }
  378. indicesCountO = indicesCount;
  379. indicesO = indices;
  380. verticesCountO = verticesCount;
  381. verticesO = vertices;
  382. return ret;
  383. }
  384. }
  385. }