BSShapes.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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.PhysicsModules.SharedBase;
  32. using OpenSim.Region.PhysicsModules.Meshing;
  33. using OpenSim.Region.PhysicsModule.ConvexDecompositionDotNet;
  34. using OMV = OpenMetaverse;
  35. namespace OpenSim.Region.PhysicsModule.BulletS
  36. {
  37. // Information class that holds stats for the shape. Which values mean
  38. // something depends on the type of shape.
  39. // This information is used for debugging and stats and is not used
  40. // for operational things.
  41. public class ShapeInfoInfo
  42. {
  43. public int Vertices { get; set; }
  44. private int m_hullCount;
  45. private int[] m_verticesPerHull;
  46. public ShapeInfoInfo()
  47. {
  48. Vertices = 0;
  49. m_hullCount = 0;
  50. m_verticesPerHull = null;
  51. }
  52. public int HullCount
  53. {
  54. set
  55. {
  56. m_hullCount = value;
  57. m_verticesPerHull = new int[m_hullCount];
  58. Array.Clear(m_verticesPerHull, 0, m_hullCount);
  59. }
  60. get { return m_hullCount; }
  61. }
  62. public void SetVerticesPerHull(int hullNum, int vertices)
  63. {
  64. if (m_verticesPerHull != null && hullNum < m_verticesPerHull.Length)
  65. {
  66. m_verticesPerHull[hullNum] = vertices;
  67. }
  68. }
  69. public int GetVerticesPerHull(int hullNum)
  70. {
  71. if (m_verticesPerHull != null && hullNum < m_verticesPerHull.Length)
  72. {
  73. return m_verticesPerHull[hullNum];
  74. }
  75. return 0;
  76. }
  77. public override string ToString()
  78. {
  79. StringBuilder buff = new StringBuilder();
  80. // buff.Append("ShapeInfo=<");
  81. buff.Append("<");
  82. if (Vertices > 0)
  83. {
  84. buff.Append("verts=");
  85. buff.Append(Vertices.ToString());
  86. }
  87. if (Vertices > 0 && HullCount > 0) buff.Append(",");
  88. if (HullCount > 0)
  89. {
  90. buff.Append("nHulls=");
  91. buff.Append(HullCount.ToString());
  92. buff.Append(",");
  93. buff.Append("hullVerts=");
  94. for (int ii = 0; ii < HullCount; ii++)
  95. {
  96. if (ii != 0) buff.Append(",");
  97. buff.Append(GetVerticesPerHull(ii).ToString());
  98. }
  99. }
  100. buff.Append(">");
  101. return buff.ToString();
  102. }
  103. }
  104. public abstract class BSShape
  105. {
  106. private static string LogHeader = "[BULLETSIM SHAPE]";
  107. public int referenceCount { get; set; }
  108. public DateTime lastReferenced { get; set; }
  109. public BulletShape physShapeInfo { get; set; }
  110. public ShapeInfoInfo shapeInfo { get; private set; }
  111. public BSShape()
  112. {
  113. referenceCount = 1;
  114. lastReferenced = DateTime.Now;
  115. physShapeInfo = new BulletShape();
  116. shapeInfo = new ShapeInfoInfo();
  117. }
  118. public BSShape(BulletShape pShape)
  119. {
  120. referenceCount = 1;
  121. lastReferenced = DateTime.Now;
  122. physShapeInfo = pShape;
  123. shapeInfo = new ShapeInfoInfo();
  124. }
  125. // Get another reference to this shape.
  126. public abstract BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim);
  127. // Called when this shape is being used again.
  128. // Used internally. External callers should call instance.GetReference() to properly copy/reference
  129. // the shape.
  130. protected virtual void IncrementReference()
  131. {
  132. referenceCount++;
  133. lastReferenced = DateTime.Now;
  134. }
  135. // Called when this shape is done being used.
  136. protected virtual void DecrementReference()
  137. {
  138. referenceCount--;
  139. lastReferenced = DateTime.Now;
  140. }
  141. // Release the use of a physical shape.
  142. public abstract void Dereference(BSScene physicsScene);
  143. // Return 'true' if there is an allocated physics physical shape under this class instance.
  144. public virtual bool HasPhysicalShape
  145. {
  146. get
  147. {
  148. if (physShapeInfo != null)
  149. return physShapeInfo.HasPhysicalShape;
  150. return false;
  151. }
  152. }
  153. public virtual BSPhysicsShapeType ShapeType
  154. {
  155. get
  156. {
  157. BSPhysicsShapeType ret = BSPhysicsShapeType.SHAPE_UNKNOWN;
  158. if (physShapeInfo != null && physShapeInfo.HasPhysicalShape)
  159. ret = physShapeInfo.shapeType;
  160. return ret;
  161. }
  162. }
  163. // Returns a string for debugging that uniquily identifies the memory used by this instance
  164. public virtual string AddrString
  165. {
  166. get
  167. {
  168. if (physShapeInfo != null)
  169. return physShapeInfo.AddrString;
  170. return "unknown";
  171. }
  172. }
  173. public override string ToString()
  174. {
  175. StringBuilder buff = new StringBuilder();
  176. if (physShapeInfo == null)
  177. {
  178. buff.Append("<noPhys");
  179. }
  180. else
  181. {
  182. buff.Append("<phy=");
  183. buff.Append(physShapeInfo.ToString());
  184. }
  185. buff.Append(",c=");
  186. buff.Append(referenceCount.ToString());
  187. buff.Append(">");
  188. return buff.ToString();
  189. }
  190. #region Common shape routines
  191. // Create a hash of all the shape parameters to be used as a key for this particular shape.
  192. public static System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs, out float retLod)
  193. {
  194. // level of detail based on size and type of the object
  195. float lod = BSParam.MeshLOD;
  196. if (pbs.SculptEntry)
  197. lod = BSParam.SculptLOD;
  198. // Mega prims usually get more detail because one can interact with shape approximations at this size.
  199. float maxAxis = Math.Max(size.X, Math.Max(size.Y, size.Z));
  200. if (maxAxis > BSParam.MeshMegaPrimThreshold)
  201. lod = BSParam.MeshMegaPrimLOD;
  202. retLod = lod;
  203. return pbs.GetMeshKey(size, lod);
  204. }
  205. // The creation of a mesh or hull can fail if an underlying asset is not available.
  206. // There are two cases: 1) the asset is not in the cache and it needs to be fetched;
  207. // and 2) the asset cannot be converted (like failed decompression of JPEG2000s).
  208. // The first case causes the asset to be fetched. The second case requires
  209. // us to not loop forever.
  210. // Called after creating a physical mesh or hull. If the physical shape was created,
  211. // just return.
  212. public static BulletShape VerifyMeshCreated(BSScene physicsScene, BulletShape newShape, BSPhysObject prim)
  213. {
  214. // If the shape was successfully created, nothing more to do
  215. if (newShape.HasPhysicalShape)
  216. return newShape;
  217. // VerifyMeshCreated is called after trying to create the mesh. If we think the asset had been
  218. // fetched but we end up here again, the meshing of the asset must have failed.
  219. // Prevent trying to keep fetching the mesh by declaring failure.
  220. if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched)
  221. {
  222. prim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedMeshing;
  223. physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. prim={1}, texture={2}",
  224. LogHeader, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture);
  225. physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,setFailed,prim={1},tex={2}",
  226. prim.LocalID, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture);
  227. }
  228. else
  229. {
  230. // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset
  231. if (prim.BaseShape.SculptEntry
  232. && !prim.AssetFailed()
  233. && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Waiting
  234. && prim.BaseShape.SculptTexture != OMV.UUID.Zero
  235. )
  236. {
  237. physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,fetchAsset,objNam={1},tex={2}",
  238. prim.LocalID, prim.PhysObjectName, prim.BaseShape.SculptTexture);
  239. // Multiple requestors will know we're waiting for this asset
  240. prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Waiting;
  241. BSPhysObject xprim = prim;
  242. RequestAssetDelegate assetProvider = physicsScene.RequestAssetMethod;
  243. if (assetProvider != null)
  244. {
  245. BSPhysObject yprim = xprim; // probably not necessary, but, just in case.
  246. assetProvider(yprim.BaseShape.SculptTexture, delegate(AssetBase asset)
  247. {
  248. // physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,assetProviderCallback", xprim.LocalID);
  249. bool assetFound = false;
  250. string mismatchIDs = String.Empty; // DEBUG DEBUG
  251. if (asset != null && yprim.BaseShape.SculptEntry)
  252. {
  253. if (yprim.BaseShape.SculptTexture.ToString() == asset.ID)
  254. {
  255. yprim.BaseShape.SculptData = asset.Data;
  256. // This will cause the prim to see that the filler shape is not the right
  257. // one and try again to build the object.
  258. // No race condition with the normal shape setting since the rebuild is at taint time.
  259. yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Fetched;
  260. yprim.ForceBodyShapeRebuild(false /* inTaintTime */);
  261. assetFound = true;
  262. }
  263. else
  264. {
  265. mismatchIDs = yprim.BaseShape.SculptTexture.ToString() + "/" + asset.ID;
  266. }
  267. }
  268. if (!assetFound)
  269. {
  270. yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedAssetFetch;
  271. }
  272. physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,fetchAssetCallback,found={1},isSculpt={2},ids={3}",
  273. yprim.LocalID, assetFound, yprim.BaseShape.SculptEntry, mismatchIDs );
  274. });
  275. }
  276. else
  277. {
  278. xprim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedAssetFetch;
  279. physicsScene.Logger.ErrorFormat("{0} Physical object requires asset but no asset provider. Name={1}",
  280. LogHeader, physicsScene.PhysicsSceneName);
  281. }
  282. }
  283. else
  284. {
  285. if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedAssetFetch)
  286. {
  287. physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. prim={1}, texture={2}",
  288. LogHeader, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture);
  289. physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailed,prim={1},tex={2}",
  290. prim.LocalID, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture);
  291. }
  292. if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedMeshing)
  293. {
  294. physicsScene.Logger.WarnFormat("{0} Mesh asset would not mesh. prim={1}, texture={2}",
  295. LogHeader, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture);
  296. physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailedMeshing,prim={1},tex={2}",
  297. prim.LocalID, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture);
  298. }
  299. }
  300. }
  301. // While we wait for the mesh defining asset to be loaded, stick in a simple box for the object.
  302. BSShape fillShape = BSShapeNative.GetReference(physicsScene, prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
  303. physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,boxTempShape", prim.LocalID);
  304. return fillShape.physShapeInfo;
  305. }
  306. public static String UsefulPrimInfo(BSScene pScene, BSPhysObject prim)
  307. {
  308. StringBuilder buff = new StringBuilder(prim.PhysObjectName);
  309. buff.Append("/pos=");
  310. buff.Append(prim.RawPosition.ToString());
  311. if (pScene != null)
  312. {
  313. buff.Append("/rgn=");
  314. buff.Append(pScene.PhysicsSceneName);
  315. }
  316. return buff.ToString();
  317. }
  318. #endregion // Common shape routines
  319. }
  320. // ============================================================================================================
  321. public class BSShapeNull : BSShape
  322. {
  323. public BSShapeNull() : base()
  324. {
  325. }
  326. public static BSShape GetReference() { return new BSShapeNull(); }
  327. public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) { return new BSShapeNull(); }
  328. public override void Dereference(BSScene physicsScene) { /* The magic of garbage collection will make this go away */ }
  329. }
  330. // ============================================================================================================
  331. // BSShapeNative is a wrapper for a Bullet 'native' shape -- cube and sphere.
  332. // They are odd in that they don't allocate meshes but are computated/procedural.
  333. // This means allocation and freeing is different than meshes.
  334. public class BSShapeNative : BSShape
  335. {
  336. private static string LogHeader = "[BULLETSIM SHAPE NATIVE]";
  337. public BSShapeNative(BulletShape pShape) : base(pShape)
  338. {
  339. }
  340. public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim,
  341. BSPhysicsShapeType shapeType, FixedShapeKey shapeKey)
  342. {
  343. // Native shapes are not shared and are always built anew.
  344. return new BSShapeNative(CreatePhysicalNativeShape(physicsScene, prim, shapeType, shapeKey));
  345. }
  346. public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim)
  347. {
  348. // Native shapes are not shared so we return a new shape.
  349. BSShape ret = null;
  350. lock (physShapeInfo)
  351. {
  352. ret = new BSShapeNative(CreatePhysicalNativeShape(pPhysicsScene, pPrim,
  353. physShapeInfo.shapeType, (FixedShapeKey)physShapeInfo.shapeKey));
  354. }
  355. return ret;
  356. }
  357. // Make this reference to the physical shape go away since native shapes are not shared.
  358. public override void Dereference(BSScene physicsScene)
  359. {
  360. // Native shapes are not tracked and are released immediately
  361. lock (physShapeInfo)
  362. {
  363. if (physShapeInfo.HasPhysicalShape)
  364. {
  365. physicsScene.DetailLog("{0},BSShapeNative.Dereference,deleteNativeShape,shape={1}", BSScene.DetailLogZero, this);
  366. physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo);
  367. }
  368. physShapeInfo.Clear();
  369. // Garbage collection will free up this instance.
  370. }
  371. }
  372. private static BulletShape CreatePhysicalNativeShape(BSScene physicsScene, BSPhysObject prim,
  373. BSPhysicsShapeType shapeType, FixedShapeKey shapeKey)
  374. {
  375. BulletShape newShape;
  376. ShapeData nativeShapeData = new ShapeData();
  377. nativeShapeData.Type = shapeType;
  378. nativeShapeData.ID = prim.LocalID;
  379. nativeShapeData.Scale = prim.Scale;
  380. nativeShapeData.Size = prim.Scale;
  381. nativeShapeData.MeshKey = (ulong)shapeKey;
  382. nativeShapeData.HullKey = (ulong)shapeKey;
  383. if (shapeType == BSPhysicsShapeType.SHAPE_CAPSULE)
  384. {
  385. newShape = physicsScene.PE.BuildCapsuleShape(physicsScene.World, 1f, 1f, prim.Scale);
  386. physicsScene.DetailLog("{0},BSShapeNative,capsule,scale={1}", prim.LocalID, prim.Scale);
  387. }
  388. else
  389. {
  390. newShape = physicsScene.PE.BuildNativeShape(physicsScene.World, nativeShapeData);
  391. }
  392. if (!newShape.HasPhysicalShape)
  393. {
  394. physicsScene.Logger.ErrorFormat("{0} BuildPhysicalNativeShape failed. ID={1}, shape={2}",
  395. LogHeader, prim.LocalID, shapeType);
  396. }
  397. newShape.shapeType = shapeType;
  398. newShape.isNativeShape = true;
  399. newShape.shapeKey = (UInt64)shapeKey;
  400. return newShape;
  401. }
  402. }
  403. // ============================================================================================================
  404. // BSShapeMesh is a simple mesh.
  405. public class BSShapeMesh : BSShape
  406. {
  407. private static string LogHeader = "[BULLETSIM SHAPE MESH]";
  408. public static Dictionary<System.UInt64, BSShapeMesh> Meshes = new Dictionary<System.UInt64, BSShapeMesh>();
  409. public BSShapeMesh(BulletShape pShape) : base(pShape)
  410. {
  411. }
  412. public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim)
  413. {
  414. float lod;
  415. System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod);
  416. BSShapeMesh retMesh = null;
  417. lock (Meshes)
  418. {
  419. if (Meshes.TryGetValue(newMeshKey, out retMesh))
  420. {
  421. // The mesh has already been created. Return a new reference to same.
  422. retMesh.IncrementReference();
  423. }
  424. else
  425. {
  426. retMesh = new BSShapeMesh(new BulletShape());
  427. // An instance of this mesh has not been created. Build and remember same.
  428. BulletShape newShape = retMesh.CreatePhysicalMesh(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod);
  429. // Check to see if mesh was created (might require an asset).
  430. newShape = VerifyMeshCreated(physicsScene, newShape, prim);
  431. if (!newShape.isNativeShape || prim.AssetFailed() )
  432. {
  433. // If a mesh was what was created, remember the built shape for later sharing.
  434. // Also note that if meshing failed we put it in the mesh list as there is nothing else to do about the mesh.
  435. Meshes.Add(newMeshKey, retMesh);
  436. }
  437. retMesh.physShapeInfo = newShape;
  438. }
  439. }
  440. physicsScene.DetailLog("{0},BSShapeMesh,getReference,mesh={1},size={2},lod={3}", prim.LocalID, retMesh, prim.Size, lod);
  441. return retMesh;
  442. }
  443. public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim)
  444. {
  445. BSShape ret = null;
  446. // If the underlying shape is native, the actual shape has not been build (waiting for asset)
  447. // and we must create a copy of the native shape since they are never shared.
  448. if (physShapeInfo.HasPhysicalShape && physShapeInfo.isNativeShape)
  449. {
  450. // TODO: decide when the native shapes should be freed. Check in Dereference?
  451. ret = BSShapeNative.GetReference(pPhysicsScene, pPrim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
  452. }
  453. else
  454. {
  455. // Another reference to this shape is just counted.
  456. IncrementReference();
  457. ret = this;
  458. }
  459. return ret;
  460. }
  461. public override void Dereference(BSScene physicsScene)
  462. {
  463. lock (Meshes)
  464. {
  465. this.DecrementReference();
  466. physicsScene.DetailLog("{0},BSShapeMesh.Dereference,shape={1}", BSScene.DetailLogZero, this);
  467. // TODO: schedule aging and destruction of unused meshes.
  468. }
  469. }
  470. // Loop through all the known meshes and return the description based on the physical address.
  471. public static bool TryGetMeshByPtr(BulletShape pShape, out BSShapeMesh outMesh)
  472. {
  473. bool ret = false;
  474. BSShapeMesh foundDesc = null;
  475. lock (Meshes)
  476. {
  477. foreach (BSShapeMesh sm in Meshes.Values)
  478. {
  479. if (sm.physShapeInfo.ReferenceSame(pShape))
  480. {
  481. foundDesc = sm;
  482. ret = true;
  483. break;
  484. }
  485. }
  486. }
  487. outMesh = foundDesc;
  488. return ret;
  489. }
  490. public delegate BulletShape CreateShapeCall(BulletWorld world, int indicesCount, int[] indices, int verticesCount, float[] vertices );
  491. private BulletShape CreatePhysicalMesh(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey,
  492. PrimitiveBaseShape pbs, OMV.Vector3 size, float lod)
  493. {
  494. return BSShapeMesh.CreatePhysicalMeshShape(physicsScene, prim, newMeshKey, pbs, size, lod,
  495. (w, iC, i, vC, v) =>
  496. {
  497. shapeInfo.Vertices = vC;
  498. return physicsScene.PE.CreateMeshShape(w, iC, i, vC, v);
  499. });
  500. }
  501. // Code that uses the mesher to create the index/vertices info for a trimesh shape.
  502. // This is used by the passed 'makeShape' call to create the Bullet mesh shape.
  503. // The actual build call is passed so this logic can be used by several of the shapes that use a
  504. // simple mesh as their base shape.
  505. public static BulletShape CreatePhysicalMeshShape(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey,
  506. PrimitiveBaseShape pbs, OMV.Vector3 size, float lod, CreateShapeCall makeShape)
  507. {
  508. BulletShape newShape = new BulletShape();
  509. IMesh meshData = null;
  510. lock (physicsScene.mesher)
  511. {
  512. meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod,
  513. false, // say it is not physical so a bounding box is not built
  514. false // do not cache the mesh and do not use previously built versions
  515. );
  516. }
  517. if (meshData != null)
  518. {
  519. if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched)
  520. {
  521. // Release the fetched asset data once it has been used.
  522. pbs.SculptData = new byte[0];
  523. prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown;
  524. }
  525. int[] indices = meshData.getIndexListAsInt();
  526. int realIndicesIndex = indices.Length;
  527. float[] verticesAsFloats = meshData.getVertexListAsFloat();
  528. if (BSParam.ShouldRemoveZeroWidthTriangles)
  529. {
  530. // Remove degenerate triangles. These are triangles with two of the vertices
  531. // are the same. This is complicated by the problem that vertices are not
  532. // made unique in sculpties so we have to compare the values in the vertex.
  533. realIndicesIndex = 0;
  534. for (int tri = 0; tri < indices.Length; tri += 3)
  535. {
  536. // Compute displacements into vertex array for each vertex of the triangle
  537. int v1 = indices[tri + 0] * 3;
  538. int v2 = indices[tri + 1] * 3;
  539. int v3 = indices[tri + 2] * 3;
  540. // Check to see if any two of the vertices are the same
  541. if (!( ( verticesAsFloats[v1 + 0] == verticesAsFloats[v2 + 0]
  542. && verticesAsFloats[v1 + 1] == verticesAsFloats[v2 + 1]
  543. && verticesAsFloats[v1 + 2] == verticesAsFloats[v2 + 2])
  544. || ( verticesAsFloats[v2 + 0] == verticesAsFloats[v3 + 0]
  545. && verticesAsFloats[v2 + 1] == verticesAsFloats[v3 + 1]
  546. && verticesAsFloats[v2 + 2] == verticesAsFloats[v3 + 2])
  547. || ( verticesAsFloats[v1 + 0] == verticesAsFloats[v3 + 0]
  548. && verticesAsFloats[v1 + 1] == verticesAsFloats[v3 + 1]
  549. && verticesAsFloats[v1 + 2] == verticesAsFloats[v3 + 2]) )
  550. )
  551. {
  552. // None of the vertices of the triangles are the same. This is a good triangle;
  553. indices[realIndicesIndex + 0] = indices[tri + 0];
  554. indices[realIndicesIndex + 1] = indices[tri + 1];
  555. indices[realIndicesIndex + 2] = indices[tri + 2];
  556. realIndicesIndex += 3;
  557. }
  558. }
  559. }
  560. physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,key={1},origTri={2},realTri={3},numVerts={4}",
  561. BSScene.DetailLogZero, newMeshKey.ToString("X"), indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3);
  562. if (realIndicesIndex != 0)
  563. {
  564. newShape = makeShape(physicsScene.World, realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats);
  565. }
  566. else
  567. {
  568. // Force the asset condition to 'failed' so we won't try to keep fetching and processing this mesh.
  569. prim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedMeshing;
  570. physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim={1}", LogHeader, UsefulPrimInfo(physicsScene, prim) );
  571. physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,allDegenerate,key={1}", prim.LocalID, newMeshKey);
  572. }
  573. }
  574. newShape.shapeKey = newMeshKey;
  575. return newShape;
  576. }
  577. }
  578. // ============================================================================================================
  579. // BSShapeHull is a physical shape representation htat is made up of many convex hulls.
  580. // The convex hulls are either supplied with the asset or are approximated by one of the
  581. // convex hull creation routines (in OpenSim or in Bullet).
  582. public class BSShapeHull : BSShape
  583. {
  584. #pragma warning disable 414
  585. private static string LogHeader = "[BULLETSIM SHAPE HULL]";
  586. #pragma warning restore 414
  587. public static Dictionary<System.UInt64, BSShapeHull> Hulls = new Dictionary<System.UInt64, BSShapeHull>();
  588. public BSShapeHull(BulletShape pShape) : base(pShape)
  589. {
  590. }
  591. public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim)
  592. {
  593. float lod;
  594. System.UInt64 newHullKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod);
  595. BSShapeHull retHull = null;
  596. lock (Hulls)
  597. {
  598. if (Hulls.TryGetValue(newHullKey, out retHull))
  599. {
  600. // The mesh has already been created. Return a new reference to same.
  601. retHull.IncrementReference();
  602. }
  603. else
  604. {
  605. retHull = new BSShapeHull(new BulletShape());
  606. // An instance of this mesh has not been created. Build and remember same.
  607. BulletShape newShape = retHull.CreatePhysicalHull(physicsScene, prim, newHullKey, prim.BaseShape, prim.Size, lod);
  608. // Check to see if hull was created (might require an asset).
  609. newShape = VerifyMeshCreated(physicsScene, newShape, prim);
  610. if (!newShape.isNativeShape || prim.AssetFailed())
  611. {
  612. // If a mesh was what was created, remember the built shape for later sharing.
  613. Hulls.Add(newHullKey, retHull);
  614. }
  615. retHull.physShapeInfo = newShape;
  616. }
  617. }
  618. physicsScene.DetailLog("{0},BSShapeHull,getReference,hull={1},size={2},lod={3}", prim.LocalID, retHull, prim.Size, lod);
  619. return retHull;
  620. }
  621. public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim)
  622. {
  623. BSShape ret = null;
  624. // If the underlying shape is native, the actual shape has not been build (waiting for asset)
  625. // and we must create a copy of the native shape since they are never shared.
  626. if (physShapeInfo.HasPhysicalShape && physShapeInfo.isNativeShape)
  627. {
  628. // TODO: decide when the native shapes should be freed. Check in Dereference?
  629. ret = BSShapeNative.GetReference(pPhysicsScene, pPrim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
  630. }
  631. else
  632. {
  633. // Another reference to this shape is just counted.
  634. IncrementReference();
  635. ret = this;
  636. }
  637. return ret;
  638. }
  639. public override void Dereference(BSScene physicsScene)
  640. {
  641. lock (Hulls)
  642. {
  643. this.DecrementReference();
  644. physicsScene.DetailLog("{0},BSShapeHull.Dereference,shape={1}", BSScene.DetailLogZero, this);
  645. // TODO: schedule aging and destruction of unused meshes.
  646. }
  647. }
  648. List<ConvexResult> m_hulls;
  649. private BulletShape CreatePhysicalHull(BSScene physicsScene, BSPhysObject prim, System.UInt64 newHullKey,
  650. PrimitiveBaseShape pbs, OMV.Vector3 size, float lod)
  651. {
  652. BulletShape newShape = new BulletShape();
  653. IMesh meshData = null;
  654. List<List<OMV.Vector3>> allHulls = null;
  655. lock (physicsScene.mesher)
  656. {
  657. // Pass true for physicalness as this prevents the creation of bounding box which is not needed
  658. meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */);
  659. // If we should use the asset's hull info, fetch it out of the locked mesher
  660. if (meshData != null && BSParam.ShouldUseAssetHulls)
  661. {
  662. Meshmerizer realMesher = physicsScene.mesher as Meshmerizer;
  663. if (realMesher != null)
  664. {
  665. allHulls = realMesher.GetConvexHulls(size);
  666. }
  667. if (allHulls == null)
  668. {
  669. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,assetHulls,noAssetHull", prim.LocalID);
  670. }
  671. }
  672. }
  673. // If there is hull data in the mesh asset, build the hull from that
  674. if (allHulls != null && BSParam.ShouldUseAssetHulls)
  675. {
  676. int hullCount = allHulls.Count;
  677. shapeInfo.HullCount = hullCount;
  678. int totalVertices = 1; // include one for the count of the hulls
  679. // Using the structure described for HACD hulls, create the memory sturcture
  680. // to pass the hull data to the creater.
  681. foreach (List<OMV.Vector3> hullVerts in allHulls)
  682. {
  683. totalVertices += 4; // add four for the vertex count and centroid
  684. totalVertices += hullVerts.Count * 3; // one vertex is three dimensions
  685. }
  686. float[] convHulls = new float[totalVertices];
  687. convHulls[0] = (float)hullCount;
  688. int jj = 1;
  689. int hullIndex = 0;
  690. foreach (List<OMV.Vector3> hullVerts in allHulls)
  691. {
  692. convHulls[jj + 0] = hullVerts.Count;
  693. convHulls[jj + 1] = 0f; // centroid x,y,z
  694. convHulls[jj + 2] = 0f;
  695. convHulls[jj + 3] = 0f;
  696. jj += 4;
  697. foreach (OMV.Vector3 oneVert in hullVerts)
  698. {
  699. convHulls[jj + 0] = oneVert.X;
  700. convHulls[jj + 1] = oneVert.Y;
  701. convHulls[jj + 2] = oneVert.Z;
  702. jj += 3;
  703. }
  704. shapeInfo.SetVerticesPerHull(hullIndex, hullVerts.Count);
  705. hullIndex++;
  706. }
  707. // create the hull data structure in Bullet
  708. newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls);
  709. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,assetHulls,hulls={1},totVert={2},shape={3}",
  710. prim.LocalID, hullCount, totalVertices, newShape);
  711. }
  712. // If no hull specified in the asset and we should use Bullet's HACD approximation...
  713. if (!newShape.HasPhysicalShape && BSParam.ShouldUseBulletHACD)
  714. {
  715. // Build the hull shape from an existing mesh shape.
  716. // The mesh should have already been created in Bullet.
  717. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,bulletHACD,entry", prim.LocalID);
  718. BSShape meshShape = BSShapeMesh.GetReference(physicsScene, true, prim);
  719. if (meshShape.physShapeInfo.HasPhysicalShape)
  720. {
  721. HACDParams parms = new HACDParams();
  722. parms.maxVerticesPerHull = BSParam.BHullMaxVerticesPerHull;
  723. parms.minClusters = BSParam.BHullMinClusters;
  724. parms.compacityWeight = BSParam.BHullCompacityWeight;
  725. parms.volumeWeight = BSParam.BHullVolumeWeight;
  726. parms.concavity = BSParam.BHullConcavity;
  727. parms.addExtraDistPoints = BSParam.NumericBool(BSParam.BHullAddExtraDistPoints);
  728. parms.addNeighboursDistPoints = BSParam.NumericBool(BSParam.BHullAddNeighboursDistPoints);
  729. parms.addFacesPoints = BSParam.NumericBool(BSParam.BHullAddFacesPoints);
  730. parms.shouldAdjustCollisionMargin = BSParam.NumericBool(BSParam.BHullShouldAdjustCollisionMargin);
  731. parms.whichHACD = 0; // Use the HACD routine that comes with Bullet
  732. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,beforeCall", prim.LocalID, newShape.HasPhysicalShape);
  733. newShape = physicsScene.PE.BuildHullShapeFromMesh(physicsScene.World, meshShape.physShapeInfo, parms);
  734. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,shape={1}", prim.LocalID, newShape);
  735. // Now done with the mesh shape.
  736. shapeInfo.HullCount = 1;
  737. BSShapeMesh maybeMesh = meshShape as BSShapeMesh;
  738. if (maybeMesh != null)
  739. shapeInfo.SetVerticesPerHull(0, maybeMesh.shapeInfo.Vertices);
  740. meshShape.Dereference(physicsScene);
  741. }
  742. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,bulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape);
  743. }
  744. // If no other hull specifications, use our HACD hull approximation.
  745. if (!newShape.HasPhysicalShape && meshData != null)
  746. {
  747. if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched)
  748. {
  749. // Release the fetched asset data once it has been used.
  750. pbs.SculptData = new byte[0];
  751. prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown;
  752. }
  753. int[] indices = meshData.getIndexListAsInt();
  754. List<OMV.Vector3> vertices = meshData.getVertexList();
  755. //format conversion from IMesh format to DecompDesc format
  756. List<int> convIndices = new List<int>();
  757. List<float3> convVertices = new List<float3>();
  758. for (int ii = 0; ii < indices.GetLength(0); ii++)
  759. {
  760. convIndices.Add(indices[ii]);
  761. }
  762. foreach (OMV.Vector3 vv in vertices)
  763. {
  764. convVertices.Add(new float3(vv.X, vv.Y, vv.Z));
  765. }
  766. uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit;
  767. if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes)
  768. {
  769. // Simple primitive shapes we know are convex so they are better implemented with
  770. // fewer hulls.
  771. // Check for simple shape (prim without cuts) and reduce split parameter if so.
  772. if (BSShapeCollection.PrimHasNoCuts(pbs))
  773. {
  774. maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes;
  775. }
  776. }
  777. // setup and do convex hull conversion
  778. m_hulls = new List<ConvexResult>();
  779. DecompDesc dcomp = new DecompDesc();
  780. dcomp.mIndices = convIndices;
  781. dcomp.mVertices = convVertices;
  782. dcomp.mDepth = maxDepthSplit;
  783. dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent;
  784. dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent;
  785. dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices;
  786. dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth;
  787. ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn);
  788. // create the hull into the _hulls variable
  789. convexBuilder.process(dcomp);
  790. physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}",
  791. BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count);
  792. // Convert the vertices and indices for passing to unmanaged.
  793. // The hull information is passed as a large floating point array.
  794. // The format is:
  795. // convHulls[0] = number of hulls
  796. // convHulls[1] = number of vertices in first hull
  797. // convHulls[2] = hull centroid X coordinate
  798. // convHulls[3] = hull centroid Y coordinate
  799. // convHulls[4] = hull centroid Z coordinate
  800. // convHulls[5] = first hull vertex X
  801. // convHulls[6] = first hull vertex Y
  802. // convHulls[7] = first hull vertex Z
  803. // convHulls[8] = second hull vertex X
  804. // ...
  805. // convHulls[n] = number of vertices in second hull
  806. // convHulls[n+1] = second hull centroid X coordinate
  807. // ...
  808. //
  809. // TODO: is is very inefficient. Someday change the convex hull generator to return
  810. // data structures that do not need to be converted in order to pass to Bullet.
  811. // And maybe put the values directly into pinned memory rather than marshaling.
  812. int hullCount = m_hulls.Count;
  813. int totalVertices = 1; // include one for the count of the hulls
  814. foreach (ConvexResult cr in m_hulls)
  815. {
  816. totalVertices += 4; // add four for the vertex count and centroid
  817. totalVertices += cr.HullIndices.Count * 3; // we pass just triangles
  818. }
  819. float[] convHulls = new float[totalVertices];
  820. convHulls[0] = (float)hullCount;
  821. int jj = 1;
  822. foreach (ConvexResult cr in m_hulls)
  823. {
  824. // copy vertices for index access
  825. float3[] verts = new float3[cr.HullVertices.Count];
  826. int kk = 0;
  827. foreach (float3 ff in cr.HullVertices)
  828. {
  829. verts[kk++] = ff;
  830. }
  831. // add to the array one hull's worth of data
  832. convHulls[jj++] = cr.HullIndices.Count;
  833. convHulls[jj++] = 0f; // centroid x,y,z
  834. convHulls[jj++] = 0f;
  835. convHulls[jj++] = 0f;
  836. foreach (int ind in cr.HullIndices)
  837. {
  838. convHulls[jj++] = verts[ind].x;
  839. convHulls[jj++] = verts[ind].y;
  840. convHulls[jj++] = verts[ind].z;
  841. }
  842. }
  843. // create the hull data structure in Bullet
  844. newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls);
  845. }
  846. newShape.shapeKey = newHullKey;
  847. return newShape;
  848. }
  849. // Callback from convex hull creater with a newly created hull.
  850. // Just add it to our collection of hulls for this shape.
  851. private void HullReturn(ConvexResult result)
  852. {
  853. m_hulls.Add(result);
  854. return;
  855. }
  856. // Loop through all the known hulls and return the description based on the physical address.
  857. public static bool TryGetHullByPtr(BulletShape pShape, out BSShapeHull outHull)
  858. {
  859. bool ret = false;
  860. BSShapeHull foundDesc = null;
  861. lock (Hulls)
  862. {
  863. foreach (BSShapeHull sh in Hulls.Values)
  864. {
  865. if (sh.physShapeInfo.ReferenceSame(pShape))
  866. {
  867. foundDesc = sh;
  868. ret = true;
  869. break;
  870. }
  871. }
  872. }
  873. outHull = foundDesc;
  874. return ret;
  875. }
  876. }
  877. // ============================================================================================================
  878. // BSShapeCompound is a wrapper for the Bullet compound shape which is built from multiple, separate
  879. // meshes. Used by BulletSim for complex shapes like linksets.
  880. public class BSShapeCompound : BSShape
  881. {
  882. private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]";
  883. public static Dictionary<string, BSShapeCompound> CompoundShapes = new Dictionary<string, BSShapeCompound>();
  884. public BSShapeCompound(BulletShape pShape) : base(pShape)
  885. {
  886. }
  887. public static BSShape GetReference(BSScene physicsScene)
  888. {
  889. // Base compound shapes are not shared so this returns a raw shape.
  890. // A built compound shape can be reused in linksets.
  891. BSShapeCompound ret = new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene));
  892. CompoundShapes.Add(ret.AddrString, ret);
  893. return ret;
  894. }
  895. public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim)
  896. {
  897. // Calling this reference means we want another handle to an existing compound shape
  898. // (usually linksets) so return this copy.
  899. IncrementReference();
  900. return this;
  901. }
  902. // Dereferencing a compound shape releases the hold on all the child shapes.
  903. public override void Dereference(BSScene physicsScene)
  904. {
  905. lock (physShapeInfo)
  906. {
  907. this.DecrementReference();
  908. physicsScene.DetailLog("{0},BSShapeCompound.Dereference,shape={1}", BSScene.DetailLogZero, this);
  909. if (referenceCount <= 0)
  910. {
  911. if (!physicsScene.PE.IsCompound(physShapeInfo))
  912. {
  913. // Failed the sanity check!!
  914. physicsScene.Logger.ErrorFormat("{0} Attempt to free a compound shape that is not compound!! type={1}, ptr={2}",
  915. LogHeader, physShapeInfo.shapeType, physShapeInfo.AddrString);
  916. physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}",
  917. BSScene.DetailLogZero, physShapeInfo.shapeType, physShapeInfo.AddrString);
  918. return;
  919. }
  920. int numChildren = physicsScene.PE.GetNumberOfCompoundChildren(physShapeInfo);
  921. physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,shape={1},children={2}",
  922. BSScene.DetailLogZero, physShapeInfo, numChildren);
  923. // Loop through all the children dereferencing each.
  924. for (int ii = numChildren - 1; ii >= 0; ii--)
  925. {
  926. BulletShape childShape = physicsScene.PE.RemoveChildShapeFromCompoundShapeIndex(physShapeInfo, ii);
  927. DereferenceAnonCollisionShape(physicsScene, childShape);
  928. }
  929. lock (CompoundShapes)
  930. CompoundShapes.Remove(physShapeInfo.AddrString);
  931. physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo);
  932. }
  933. }
  934. }
  935. public static bool TryGetCompoundByPtr(BulletShape pShape, out BSShapeCompound outCompound)
  936. {
  937. lock (CompoundShapes)
  938. {
  939. string addr = pShape.AddrString;
  940. return CompoundShapes.TryGetValue(addr, out outCompound);
  941. }
  942. }
  943. private static BulletShape CreatePhysicalCompoundShape(BSScene physicsScene)
  944. {
  945. BulletShape cShape = physicsScene.PE.CreateCompoundShape(physicsScene.World, false);
  946. return cShape;
  947. }
  948. // Sometimes we have a pointer to a collision shape but don't know what type it is.
  949. // Figure out type and call the correct dereference routine.
  950. // Called at taint-time.
  951. private void DereferenceAnonCollisionShape(BSScene physicsScene, BulletShape pShape)
  952. {
  953. // TODO: figure a better way to go through all the shape types and find a possible instance.
  954. physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,shape={1}",
  955. BSScene.DetailLogZero, pShape);
  956. BSShapeMesh meshDesc;
  957. if (BSShapeMesh.TryGetMeshByPtr(pShape, out meshDesc))
  958. {
  959. meshDesc.Dereference(physicsScene);
  960. // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundMesh,shape={1}", BSScene.DetailLogZero, pShape);
  961. }
  962. else
  963. {
  964. BSShapeHull hullDesc;
  965. if (BSShapeHull.TryGetHullByPtr(pShape, out hullDesc))
  966. {
  967. hullDesc.Dereference(physicsScene);
  968. // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundHull,shape={1}", BSScene.DetailLogZero, pShape);
  969. }
  970. else
  971. {
  972. BSShapeConvexHull chullDesc;
  973. if (BSShapeConvexHull.TryGetConvexHullByPtr(pShape, out chullDesc))
  974. {
  975. chullDesc.Dereference(physicsScene);
  976. // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundConvexHull,shape={1}", BSScene.DetailLogZero, pShape);
  977. }
  978. else
  979. {
  980. BSShapeGImpact gImpactDesc;
  981. if (BSShapeGImpact.TryGetGImpactByPtr(pShape, out gImpactDesc))
  982. {
  983. gImpactDesc.Dereference(physicsScene);
  984. // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundgImpact,shape={1}", BSScene.DetailLogZero, pShape);
  985. }
  986. else
  987. {
  988. // Didn't find it in the lists of specific types. It could be compound.
  989. BSShapeCompound compoundDesc;
  990. if (BSShapeCompound.TryGetCompoundByPtr(pShape, out compoundDesc))
  991. {
  992. compoundDesc.Dereference(physicsScene);
  993. // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,recursiveCompoundShape,shape={1}", BSScene.DetailLogZero, pShape);
  994. }
  995. else
  996. {
  997. // If none of the above, maybe it is a simple native shape.
  998. if (physicsScene.PE.IsNativeShape(pShape))
  999. {
  1000. // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,assumingNative,shape={1}", BSScene.DetailLogZero, pShape);
  1001. BSShapeNative nativeShape = new BSShapeNative(pShape);
  1002. nativeShape.Dereference(physicsScene);
  1003. }
  1004. else
  1005. {
  1006. physicsScene.Logger.WarnFormat("{0} DereferenceAnonCollisionShape. Did not find shape. {1}",
  1007. LogHeader, pShape);
  1008. }
  1009. }
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. // ============================================================================================================
  1017. // BSShapeConvexHull is a wrapper for a Bullet single convex hull. A BSShapeHull contains multiple convex
  1018. // hull shapes. This is used for simple prims that are convex and thus can be made into a simple
  1019. // collision shape (a single hull). More complex physical shapes will be BSShapeHull's.
  1020. public class BSShapeConvexHull : BSShape
  1021. {
  1022. #pragma warning disable 414
  1023. private static string LogHeader = "[BULLETSIM SHAPE CONVEX HULL]";
  1024. #pragma warning restore 414
  1025. public static Dictionary<System.UInt64, BSShapeConvexHull> ConvexHulls = new Dictionary<System.UInt64, BSShapeConvexHull>();
  1026. public BSShapeConvexHull(BulletShape pShape) : base(pShape)
  1027. {
  1028. }
  1029. public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim)
  1030. {
  1031. float lod;
  1032. System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod);
  1033. physicsScene.DetailLog("{0},BSShapeConvexHull,getReference,newKey={1},size={2},lod={3}",
  1034. prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod);
  1035. BSShapeConvexHull retConvexHull = null;
  1036. lock (ConvexHulls)
  1037. {
  1038. if (ConvexHulls.TryGetValue(newMeshKey, out retConvexHull))
  1039. {
  1040. // The mesh has already been created. Return a new reference to same.
  1041. retConvexHull.IncrementReference();
  1042. }
  1043. else
  1044. {
  1045. retConvexHull = new BSShapeConvexHull(new BulletShape());
  1046. BulletShape convexShape = null;
  1047. // Get a handle to a mesh to build the hull from
  1048. BSShape baseMesh = BSShapeMesh.GetReference(physicsScene, false /* forceRebuild */, prim);
  1049. if (baseMesh.physShapeInfo.isNativeShape)
  1050. {
  1051. // We get here if the mesh was not creatable. Could be waiting for an asset from the disk.
  1052. // In the short term, we return the native shape and a later ForceBodyShapeRebuild should
  1053. // get back to this code with a buildable mesh.
  1054. // TODO: not sure the temp native shape is freed when the mesh is rebuilt. When does this get freed?
  1055. convexShape = baseMesh.physShapeInfo;
  1056. }
  1057. else
  1058. {
  1059. convexShape = physicsScene.PE.BuildConvexHullShapeFromMesh(physicsScene.World, baseMesh.physShapeInfo);
  1060. convexShape.shapeKey = newMeshKey;
  1061. ConvexHulls.Add(convexShape.shapeKey, retConvexHull);
  1062. physicsScene.DetailLog("{0},BSShapeConvexHull.GetReference,addingNewlyCreatedShape,shape={1}",
  1063. BSScene.DetailLogZero, convexShape);
  1064. }
  1065. // Done with the base mesh
  1066. baseMesh.Dereference(physicsScene);
  1067. retConvexHull.physShapeInfo = convexShape;
  1068. }
  1069. }
  1070. return retConvexHull;
  1071. }
  1072. public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim)
  1073. {
  1074. // Calling this reference means we want another handle to an existing shape
  1075. // (usually linksets) so return this copy.
  1076. IncrementReference();
  1077. return this;
  1078. }
  1079. // Dereferencing a compound shape releases the hold on all the child shapes.
  1080. public override void Dereference(BSScene physicsScene)
  1081. {
  1082. lock (ConvexHulls)
  1083. {
  1084. this.DecrementReference();
  1085. physicsScene.DetailLog("{0},BSShapeConvexHull.Dereference,shape={1}", BSScene.DetailLogZero, this);
  1086. // TODO: schedule aging and destruction of unused meshes.
  1087. }
  1088. }
  1089. // Loop through all the known hulls and return the description based on the physical address.
  1090. public static bool TryGetConvexHullByPtr(BulletShape pShape, out BSShapeConvexHull outHull)
  1091. {
  1092. bool ret = false;
  1093. BSShapeConvexHull foundDesc = null;
  1094. lock (ConvexHulls)
  1095. {
  1096. foreach (BSShapeConvexHull sh in ConvexHulls.Values)
  1097. {
  1098. if (sh.physShapeInfo.ReferenceSame(pShape))
  1099. {
  1100. foundDesc = sh;
  1101. ret = true;
  1102. break;
  1103. }
  1104. }
  1105. }
  1106. outHull = foundDesc;
  1107. return ret;
  1108. }
  1109. }
  1110. // ============================================================================================================
  1111. // BSShapeGImpact is a wrapper for the Bullet GImpact shape which is a collision mesh shape that
  1112. // can handle concave as well as convex shapes. Much slower computationally but creates smoother
  1113. // shapes than multiple convex hull approximations.
  1114. public class BSShapeGImpact : BSShape
  1115. {
  1116. #pragma warning disable 414
  1117. private static string LogHeader = "[BULLETSIM SHAPE GIMPACT]";
  1118. #pragma warning restore 414
  1119. public static Dictionary<System.UInt64, BSShapeGImpact> GImpacts = new Dictionary<System.UInt64, BSShapeGImpact>();
  1120. public BSShapeGImpact(BulletShape pShape) : base(pShape)
  1121. {
  1122. }
  1123. public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim)
  1124. {
  1125. float lod;
  1126. System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod);
  1127. physicsScene.DetailLog("{0},BSShapeGImpact,getReference,newKey={1},size={2},lod={3}",
  1128. prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod);
  1129. BSShapeGImpact retGImpact = null;
  1130. lock (GImpacts)
  1131. {
  1132. if (GImpacts.TryGetValue(newMeshKey, out retGImpact))
  1133. {
  1134. // The mesh has already been created. Return a new reference to same.
  1135. retGImpact.IncrementReference();
  1136. }
  1137. else
  1138. {
  1139. retGImpact = new BSShapeGImpact(new BulletShape());
  1140. BulletShape newShape = retGImpact.CreatePhysicalGImpact(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod);
  1141. // Check to see if mesh was created (might require an asset).
  1142. newShape = VerifyMeshCreated(physicsScene, newShape, prim);
  1143. newShape.shapeKey = newMeshKey;
  1144. if (!newShape.isNativeShape || prim.AssetFailed())
  1145. {
  1146. // If a mesh was what was created, remember the built shape for later sharing.
  1147. // Also note that if meshing failed we put it in the mesh list as there is nothing
  1148. // else to do about the mesh.
  1149. GImpacts.Add(newMeshKey, retGImpact);
  1150. }
  1151. retGImpact.physShapeInfo = newShape;
  1152. }
  1153. }
  1154. return retGImpact;
  1155. }
  1156. private BulletShape CreatePhysicalGImpact(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey,
  1157. PrimitiveBaseShape pbs, OMV.Vector3 size, float lod)
  1158. {
  1159. return BSShapeMesh.CreatePhysicalMeshShape(physicsScene, prim, newMeshKey, pbs, size, lod,
  1160. (w, iC, i, vC, v) =>
  1161. {
  1162. shapeInfo.Vertices = vC;
  1163. return physicsScene.PE.CreateGImpactShape(w, iC, i, vC, v);
  1164. });
  1165. }
  1166. public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim)
  1167. {
  1168. BSShape ret = null;
  1169. // If the underlying shape is native, the actual shape has not been build (waiting for asset)
  1170. // and we must create a copy of the native shape since they are never shared.
  1171. if (physShapeInfo.HasPhysicalShape && physShapeInfo.isNativeShape)
  1172. {
  1173. // TODO: decide when the native shapes should be freed. Check in Dereference?
  1174. ret = BSShapeNative.GetReference(pPhysicsScene, pPrim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
  1175. }
  1176. else
  1177. {
  1178. // Another reference to this shape is just counted.
  1179. IncrementReference();
  1180. ret = this;
  1181. }
  1182. return ret;
  1183. }
  1184. // Dereferencing a compound shape releases the hold on all the child shapes.
  1185. public override void Dereference(BSScene physicsScene)
  1186. {
  1187. lock (GImpacts)
  1188. {
  1189. this.DecrementReference();
  1190. physicsScene.DetailLog("{0},BSShapeGImpact.Dereference,shape={1}", BSScene.DetailLogZero, this);
  1191. // TODO: schedule aging and destruction of unused meshes.
  1192. }
  1193. }
  1194. // Loop through all the known hulls and return the description based on the physical address.
  1195. public static bool TryGetGImpactByPtr(BulletShape pShape, out BSShapeGImpact outHull)
  1196. {
  1197. bool ret = false;
  1198. BSShapeGImpact foundDesc = null;
  1199. lock (GImpacts)
  1200. {
  1201. foreach (BSShapeGImpact sh in GImpacts.Values)
  1202. {
  1203. if (sh.physShapeInfo.ReferenceSame(pShape))
  1204. {
  1205. foundDesc = sh;
  1206. ret = true;
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. outHull = foundDesc;
  1212. return ret;
  1213. }
  1214. }
  1215. // ============================================================================================================
  1216. // BSShapeAvatar is a specialized mesh shape for avatars.
  1217. public class BSShapeAvatar : BSShape
  1218. {
  1219. #pragma warning disable 414
  1220. private static string LogHeader = "[BULLETSIM SHAPE AVATAR]";
  1221. #pragma warning restore 414
  1222. public BSShapeAvatar()
  1223. : base()
  1224. {
  1225. }
  1226. public static BSShape GetReference(BSPhysObject prim)
  1227. {
  1228. return new BSShapeNull();
  1229. }
  1230. public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim)
  1231. {
  1232. return new BSShapeNull();
  1233. }
  1234. public override void Dereference(BSScene physicsScene) { }
  1235. // From the front:
  1236. // A---A
  1237. // / \
  1238. // B-------B
  1239. // / \ +Z
  1240. // C-----------C |
  1241. // \ / -Y --+-- +Y
  1242. // \ / |
  1243. // \ / -Z
  1244. // D-----D
  1245. // \ /
  1246. // E-E
  1247. // From the top A and E are just lines.
  1248. // B, C and D are hexagons:
  1249. //
  1250. // C1--C2 +X
  1251. // / \ |
  1252. // C0 C3 -Y --+-- +Y
  1253. // \ / |
  1254. // C5--C4 -X
  1255. // Zero goes directly through the middle so the offsets are from that middle axis
  1256. // and up and down from a middle horizon (A and E are the same distance from the zero).
  1257. // The height, width and depth is one. All scaling is done by the simulator.
  1258. // Z component -- how far the level is from the middle zero
  1259. private const float Aup = 0.5f;
  1260. private const float Bup = 0.4f;
  1261. private const float Cup = 0.3f;
  1262. private const float Dup = -0.4f;
  1263. private const float Eup = -0.5f;
  1264. // Y component -- distance from center to x0 and x3
  1265. private const float Awid = 0.25f;
  1266. private const float Bwid = 0.3f;
  1267. private const float Cwid = 0.5f;
  1268. private const float Dwid = 0.3f;
  1269. private const float Ewid = 0.2f;
  1270. // Y component -- distance from center to x1, x2, x4 and x5
  1271. private const float Afwid = 0.0f;
  1272. private const float Bfwid = 0.2f;
  1273. private const float Cfwid = 0.4f;
  1274. private const float Dfwid = 0.2f;
  1275. private const float Efwid = 0.0f;
  1276. // X component -- distance from zero to the front or back of a level
  1277. private const float Adep = 0f;
  1278. private const float Bdep = 0.3f;
  1279. private const float Cdep = 0.5f;
  1280. private const float Ddep = 0.2f;
  1281. private const float Edep = 0f;
  1282. private OMV.Vector3[] avatarVertices = {
  1283. new OMV.Vector3( 0.0f, -Awid, Aup), // A0
  1284. new OMV.Vector3( 0.0f, +Awid, Aup), // A3
  1285. new OMV.Vector3( 0.0f, -Bwid, Bup), // B0
  1286. new OMV.Vector3(+Bdep, -Bfwid, Bup), // B1
  1287. new OMV.Vector3(+Bdep, +Bfwid, Bup), // B2
  1288. new OMV.Vector3( 0.0f, +Bwid, Bup), // B3
  1289. new OMV.Vector3(-Bdep, +Bfwid, Bup), // B4
  1290. new OMV.Vector3(-Bdep, -Bfwid, Bup), // B5
  1291. new OMV.Vector3( 0.0f, -Cwid, Cup), // C0
  1292. new OMV.Vector3(+Cdep, -Cfwid, Cup), // C1
  1293. new OMV.Vector3(+Cdep, +Cfwid, Cup), // C2
  1294. new OMV.Vector3( 0.0f, +Cwid, Cup), // C3
  1295. new OMV.Vector3(-Cdep, +Cfwid, Cup), // C4
  1296. new OMV.Vector3(-Cdep, -Cfwid, Cup), // C5
  1297. new OMV.Vector3( 0.0f, -Dwid, Dup), // D0
  1298. new OMV.Vector3(+Ddep, -Dfwid, Dup), // D1
  1299. new OMV.Vector3(+Ddep, +Dfwid, Dup), // D2
  1300. new OMV.Vector3( 0.0f, +Dwid, Dup), // D3
  1301. new OMV.Vector3(-Ddep, +Dfwid, Dup), // D4
  1302. new OMV.Vector3(-Ddep, -Dfwid, Dup), // D5
  1303. new OMV.Vector3( 0.0f, -Ewid, Eup), // E0
  1304. new OMV.Vector3( 0.0f, +Ewid, Eup), // E3
  1305. };
  1306. // Offsets of the vertices in the vertices array
  1307. private enum Ind : int
  1308. {
  1309. A0, A3,
  1310. B0, B1, B2, B3, B4, B5,
  1311. C0, C1, C2, C3, C4, C5,
  1312. D0, D1, D2, D3, D4, D5,
  1313. E0, E3
  1314. }
  1315. // Comments specify trianges and quads in clockwise direction
  1316. private Ind[] avatarIndices = {
  1317. Ind.A0, Ind.B0, Ind.B1, // A0,B0,B1
  1318. Ind.A0, Ind.B1, Ind.B2, Ind.B2, Ind.A3, Ind.A0, // A0,B1,B2,A3
  1319. Ind.A3, Ind.B2, Ind.B3, // A3,B2,B3
  1320. Ind.A3, Ind.B3, Ind.B4, // A3,B3,B4
  1321. Ind.A3, Ind.B4, Ind.B5, Ind.B5, Ind.A0, Ind.A3, // A3,B4,B5,A0
  1322. Ind.A0, Ind.B5, Ind.B0, // A0,B5,B0
  1323. Ind.B0, Ind.C0, Ind.C1, Ind.C1, Ind.B1, Ind.B0, // B0,C0,C1,B1
  1324. Ind.B1, Ind.C1, Ind.C2, Ind.C2, Ind.B2, Ind.B1, // B1,C1,C2,B2
  1325. Ind.B2, Ind.C2, Ind.C3, Ind.C3, Ind.B3, Ind.B2, // B2,C2,C3,B3
  1326. Ind.B3, Ind.C3, Ind.C4, Ind.C4, Ind.B4, Ind.B3, // B3,C3,C4,B4
  1327. Ind.B4, Ind.C4, Ind.C5, Ind.C5, Ind.B5, Ind.B4, // B4,C4,C5,B5
  1328. Ind.B5, Ind.C5, Ind.C0, Ind.C0, Ind.B0, Ind.B5, // B5,C5,C0,B0
  1329. Ind.C0, Ind.D0, Ind.D1, Ind.D1, Ind.C1, Ind.C0, // C0,D0,D1,C1
  1330. Ind.C1, Ind.D1, Ind.D2, Ind.D2, Ind.C2, Ind.C1, // C1,D1,D2,C2
  1331. Ind.C2, Ind.D2, Ind.D3, Ind.D3, Ind.C3, Ind.C2, // C2,D2,D3,C3
  1332. Ind.C3, Ind.D3, Ind.D4, Ind.D4, Ind.C4, Ind.C3, // C3,D3,D4,C4
  1333. Ind.C4, Ind.D4, Ind.D5, Ind.D5, Ind.C5, Ind.C4, // C4,D4,D5,C5
  1334. Ind.C5, Ind.D5, Ind.D0, Ind.D0, Ind.C0, Ind.C5, // C5,D5,D0,C0
  1335. Ind.E0, Ind.D0, Ind.D1, // E0,D0,D1
  1336. Ind.E0, Ind.D1, Ind.D2, Ind.D2, Ind.E3, Ind.E0, // E0,D1,D2,E3
  1337. Ind.E3, Ind.D2, Ind.D3, // E3,D2,D3
  1338. Ind.E3, Ind.D3, Ind.D4, // E3,D3,D4
  1339. Ind.E3, Ind.D4, Ind.D5, Ind.D5, Ind.E0, Ind.E3, // E3,D4,D5,E0
  1340. Ind.E0, Ind.D5, Ind.D0, // E0,D5,D0
  1341. };
  1342. }
  1343. }