BSShapeCollection.cs 19 KB

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