1
0

BSTerrainMesh.cs 20 KB

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