BSShapeCollection.cs 19 KB

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