BSShapeCollection.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 OMV = OpenMetaverse;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.Physics.Manager;
  33. using OpenSim.Region.Physics.ConvexDecompositionDotNet;
  34. namespace OpenSim.Region.Physics.BulletSPlugin
  35. {
  36. public sealed class BSShapeCollection : IDisposable
  37. {
  38. private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]";
  39. private BSScene m_physicsScene { get; set; }
  40. private Object m_collectionActivityLock = new Object();
  41. private bool DDetail = false;
  42. public BSShapeCollection(BSScene physScene)
  43. {
  44. m_physicsScene = physScene;
  45. // Set the next to 'true' for very detailed shape update detailed logging (detailed details?)
  46. // While detailed debugging is still active, this is better than commenting out all the
  47. // DetailLog statements. When debugging slows down, this and the protected logging
  48. // statements can be commented/removed.
  49. DDetail = true;
  50. }
  51. public void Dispose()
  52. {
  53. // TODO!!!!!!!!!
  54. }
  55. // Callbacks called just before either the body or shape is destroyed.
  56. // Mostly used for changing bodies out from under Linksets.
  57. // Useful for other cases where parameters need saving.
  58. // Passing 'null' says no callback.
  59. public delegate void PhysicalDestructionCallback(BulletBody pBody, BulletShape pShape);
  60. // Called to update/change the body and shape for an object.
  61. // The object has some shape and body on it. Here we decide if that is the correct shape
  62. // for the current state of the object (static/dynamic/...).
  63. // If bodyCallback is not null, it is called if either the body or the shape are changed
  64. // so dependencies (like constraints) can be removed before the physical object is dereferenced.
  65. // Return 'true' if either the body or the shape changed.
  66. // Called at taint-time.
  67. public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim, PhysicalDestructionCallback bodyCallback)
  68. {
  69. m_physicsScene.AssertInTaintTime("BSShapeCollection.GetBodyAndShape");
  70. bool ret = false;
  71. // This lock could probably be pushed down lower but building shouldn't take long
  72. lock (m_collectionActivityLock)
  73. {
  74. // Do we have the correct geometry for this type of object?
  75. // Updates prim.BSShape with information/pointers to shape.
  76. // Returns 'true' of BSShape is changed to a new shape.
  77. bool newGeom = CreateGeom(forceRebuild, prim, bodyCallback);
  78. // If we had to select a new shape geometry for the object,
  79. // rebuild the body around it.
  80. // Updates prim.BSBody with information/pointers to requested body
  81. // Returns 'true' if BSBody was changed.
  82. bool newBody = CreateBody((newGeom || forceRebuild), prim, m_physicsScene.World, bodyCallback);
  83. ret = newGeom || newBody;
  84. }
  85. DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}",
  86. prim.LocalID, forceRebuild, ret, prim.PhysBody, prim.PhysShape);
  87. return ret;
  88. }
  89. public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim)
  90. {
  91. return GetBodyAndShape(forceRebuild, sim, prim, null);
  92. }
  93. // If the existing prim's shape is to be replaced, remove the tie to the existing shape
  94. // before replacing it.
  95. private void DereferenceExistingShape(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
  96. {
  97. if (prim.PhysShape.HasPhysicalShape)
  98. {
  99. if (shapeCallback != null)
  100. shapeCallback(prim.PhysBody, prim.PhysShape.physShapeInfo);
  101. prim.PhysShape.Dereference(m_physicsScene);
  102. }
  103. prim.PhysShape = new BSShapeNull();
  104. }
  105. // Create the geometry information in Bullet for later use.
  106. // The objects needs a hull if it's physical otherwise a mesh is enough.
  107. // if 'forceRebuild' is true, the geometry is unconditionally rebuilt. For meshes and hulls,
  108. // shared geometries will be used. If the parameters of the existing shape are the same
  109. // as this request, the shape is not rebuilt.
  110. // Info in prim.BSShape is updated to the new shape.
  111. // Returns 'true' if the geometry was rebuilt.
  112. // Called at taint-time!
  113. private bool CreateGeom(bool forceRebuild, BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
  114. {
  115. bool ret = false;
  116. bool haveShape = false;
  117. bool nativeShapePossible = true;
  118. PrimitiveBaseShape pbs = prim.BaseShape;
  119. // Kludge to create the capsule for the avatar.
  120. // TDOD: Remove/redo this when BSShapeAvatar is working!!
  121. BSCharacter theChar = prim as BSCharacter;
  122. if (theChar != null)
  123. {
  124. DereferenceExistingShape(prim, shapeCallback);
  125. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  126. BSPhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE);
  127. ret = true;
  128. haveShape = true;
  129. }
  130. // If the prim attributes are simple, this could be a simple Bullet native shape
  131. // Native shapes work whether to object is static or physical.
  132. if (!haveShape
  133. && nativeShapePossible
  134. && pbs != null
  135. && PrimHasNoCuts(pbs)
  136. && ( !pbs.SculptEntry || (pbs.SculptEntry && !BSParam.ShouldMeshSculptedPrim) )
  137. )
  138. {
  139. // Get the scale of any existing shape so we can see if the new shape is same native type and same size.
  140. OMV.Vector3 scaleOfExistingShape = OMV.Vector3.Zero;
  141. if (prim.PhysShape.HasPhysicalShape)
  142. scaleOfExistingShape = m_physicsScene.PE.GetLocalScaling(prim.PhysShape.physShapeInfo);
  143. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,maybeNative,force={1},primScale={2},primSize={3},primShape={4}",
  144. prim.LocalID, forceRebuild, prim.Scale, prim.Size, prim.PhysShape.physShapeInfo.shapeType);
  145. // It doesn't look like Bullet scales native spheres so make sure the scales are all equal
  146. if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1)
  147. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z)
  148. {
  149. haveShape = true;
  150. if (forceRebuild
  151. || prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_SPHERE
  152. )
  153. {
  154. DereferenceExistingShape(prim, shapeCallback);
  155. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  156. BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_SPHERE);
  157. ret = true;
  158. }
  159. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},rebuilt={2},shape={3}",
  160. prim.LocalID, forceRebuild, ret, prim.PhysShape);
  161. }
  162. // If we didn't make a sphere, maybe a box will work.
  163. if (!haveShape && pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  164. {
  165. haveShape = true;
  166. if (forceRebuild
  167. || prim.Scale != scaleOfExistingShape
  168. || prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_BOX
  169. )
  170. {
  171. DereferenceExistingShape(prim, shapeCallback);
  172. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  173. BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
  174. ret = true;
  175. }
  176. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},rebuilt={2},shape={3}",
  177. prim.LocalID, forceRebuild, ret, prim.PhysShape);
  178. }
  179. }
  180. // If a simple shape is not happening, create a mesh and possibly a hull.
  181. if (!haveShape && pbs != null)
  182. {
  183. ret = CreateGeomMeshOrHull(prim, shapeCallback);
  184. }
  185. return ret;
  186. }
  187. // return 'true' if this shape description does not include any cutting or twisting.
  188. public static bool PrimHasNoCuts(PrimitiveBaseShape pbs)
  189. {
  190. return pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  191. && pbs.ProfileHollow == 0
  192. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  193. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  194. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  195. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  196. && pbs.PathShearX == 0 && pbs.PathShearY == 0;
  197. }
  198. // return 'true' if the prim's shape was changed.
  199. private bool CreateGeomMeshOrHull(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
  200. {
  201. bool ret = false;
  202. // Note that if it's a native shape, the check for physical/non-physical is not
  203. // made. Native shapes work in either case.
  204. if (prim.IsPhysical && BSParam.ShouldUseHullsForPhysicalObjects)
  205. {
  206. // Use a simple, single mesh convex hull shape if the object is simple enough
  207. BSShape potentialHull = null;
  208. PrimitiveBaseShape pbs = prim.BaseShape;
  209. // Use a simple, one section convex shape for prims that are probably convex (no cuts or twists)
  210. if (BSParam.ShouldUseSingleConvexHullForPrims
  211. && pbs != null
  212. && !pbs.SculptEntry
  213. && PrimHasNoCuts(pbs)
  214. )
  215. {
  216. potentialHull = BSShapeConvexHull.GetReference(m_physicsScene, false /* forceRebuild */, prim);
  217. }
  218. // Use the GImpact shape if it is a prim that has some concaveness
  219. if (potentialHull == null
  220. && BSParam.ShouldUseGImpactShapeForPrims
  221. && pbs != null
  222. && !pbs.SculptEntry
  223. )
  224. {
  225. potentialHull = BSShapeGImpact.GetReference(m_physicsScene, false /* forceRebuild */, prim);
  226. }
  227. // If not any of the simple cases, just make a hull
  228. if (potentialHull == null)
  229. {
  230. potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
  231. }
  232. // If the current shape is not what is on the prim at the moment, time to change.
  233. if (!prim.PhysShape.HasPhysicalShape
  234. || potentialHull.ShapeType != prim.PhysShape.ShapeType
  235. || potentialHull.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
  236. {
  237. DereferenceExistingShape(prim, shapeCallback);
  238. prim.PhysShape = potentialHull;
  239. ret = true;
  240. }
  241. else
  242. {
  243. // The current shape on the prim is the correct one. We don't need the potential reference.
  244. potentialHull.Dereference(m_physicsScene);
  245. }
  246. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1}", prim.LocalID, prim.PhysShape);
  247. }
  248. else
  249. {
  250. // Non-physical objects should be just meshes.
  251. BSShape potentialMesh = BSShapeMesh.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
  252. // If the current shape is not what is on the prim at the moment, time to change.
  253. if (!prim.PhysShape.HasPhysicalShape
  254. || potentialMesh.ShapeType != prim.PhysShape.ShapeType
  255. || potentialMesh.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
  256. {
  257. DereferenceExistingShape(prim, shapeCallback);
  258. prim.PhysShape = potentialMesh;
  259. ret = true;
  260. }
  261. else
  262. {
  263. // We don't need this reference to the mesh that is already being using.
  264. potentialMesh.Dereference(m_physicsScene);
  265. }
  266. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1}", prim.LocalID, prim.PhysShape);
  267. }
  268. return ret;
  269. }
  270. // Track another user of a body.
  271. // We presume the caller has allocated the body.
  272. // Bodies only have one user so the body is just put into the world if not already there.
  273. private void ReferenceBody(BulletBody body)
  274. {
  275. lock (m_collectionActivityLock)
  276. {
  277. if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body);
  278. if (!m_physicsScene.PE.IsInWorld(m_physicsScene.World, body))
  279. {
  280. m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, body);
  281. if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body);
  282. }
  283. }
  284. }
  285. // Release the usage of a body.
  286. // Called when releasing use of a BSBody. BSShape is handled separately.
  287. // Called in taint time.
  288. public void DereferenceBody(BulletBody body, PhysicalDestructionCallback bodyCallback )
  289. {
  290. if (!body.HasPhysicalBody)
  291. return;
  292. m_physicsScene.AssertInTaintTime("BSShapeCollection.DereferenceBody");
  293. lock (m_collectionActivityLock)
  294. {
  295. if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1}", body.ID, body);
  296. // If the caller needs to know the old body is going away, pass the event up.
  297. if (bodyCallback != null)
  298. bodyCallback(body, null);
  299. // Removing an object not in the world is a NOOP
  300. m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, body);
  301. // Zero any reference to the shape so it is not freed when the body is deleted.
  302. m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, body, null);
  303. m_physicsScene.PE.DestroyObject(m_physicsScene.World, body);
  304. }
  305. }
  306. // Create a body object in Bullet.
  307. // Updates prim.BSBody with the information about the new body if one is created.
  308. // Returns 'true' if an object was actually created.
  309. // Called at taint-time.
  310. private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletWorld sim, PhysicalDestructionCallback bodyCallback)
  311. {
  312. bool ret = false;
  313. // the mesh, hull or native shape must have already been created in Bullet
  314. bool mustRebuild = !prim.PhysBody.HasPhysicalBody;
  315. // If there is an existing body, verify it's of an acceptable type.
  316. // If not a solid object, body is a GhostObject. Otherwise a RigidBody.
  317. if (!mustRebuild)
  318. {
  319. CollisionObjectTypes bodyType = (CollisionObjectTypes)m_physicsScene.PE.GetBodyType(prim.PhysBody);
  320. if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY
  321. || !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT)
  322. {
  323. // If the collisionObject is not the correct type for solidness, rebuild what's there
  324. mustRebuild = true;
  325. if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,forceRebuildBecauseChangingBodyType,bodyType={1}", prim.LocalID, bodyType);
  326. }
  327. }
  328. if (mustRebuild || forceRebuild)
  329. {
  330. // Free any old body
  331. DereferenceBody(prim.PhysBody, bodyCallback);
  332. BulletBody aBody;
  333. if (prim.IsSolid)
  334. {
  335. aBody = m_physicsScene.PE.CreateBodyFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
  336. if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,rigid,body={1}", prim.LocalID, aBody);
  337. }
  338. else
  339. {
  340. aBody = m_physicsScene.PE.CreateGhostFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
  341. if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,ghost,body={1}", prim.LocalID, aBody);
  342. }
  343. ReferenceBody(aBody);
  344. prim.PhysBody = aBody;
  345. ret = true;
  346. }
  347. return ret;
  348. }
  349. private void DetailLog(string msg, params Object[] args)
  350. {
  351. if (m_physicsScene.PhysicsLogging.Enabled)
  352. m_physicsScene.DetailLog(msg, args);
  353. }
  354. }
  355. }