BulletXPlugin.cs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  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 copyright
  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 OpenSim 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. #region References
  28. using System;
  29. using System.Collections.Generic;
  30. using OpenMetaverse;
  31. using MonoXnaCompactMaths;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Physics.Manager;
  34. using XnaDevRu.BulletX;
  35. using XnaDevRu.BulletX.Dynamics;
  36. using Nini.Config;
  37. using Vector3 = MonoXnaCompactMaths.Vector3;
  38. using Quaternion = MonoXnaCompactMaths.Quaternion;
  39. #endregion
  40. namespace OpenSim.Region.Physics.BulletXPlugin
  41. {
  42. /// <summary>
  43. /// BulletXConversions are called now BulletXMaths
  44. /// This Class converts objects and types for BulletX and give some operations
  45. /// </summary>
  46. public class BulletXMaths
  47. {
  48. //private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  49. //Vector3
  50. public static Vector3 PhysicsVectorToXnaVector3(PhysicsVector physicsVector)
  51. {
  52. return new Vector3(physicsVector.X, physicsVector.Y, physicsVector.Z);
  53. }
  54. public static PhysicsVector XnaVector3ToPhysicsVector(Vector3 xnaVector3)
  55. {
  56. return new PhysicsVector(xnaVector3.X, xnaVector3.Y, xnaVector3.Z);
  57. }
  58. //Quaternion
  59. public static Quaternion QuaternionToXnaQuaternion(OpenMetaverse.Quaternion quaternion)
  60. {
  61. return new Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
  62. }
  63. public static OpenMetaverse.Quaternion XnaQuaternionToQuaternion(Quaternion xnaQuaternion)
  64. {
  65. return new OpenMetaverse.Quaternion(xnaQuaternion.W, xnaQuaternion.X, xnaQuaternion.Y, xnaQuaternion.Z);
  66. }
  67. //Next methods are extracted from XnaDevRu.BulletX(See 3rd party license):
  68. //- SetRotation (class MatrixOperations)
  69. //- GetRotation (class MatrixOperations)
  70. //- GetElement (class MathHelper)
  71. //- SetElement (class MathHelper)
  72. internal static void SetRotation(ref Matrix m, Quaternion q)
  73. {
  74. float d = q.LengthSquared();
  75. float s = 2f/d;
  76. float xs = q.X*s, ys = q.Y*s, zs = q.Z*s;
  77. float wx = q.W*xs, wy = q.W*ys, wz = q.W*zs;
  78. float xx = q.X*xs, xy = q.X*ys, xz = q.X*zs;
  79. float yy = q.Y*ys, yz = q.Y*zs, zz = q.Z*zs;
  80. m = new Matrix(1 - (yy + zz), xy - wz, xz + wy, 0,
  81. xy + wz, 1 - (xx + zz), yz - wx, 0,
  82. xz - wy, yz + wx, 1 - (xx + yy), 0,
  83. m.M41, m.M42, m.M43, 1);
  84. }
  85. internal static Quaternion GetRotation(Matrix m)
  86. {
  87. Quaternion q;
  88. float trace = m.M11 + m.M22 + m.M33;
  89. if (trace > 0)
  90. {
  91. float s = (float) Math.Sqrt(trace + 1);
  92. q.W = s*0.5f;
  93. s = 0.5f/s;
  94. q.X = (m.M32 - m.M23)*s;
  95. q.Y = (m.M13 - m.M31)*s;
  96. q.Z = (m.M21 - m.M12)*s;
  97. }
  98. else
  99. {
  100. q.X = q.Y = q.Z = q.W = 0f;
  101. int i = m.M11 < m.M22
  102. ?
  103. (m.M22 < m.M33 ? 2 : 1)
  104. :
  105. (m.M11 < m.M33 ? 2 : 0);
  106. int j = (i + 1)%3;
  107. int k = (i + 2)%3;
  108. float s = (float) Math.Sqrt(GetElement(m, i, i) - GetElement(m, j, j) - GetElement(m, k, k) + 1);
  109. SetElement(ref q, i, s*0.5f);
  110. s = 0.5f/s;
  111. q.W = (GetElement(m, k, j) - GetElement(m, j, k))*s;
  112. SetElement(ref q, j, (GetElement(m, j, i) + GetElement(m, i, j))*s);
  113. SetElement(ref q, k, (GetElement(m, k, i) + GetElement(m, i, k))*s);
  114. }
  115. return q;
  116. }
  117. internal static float SetElement(ref Quaternion q, int index, float value)
  118. {
  119. switch (index)
  120. {
  121. case 0:
  122. q.X = value;
  123. break;
  124. case 1:
  125. q.Y = value;
  126. break;
  127. case 2:
  128. q.Z = value;
  129. break;
  130. case 3:
  131. q.W = value;
  132. break;
  133. }
  134. return 0;
  135. }
  136. internal static float GetElement(Matrix mat, int row, int col)
  137. {
  138. switch (row)
  139. {
  140. case 0:
  141. switch (col)
  142. {
  143. case 0:
  144. return mat.M11;
  145. case 1:
  146. return mat.M12;
  147. case 2:
  148. return mat.M13;
  149. }
  150. break;
  151. case 1:
  152. switch (col)
  153. {
  154. case 0:
  155. return mat.M21;
  156. case 1:
  157. return mat.M22;
  158. case 2:
  159. return mat.M23;
  160. }
  161. break;
  162. case 2:
  163. switch (col)
  164. {
  165. case 0:
  166. return mat.M31;
  167. case 1:
  168. return mat.M32;
  169. case 2:
  170. return mat.M33;
  171. }
  172. break;
  173. }
  174. return 0;
  175. }
  176. }
  177. /// <summary>
  178. /// PhysicsPlugin Class for BulletX
  179. /// </summary>
  180. public class BulletXPlugin : IPhysicsPlugin
  181. {
  182. private BulletXScene _mScene;
  183. public BulletXPlugin()
  184. {
  185. }
  186. public bool Init()
  187. {
  188. return true;
  189. }
  190. public PhysicsScene GetScene(string sceneIdentifier)
  191. {
  192. if (_mScene == null)
  193. {
  194. _mScene = new BulletXScene(sceneIdentifier);
  195. }
  196. return (_mScene);
  197. }
  198. public string GetName()
  199. {
  200. return ("modified_BulletX"); //Changed!! "BulletXEngine" To "modified_BulletX"
  201. }
  202. public void Dispose()
  203. {
  204. }
  205. }
  206. // Class to detect and debug collisions
  207. // Mainly used for debugging purposes
  208. internal class CollisionDispatcherLocal : CollisionDispatcher
  209. {
  210. private BulletXScene relatedScene;
  211. public CollisionDispatcherLocal(BulletXScene s)
  212. : base()
  213. {
  214. relatedScene = s;
  215. }
  216. public override bool NeedsCollision(CollisionObject bodyA, CollisionObject bodyB)
  217. {
  218. RigidBody rb;
  219. BulletXCharacter bxcA = null;
  220. BulletXPrim bxpA = null;
  221. Type t = bodyA.GetType();
  222. if (t == typeof (RigidBody))
  223. {
  224. rb = (RigidBody) bodyA;
  225. relatedScene._characters.TryGetValue(rb, out bxcA);
  226. relatedScene._prims.TryGetValue(rb, out bxpA);
  227. }
  228. // String nameA;
  229. // if (bxcA != null)
  230. // nameA = bxcA._name;
  231. // else if (bxpA != null)
  232. // nameA = bxpA._name;
  233. // else
  234. // nameA = "null";
  235. BulletXCharacter bxcB = null;
  236. BulletXPrim bxpB = null;
  237. t = bodyB.GetType();
  238. if (t == typeof (RigidBody))
  239. {
  240. rb = (RigidBody) bodyB;
  241. relatedScene._characters.TryGetValue(rb, out bxcB);
  242. relatedScene._prims.TryGetValue(rb, out bxpB);
  243. }
  244. // String nameB;
  245. // if (bxcB != null)
  246. // nameB = bxcB._name;
  247. // else if (bxpB != null)
  248. // nameB = bxpB._name;
  249. // else
  250. // nameB = "null";
  251. bool needsCollision;// = base.NeedsCollision(bodyA, bodyB);
  252. int c1 = 3;
  253. int c2 = 3;
  254. ////////////////////////////////////////////////////////
  255. //BulletX Mesh Collisions
  256. //added by Jed zhu
  257. //data: May 07,2005
  258. ////////////////////////////////////////////////////////
  259. #region BulletXMeshCollisions Fields
  260. if (bxcA != null && bxpB != null)
  261. c1 = Collision(bxcA, bxpB);
  262. if (bxpA != null && bxcB != null)
  263. c2 = Collision(bxcB, bxpA);
  264. if (c1 < 2)
  265. needsCollision = (c1 > 0) ? true : false;
  266. else if (c2 < 2)
  267. needsCollision = (c2 > 0) ? true : false;
  268. else
  269. needsCollision = base.NeedsCollision(bodyA, bodyB);
  270. #endregion
  271. //m_log.DebugFormat("[BulletX]: A collision was detected between {0} and {1} --> {2}", nameA, nameB,
  272. //needsCollision);
  273. return needsCollision;
  274. }
  275. //added by jed zhu
  276. //calculas the collision between the Prim and Actor
  277. //
  278. private int Collision(BulletXCharacter actorA, BulletXPrim primB)
  279. {
  280. int[] indexBase;
  281. Vector3[] vertexBase;
  282. Vector3 vNormal;
  283. // Vector3 vP1;
  284. // Vector3 vP2;
  285. // Vector3 vP3;
  286. IMesh mesh = primB.GetMesh();
  287. float fdistance;
  288. if (primB == null)
  289. return 3;
  290. if (mesh == null)
  291. return 2;
  292. if (actorA == null)
  293. return 3;
  294. int iVertexCount = mesh.getVertexList().Count;
  295. int iIndexCount = mesh.getIndexListAsInt().Length;
  296. if (iVertexCount == 0)
  297. return 3;
  298. if (iIndexCount == 0)
  299. return 3;
  300. lock (BulletXScene.BulletXLock)
  301. {
  302. indexBase = mesh.getIndexListAsInt();
  303. vertexBase = new Vector3[iVertexCount];
  304. for (int i = 0; i < iVertexCount; i++)
  305. {
  306. PhysicsVector v = mesh.getVertexList()[i];
  307. if (v != null) // Note, null has special meaning. See meshing code for details
  308. vertexBase[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
  309. else
  310. vertexBase[i] = Vector3.Zero;
  311. }
  312. for (int ix = 0; ix < iIndexCount; ix += 3)
  313. {
  314. int ia = indexBase[ix + 0];
  315. int ib = indexBase[ix + 1];
  316. int ic = indexBase[ix + 2];
  317. //
  318. Vector3 v1 = vertexBase[ib] - vertexBase[ia];
  319. Vector3 v2 = vertexBase[ic] - vertexBase[ia];
  320. Vector3.Cross(ref v1, ref v2, out vNormal);
  321. Vector3.Normalize(ref vNormal, out vNormal);
  322. fdistance = Vector3.Dot(vNormal, vertexBase[ia]) + 0.50f;
  323. if (preCheckCollision(actorA, vNormal, fdistance) == 1)
  324. {
  325. if (CheckCollision(actorA, ia, ib, ic, vNormal, vertexBase) == 1)
  326. {
  327. //PhysicsVector v = actorA.Position;
  328. //Vector3 v3 = BulletXMaths.PhysicsVectorToXnaVector3(v);
  329. //Vector3 vp = vNormal * (fdistance - Vector3.Dot(vNormal, v3) + 0.2f);
  330. //actorA.Position += BulletXMaths.XnaVector3ToPhysicsVector(vp);
  331. return 1;
  332. }
  333. }
  334. }
  335. }
  336. return 0;
  337. }
  338. //added by jed zhu
  339. //return value 1: need second check
  340. //return value 0: no need check
  341. private int preCheckCollision(BulletXActor actA, Vector3 vNormal, float fDist)
  342. {
  343. float fstartSide;
  344. PhysicsVector v = actA.Position;
  345. Vector3 v3 = BulletXMaths.PhysicsVectorToXnaVector3(v);
  346. fstartSide = Vector3.Dot(vNormal, v3) - fDist;
  347. if (fstartSide > 0) return 0;
  348. else return 1;
  349. }
  350. //added by jed zhu
  351. private int CheckCollision(BulletXActor actA, int ia, int ib, int ic, Vector3 vNormal, Vector3[] vertBase)
  352. {
  353. Vector3 perPlaneNormal;
  354. float fPerPlaneDist;
  355. PhysicsVector v = actA.Position;
  356. Vector3 v3 = BulletXMaths.PhysicsVectorToXnaVector3(v);
  357. //check AB
  358. Vector3 v1;
  359. v1 = vertBase[ib] - vertBase[ia];
  360. Vector3.Cross(ref vNormal, ref v1, out perPlaneNormal);
  361. Vector3.Normalize(ref perPlaneNormal, out perPlaneNormal);
  362. if (Vector3.Dot((vertBase[ic] - vertBase[ia]), perPlaneNormal) < 0)
  363. perPlaneNormal = -perPlaneNormal;
  364. fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ia]) - 0.50f;
  365. if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) < 0)
  366. return 0;
  367. fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ic]) + 0.50f;
  368. if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) > 0)
  369. return 0;
  370. //check BC
  371. v1 = vertBase[ic] - vertBase[ib];
  372. Vector3.Cross(ref vNormal, ref v1, out perPlaneNormal);
  373. Vector3.Normalize(ref perPlaneNormal, out perPlaneNormal);
  374. if (Vector3.Dot((vertBase[ia] - vertBase[ib]), perPlaneNormal) < 0)
  375. perPlaneNormal = -perPlaneNormal;
  376. fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ib]) - 0.50f;
  377. if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) < 0)
  378. return 0;
  379. fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ia]) + 0.50f;
  380. if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) > 0)
  381. return 0;
  382. //check CA
  383. v1 = vertBase[ia] - vertBase[ic];
  384. Vector3.Cross(ref vNormal, ref v1, out perPlaneNormal);
  385. Vector3.Normalize(ref perPlaneNormal, out perPlaneNormal);
  386. if (Vector3.Dot((vertBase[ib] - vertBase[ic]), perPlaneNormal) < 0)
  387. perPlaneNormal = -perPlaneNormal;
  388. fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ic]) - 0.50f;
  389. if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) < 0)
  390. return 0;
  391. fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ib]) + 0.50f;
  392. if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) > 0)
  393. return 0;
  394. return 1;
  395. }
  396. }
  397. /// <summary>
  398. /// PhysicsScene Class for BulletX
  399. /// </summary>
  400. public class BulletXScene : PhysicsScene
  401. {
  402. #region BulletXScene Fields
  403. public DiscreteDynamicsWorld ddWorld;
  404. private CollisionDispatcher cDispatcher;
  405. private OverlappingPairCache opCache;
  406. private SequentialImpulseConstraintSolver sicSolver;
  407. public static Object BulletXLock = new Object();
  408. private const int minXY = 0;
  409. private const int minZ = 0;
  410. private const int maxXY = (int)Constants.RegionSize;
  411. private const int maxZ = 4096;
  412. private const int maxHandles = 32766; //Why? I don't know
  413. private const float gravity = 9.8f;
  414. private const float heightLevel0 = 77.0f;
  415. private const float heightLevel1 = 200.0f;
  416. private const float lowGravityFactor = 0.2f;
  417. //OpenSim calls Simulate 10 times per seconds. So FPS = "Simulate Calls" * simulationSubSteps = 100 FPS
  418. private const int simulationSubSteps = 10;
  419. //private float[] _heightmap;
  420. private BulletXPlanet _simFlatPlanet;
  421. internal Dictionary<RigidBody, BulletXCharacter> _characters = new Dictionary<RigidBody, BulletXCharacter>();
  422. internal Dictionary<RigidBody, BulletXPrim> _prims = new Dictionary<RigidBody, BulletXPrim>();
  423. public IMesher mesher;
  424. // private IConfigSource m_config;
  425. // protected internal String identifier;
  426. public BulletXScene(String sceneIdentifier)
  427. {
  428. //identifier = sceneIdentifier;
  429. }
  430. public static float Gravity
  431. {
  432. get { return gravity; }
  433. }
  434. public static float HeightLevel0
  435. {
  436. get { return heightLevel0; }
  437. }
  438. public static float HeightLevel1
  439. {
  440. get { return heightLevel1; }
  441. }
  442. public static float LowGravityFactor
  443. {
  444. get { return lowGravityFactor; }
  445. }
  446. public static int MaxXY
  447. {
  448. get { return maxXY; }
  449. }
  450. public static int MaxZ
  451. {
  452. get { return maxZ; }
  453. }
  454. private List<RigidBody> _forgottenRigidBodies = new List<RigidBody>();
  455. internal string is_ex_message = "Can't remove rigidBody!: ";
  456. #endregion
  457. public BulletXScene()
  458. {
  459. cDispatcher = new CollisionDispatcherLocal(this);
  460. Vector3 worldMinDim = new Vector3((float) minXY, (float) minXY, (float) minZ);
  461. Vector3 worldMaxDim = new Vector3((float) maxXY, (float) maxXY, (float) maxZ);
  462. opCache = new AxisSweep3(worldMinDim, worldMaxDim, maxHandles);
  463. sicSolver = new SequentialImpulseConstraintSolver();
  464. lock (BulletXLock)
  465. {
  466. ddWorld = new DiscreteDynamicsWorld(cDispatcher, opCache, sicSolver);
  467. ddWorld.Gravity = new Vector3(0, 0, -gravity);
  468. }
  469. //this._heightmap = new float[65536];
  470. }
  471. public override void Initialise(IMesher meshmerizer, IConfigSource config)
  472. {
  473. mesher = meshmerizer;
  474. // m_config = config;
  475. }
  476. public override void Dispose()
  477. {
  478. }
  479. public override Dictionary<uint, float> GetTopColliders()
  480. {
  481. Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
  482. return returncolliders;
  483. }
  484. public override void SetWaterLevel(float baseheight)
  485. {
  486. }
  487. public override PhysicsActor AddAvatar(string avName, PhysicsVector position, PhysicsVector size, bool isFlying)
  488. {
  489. PhysicsVector pos = new PhysicsVector();
  490. pos.X = position.X;
  491. pos.Y = position.Y;
  492. pos.Z = position.Z + 20;
  493. BulletXCharacter newAv = null;
  494. newAv.Flying = isFlying;
  495. lock (BulletXLock)
  496. {
  497. newAv = new BulletXCharacter(avName, this, pos);
  498. _characters.Add(newAv.RigidBody, newAv);
  499. }
  500. return newAv;
  501. }
  502. public override void RemoveAvatar(PhysicsActor actor)
  503. {
  504. if (actor is BulletXCharacter)
  505. {
  506. lock (BulletXLock)
  507. {
  508. try
  509. {
  510. ddWorld.RemoveRigidBody(((BulletXCharacter) actor).RigidBody);
  511. }
  512. catch (Exception ex)
  513. {
  514. BulletXMessage(is_ex_message + ex.Message, true);
  515. ((BulletXCharacter) actor).RigidBody.ActivationState = ActivationState.DisableSimulation;
  516. AddForgottenRigidBody(((BulletXCharacter) actor).RigidBody);
  517. }
  518. _characters.Remove(((BulletXCharacter) actor).RigidBody);
  519. }
  520. GC.Collect();
  521. }
  522. }
  523. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
  524. PhysicsVector size, OpenMetaverse.Quaternion rotation)
  525. {
  526. return AddPrimShape(primName, pbs, position, size, rotation, false);
  527. }
  528. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
  529. PhysicsVector size, OpenMetaverse.Quaternion rotation, bool isPhysical)
  530. {
  531. PhysicsActor result;
  532. switch (pbs.ProfileShape)
  533. {
  534. case ProfileShape.Square:
  535. /// support simple box & hollow box now; later, more shapes
  536. if (pbs.ProfileHollow == 0)
  537. {
  538. result = AddPrim(primName, position, size, rotation, null, null, isPhysical);
  539. }
  540. else
  541. {
  542. IMesh mesh = mesher.CreateMesh(primName, pbs, size, 32f, isPhysical);
  543. result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical);
  544. }
  545. break;
  546. default:
  547. result = AddPrim(primName, position, size, rotation, null, null, isPhysical);
  548. break;
  549. }
  550. return result;
  551. }
  552. public PhysicsActor AddPrim(String name, PhysicsVector position, PhysicsVector size, OpenMetaverse.Quaternion rotation,
  553. IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
  554. {
  555. BulletXPrim newPrim = null;
  556. lock (BulletXLock)
  557. {
  558. newPrim = new BulletXPrim(name, this, position, size, rotation, mesh, pbs, isPhysical);
  559. _prims.Add(newPrim.RigidBody, newPrim);
  560. }
  561. return newPrim;
  562. }
  563. public override void RemovePrim(PhysicsActor prim)
  564. {
  565. if (prim is BulletXPrim)
  566. {
  567. lock (BulletXLock)
  568. {
  569. try
  570. {
  571. ddWorld.RemoveRigidBody(((BulletXPrim) prim).RigidBody);
  572. }
  573. catch (Exception ex)
  574. {
  575. BulletXMessage(is_ex_message + ex.Message, true);
  576. ((BulletXPrim) prim).RigidBody.ActivationState = ActivationState.DisableSimulation;
  577. AddForgottenRigidBody(((BulletXPrim) prim).RigidBody);
  578. }
  579. _prims.Remove(((BulletXPrim) prim).RigidBody);
  580. }
  581. GC.Collect();
  582. }
  583. }
  584. public override void AddPhysicsActorTaint(PhysicsActor prim)
  585. {
  586. }
  587. public override float Simulate(float timeStep)
  588. {
  589. float fps = 0;
  590. lock (BulletXLock)
  591. {
  592. //Try to remove garbage
  593. RemoveForgottenRigidBodies();
  594. //End of remove
  595. MoveAPrimitives(timeStep);
  596. fps = (timeStep*simulationSubSteps);
  597. ddWorld.StepSimulation(timeStep, simulationSubSteps, timeStep);
  598. //Extra Heightmap Validation: BulletX's HeightFieldTerrain somestimes doesn't work so fine.
  599. ValidateHeightForAll();
  600. //End heightmap validation.
  601. UpdateKineticsForAll();
  602. }
  603. return fps;
  604. }
  605. private void MoveAPrimitives(float timeStep)
  606. {
  607. foreach (BulletXCharacter actor in _characters.Values)
  608. {
  609. actor.Move(timeStep);
  610. }
  611. }
  612. private void ValidateHeightForAll()
  613. {
  614. float _height;
  615. foreach (BulletXCharacter actor in _characters.Values)
  616. {
  617. //_height = HeightValue(actor.RigidBodyPosition);
  618. _height = _simFlatPlanet.HeightValue(actor.RigidBodyPosition);
  619. actor.ValidateHeight(_height);
  620. //if (_simFlatPlanet.heightIsNotValid(actor.RigidBodyPosition, out _height)) actor.ValidateHeight(_height);
  621. }
  622. foreach (BulletXPrim prim in _prims.Values)
  623. {
  624. //_height = HeightValue(prim.RigidBodyPosition);
  625. _height = _simFlatPlanet.HeightValue(prim.RigidBodyPosition);
  626. prim.ValidateHeight(_height);
  627. //if (_simFlatPlanet.heightIsNotValid(prim.RigidBodyPosition, out _height)) prim.ValidateHeight(_height);
  628. }
  629. //foreach (BulletXCharacter actor in _characters)
  630. //{
  631. // actor.ValidateHeight(0);
  632. //}
  633. //foreach (BulletXPrim prim in _prims)
  634. //{
  635. // prim.ValidateHeight(0);
  636. //}
  637. }
  638. private void UpdateKineticsForAll()
  639. {
  640. //UpdatePosition > UpdateKinetics.
  641. //Not only position will be updated, also velocity cause acceleration.
  642. foreach (BulletXCharacter actor in _characters.Values)
  643. {
  644. actor.UpdateKinetics();
  645. }
  646. foreach (BulletXPrim prim in _prims.Values)
  647. {
  648. prim.UpdateKinetics();
  649. }
  650. //if (this._simFlatPlanet!=null) this._simFlatPlanet.Restore();
  651. }
  652. public override void GetResults()
  653. {
  654. }
  655. public override bool IsThreaded
  656. {
  657. get
  658. {
  659. return (false); // for now we won't be multithreaded
  660. }
  661. }
  662. public override void SetTerrain(float[] heightMap)
  663. {
  664. ////As the same as ODE, heightmap (x,y) must be swapped for BulletX
  665. //for (int i = 0; i < 65536; i++)
  666. //{
  667. // // this._heightmap[i] = (double)heightMap[i];
  668. // // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
  669. // int x = i & 0xff;
  670. // int y = i >> 8;
  671. // this._heightmap[i] = heightMap[x * 256 + y];
  672. //}
  673. //float[] swappedHeightMap = new float[65536];
  674. ////As the same as ODE, heightmap (x,y) must be swapped for BulletX
  675. //for (int i = 0; i < 65536; i++)
  676. //{
  677. // // this._heightmap[i] = (double)heightMap[i];
  678. // // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
  679. // int x = i & 0xff;
  680. // int y = i >> 8;
  681. // swappedHeightMap[i] = heightMap[x * 256 + y];
  682. //}
  683. DeleteTerrain();
  684. //There is a BulletXLock inside the constructor of BulletXPlanet
  685. //this._simFlatPlanet = new BulletXPlanet(this, swappedHeightMap);
  686. _simFlatPlanet = new BulletXPlanet(this, heightMap);
  687. //this._heightmap = heightMap;
  688. }
  689. public override void DeleteTerrain()
  690. {
  691. if (_simFlatPlanet != null)
  692. {
  693. lock (BulletXLock)
  694. {
  695. try
  696. {
  697. ddWorld.RemoveRigidBody(_simFlatPlanet.RigidBody);
  698. }
  699. catch (Exception ex)
  700. {
  701. BulletXMessage(is_ex_message + ex.Message, true);
  702. _simFlatPlanet.RigidBody.ActivationState = ActivationState.DisableSimulation;
  703. AddForgottenRigidBody(_simFlatPlanet.RigidBody);
  704. }
  705. }
  706. _simFlatPlanet = null;
  707. GC.Collect();
  708. BulletXMessage("Terrain erased!", false);
  709. }
  710. //this._heightmap = null;
  711. }
  712. internal void AddForgottenRigidBody(RigidBody forgottenRigidBody)
  713. {
  714. _forgottenRigidBodies.Add(forgottenRigidBody);
  715. }
  716. private void RemoveForgottenRigidBodies()
  717. {
  718. RigidBody forgottenRigidBody;
  719. int nRigidBodies = _forgottenRigidBodies.Count;
  720. for (int i = nRigidBodies - 1; i >= 0; i--)
  721. {
  722. forgottenRigidBody = _forgottenRigidBodies[i];
  723. try
  724. {
  725. ddWorld.RemoveRigidBody(forgottenRigidBody);
  726. _forgottenRigidBodies.Remove(forgottenRigidBody);
  727. BulletXMessage("Forgotten Rigid Body Removed", false);
  728. }
  729. catch (Exception ex)
  730. {
  731. BulletXMessage("Can't remove forgottenRigidBody!: " + ex.Message, false);
  732. }
  733. }
  734. GC.Collect();
  735. }
  736. internal static void BulletXMessage(string message, bool isWarning)
  737. {
  738. PhysicsPluginManager.PhysicsPluginMessage("[Modified BulletX]:\t" + message, isWarning);
  739. }
  740. //temp
  741. //private float HeightValue(MonoXnaCompactMaths.Vector3 position)
  742. //{
  743. // int li_x, li_y;
  744. // float height;
  745. // li_x = (int)Math.Round(position.X); if (li_x < 0) li_x = 0;
  746. // li_y = (int)Math.Round(position.Y); if (li_y < 0) li_y = 0;
  747. // height = this._heightmap[li_y * 256 + li_x];
  748. // if (height < 0) height = 0;
  749. // else if (height > maxZ) height = maxZ;
  750. // return height;
  751. //}
  752. }
  753. /// <summary>
  754. /// Generic Physics Actor for BulletX inherit from PhysicActor
  755. /// </summary>
  756. public class BulletXActor : PhysicsActor
  757. {
  758. protected bool flying = false;
  759. protected bool _physical = false;
  760. protected PhysicsVector _position;
  761. protected PhysicsVector _velocity;
  762. protected PhysicsVector _size;
  763. protected PhysicsVector _acceleration;
  764. protected OpenMetaverse.Quaternion _orientation;
  765. protected PhysicsVector m_rotationalVelocity = PhysicsVector.Zero;
  766. protected RigidBody rigidBody;
  767. protected int m_PhysicsActorType;
  768. private Boolean iscolliding = false;
  769. internal string _name;
  770. public BulletXActor(String name)
  771. {
  772. _name = name;
  773. }
  774. public override bool Stopped
  775. {
  776. get { return false; }
  777. }
  778. public override PhysicsVector Position
  779. {
  780. get { return _position; }
  781. set
  782. {
  783. lock (BulletXScene.BulletXLock)
  784. {
  785. _position = value;
  786. Translate();
  787. }
  788. }
  789. }
  790. public override PhysicsVector RotationalVelocity
  791. {
  792. get { return m_rotationalVelocity; }
  793. set { m_rotationalVelocity = value; }
  794. }
  795. public override PhysicsVector Velocity
  796. {
  797. get { return _velocity; }
  798. set
  799. {
  800. lock (BulletXScene.BulletXLock)
  801. {
  802. //Static objects don' have linear velocity
  803. if (_physical)
  804. {
  805. _velocity = value;
  806. Speed();
  807. }
  808. else
  809. {
  810. _velocity = new PhysicsVector();
  811. }
  812. }
  813. }
  814. }
  815. public override float CollisionScore
  816. {
  817. get { return 0f; }
  818. set { }
  819. }
  820. public override PhysicsVector Size
  821. {
  822. get { return _size; }
  823. set
  824. {
  825. lock (BulletXScene.BulletXLock)
  826. {
  827. _size = value;
  828. }
  829. }
  830. }
  831. public override PhysicsVector Force
  832. {
  833. get { return PhysicsVector.Zero; }
  834. set { return; }
  835. }
  836. public override int VehicleType
  837. {
  838. get { return 0; }
  839. set { return; }
  840. }
  841. public override void VehicleFloatParam(int param, float value)
  842. {
  843. }
  844. public override void VehicleVectorParam(int param, PhysicsVector value)
  845. {
  846. }
  847. public override void VehicleRotationParam(int param, OpenMetaverse.Quaternion rotation)
  848. {
  849. }
  850. public override void SetVolumeDetect(int param)
  851. {
  852. }
  853. public override PhysicsVector CenterOfMass
  854. {
  855. get { return PhysicsVector.Zero; }
  856. }
  857. public override PhysicsVector GeometricCenter
  858. {
  859. get { return PhysicsVector.Zero; }
  860. }
  861. public override PrimitiveBaseShape Shape
  862. {
  863. set { return; }
  864. }
  865. public override bool SetAlwaysRun
  866. {
  867. get { return false; }
  868. set { return; }
  869. }
  870. public override PhysicsVector Acceleration
  871. {
  872. get { return _acceleration; }
  873. }
  874. public override OpenMetaverse.Quaternion Orientation
  875. {
  876. get { return _orientation; }
  877. set
  878. {
  879. lock (BulletXScene.BulletXLock)
  880. {
  881. _orientation = value;
  882. ReOrient();
  883. }
  884. }
  885. }
  886. public override void link(PhysicsActor obj)
  887. {
  888. }
  889. public override void delink()
  890. {
  891. }
  892. public override void LockAngularMotion(PhysicsVector axis)
  893. {
  894. }
  895. public override float Mass
  896. {
  897. get { return ActorMass; }
  898. }
  899. public virtual float ActorMass
  900. {
  901. get { return 0; }
  902. }
  903. public override int PhysicsActorType
  904. {
  905. get { return (int) m_PhysicsActorType; }
  906. set { m_PhysicsActorType = value; }
  907. }
  908. public RigidBody RigidBody
  909. {
  910. get { return rigidBody; }
  911. }
  912. public Vector3 RigidBodyPosition
  913. {
  914. get { return rigidBody.CenterOfMassPosition; }
  915. }
  916. public override bool IsPhysical
  917. {
  918. get { return _physical; }
  919. set { _physical = value; }
  920. }
  921. public override bool Flying
  922. {
  923. get { return flying; }
  924. set { flying = value; }
  925. }
  926. public override bool ThrottleUpdates
  927. {
  928. get { return false; }
  929. set { return; }
  930. }
  931. public override bool IsColliding
  932. {
  933. get { return iscolliding; }
  934. set { iscolliding = value; }
  935. }
  936. public override bool CollidingGround
  937. {
  938. get { return false; }
  939. set { return; }
  940. }
  941. public override bool CollidingObj
  942. {
  943. get { return false; }
  944. set { return; }
  945. }
  946. public override uint LocalID
  947. {
  948. set { return; }
  949. }
  950. public override bool Grabbed
  951. {
  952. set { return; }
  953. }
  954. public override bool Selected
  955. {
  956. set { return; }
  957. }
  958. public override float Buoyancy
  959. {
  960. get { return 0f; }
  961. set { return; }
  962. }
  963. public override bool FloatOnWater
  964. {
  965. set { return; }
  966. }
  967. public virtual void SetAcceleration(PhysicsVector accel)
  968. {
  969. lock (BulletXScene.BulletXLock)
  970. {
  971. _acceleration = accel;
  972. }
  973. }
  974. public override bool Kinematic
  975. {
  976. get { return false; }
  977. set { }
  978. }
  979. public override void AddForce(PhysicsVector force, bool pushforce)
  980. {
  981. }
  982. public override PhysicsVector Torque
  983. {
  984. get { return PhysicsVector.Zero; }
  985. set { return; }
  986. }
  987. public override void AddAngularForce(PhysicsVector force, bool pushforce)
  988. {
  989. }
  990. public override void SetMomentum(PhysicsVector momentum)
  991. {
  992. }
  993. internal virtual void ValidateHeight(float heighmapPositionValue)
  994. {
  995. }
  996. internal virtual void UpdateKinetics()
  997. {
  998. }
  999. #region Methods for updating values of RigidBody
  1000. protected internal void Translate()
  1001. {
  1002. Translate(_position);
  1003. }
  1004. protected internal void Translate(PhysicsVector _newPos)
  1005. {
  1006. Vector3 _translation;
  1007. _translation = BulletXMaths.PhysicsVectorToXnaVector3(_newPos) - rigidBody.CenterOfMassPosition;
  1008. rigidBody.Translate(_translation);
  1009. }
  1010. protected internal void Speed()
  1011. {
  1012. Speed(_velocity);
  1013. }
  1014. protected internal void Speed(PhysicsVector _newSpeed)
  1015. {
  1016. Vector3 _speed;
  1017. _speed = BulletXMaths.PhysicsVectorToXnaVector3(_newSpeed);
  1018. rigidBody.LinearVelocity = _speed;
  1019. }
  1020. protected internal void ReOrient()
  1021. {
  1022. ReOrient(_orientation);
  1023. }
  1024. protected internal void ReOrient(OpenMetaverse.Quaternion _newOrient)
  1025. {
  1026. Quaternion _newOrientation;
  1027. _newOrientation = BulletXMaths.QuaternionToXnaQuaternion(_newOrient);
  1028. Matrix _comTransform = rigidBody.CenterOfMassTransform;
  1029. BulletXMaths.SetRotation(ref _comTransform, _newOrientation);
  1030. rigidBody.CenterOfMassTransform = _comTransform;
  1031. }
  1032. protected internal void ReSize()
  1033. {
  1034. ReSize(_size);
  1035. }
  1036. protected internal virtual void ReSize(PhysicsVector _newSize)
  1037. {
  1038. }
  1039. public virtual void ScheduleTerseUpdate()
  1040. {
  1041. base.RequestPhysicsterseUpdate();
  1042. }
  1043. #endregion
  1044. public override void CrossingFailure()
  1045. {
  1046. }
  1047. public override PhysicsVector PIDTarget { set { return; } }
  1048. public override bool PIDActive { set { return; } }
  1049. public override float PIDTau { set { return; } }
  1050. public override float PIDHoverHeight { set { return; } }
  1051. public override bool PIDHoverActive { set { return; } }
  1052. public override PIDHoverType PIDHoverType { set { return; } }
  1053. public override float PIDHoverTau { set { return; } }
  1054. public override void SubscribeEvents(int ms)
  1055. {
  1056. }
  1057. public override void UnSubscribeEvents()
  1058. {
  1059. }
  1060. public override bool SubscribedEvents()
  1061. {
  1062. return false;
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// PhysicsActor Character Class for BulletX
  1067. /// </summary>
  1068. public class BulletXCharacter : BulletXActor
  1069. {
  1070. public BulletXCharacter(BulletXScene parent_scene, PhysicsVector pos)
  1071. : this(String.Empty, parent_scene, pos)
  1072. {
  1073. }
  1074. public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos)
  1075. : this(avName, parent_scene, pos, new PhysicsVector(), new PhysicsVector(), new PhysicsVector(),
  1076. OpenMetaverse.Quaternion.Identity)
  1077. {
  1078. }
  1079. public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
  1080. PhysicsVector size, PhysicsVector acceleration, OpenMetaverse.Quaternion orientation)
  1081. : base(avName)
  1082. {
  1083. //This fields will be removed. They're temporal
  1084. float _sizeX = 0.5f;
  1085. float _sizeY = 0.5f;
  1086. float _sizeZ = 1.6f;
  1087. //.
  1088. _position = pos;
  1089. _velocity = velocity;
  1090. _size = size;
  1091. //---
  1092. _size.X = _sizeX;
  1093. _size.Y = _sizeY;
  1094. _size.Z = _sizeZ;
  1095. //.
  1096. _acceleration = acceleration;
  1097. _orientation = orientation;
  1098. _physical = true;
  1099. float _mass = 50.0f; //This depends of avatar's dimensions
  1100. //For RigidBody Constructor. The next values might change
  1101. float _linearDamping = 0.0f;
  1102. float _angularDamping = 0.0f;
  1103. float _friction = 0.5f;
  1104. float _restitution = 0.0f;
  1105. Matrix _startTransform = Matrix.Identity;
  1106. Matrix _centerOfMassOffset = Matrix.Identity;
  1107. lock (BulletXScene.BulletXLock)
  1108. {
  1109. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1110. //CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(1.0f, 1.0f, 1.60f));
  1111. //For now, like ODE, collisionShape = sphere of radious = 1.0
  1112. CollisionShape _collisionShape = new SphereShape(1.0f);
  1113. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1114. Vector3 _localInertia = new Vector3();
  1115. _collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1116. rigidBody =
  1117. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1118. _friction, _restitution);
  1119. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1120. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1121. Vector3 _vDebugTranslation;
  1122. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1123. rigidBody.Translate(_vDebugTranslation);
  1124. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1125. }
  1126. }
  1127. public override int PhysicsActorType
  1128. {
  1129. get { return (int) ActorTypes.Agent; }
  1130. set { return; }
  1131. }
  1132. public override PhysicsVector Position
  1133. {
  1134. get { return base.Position; }
  1135. set { base.Position = value; }
  1136. }
  1137. public override PhysicsVector Velocity
  1138. {
  1139. get { return base.Velocity; }
  1140. set { base.Velocity = value; }
  1141. }
  1142. public override PhysicsVector Size
  1143. {
  1144. get { return base.Size; }
  1145. set { base.Size = value; }
  1146. }
  1147. public override PhysicsVector Acceleration
  1148. {
  1149. get { return base.Acceleration; }
  1150. }
  1151. public override OpenMetaverse.Quaternion Orientation
  1152. {
  1153. get { return base.Orientation; }
  1154. set { base.Orientation = value; }
  1155. }
  1156. public override bool Flying
  1157. {
  1158. get { return base.Flying; }
  1159. set { base.Flying = value; }
  1160. }
  1161. public override bool IsColliding
  1162. {
  1163. get { return base.IsColliding; }
  1164. set { base.IsColliding = value; }
  1165. }
  1166. public override bool Kinematic
  1167. {
  1168. get { return base.Kinematic; }
  1169. set { base.Kinematic = value; }
  1170. }
  1171. public override void SetAcceleration(PhysicsVector accel)
  1172. {
  1173. base.SetAcceleration(accel);
  1174. }
  1175. public override void AddForce(PhysicsVector force, bool pushforce)
  1176. {
  1177. base.AddForce(force, pushforce);
  1178. }
  1179. public override void SetMomentum(PhysicsVector momentum)
  1180. {
  1181. base.SetMomentum(momentum);
  1182. }
  1183. internal void Move(float timeStep)
  1184. {
  1185. Vector3 vec = new Vector3();
  1186. //At this point it's supossed that:
  1187. //_velocity == rigidBody.LinearVelocity
  1188. vec.X = _velocity.X;
  1189. vec.Y = _velocity.Y;
  1190. vec.Z = _velocity.Z;
  1191. if ((vec.X != 0.0f) || (vec.Y != 0.0f) || (vec.Z != 0.0f)) rigidBody.Activate();
  1192. if (flying)
  1193. {
  1194. //Antigravity with movement
  1195. if (_position.Z <= BulletXScene.HeightLevel0)
  1196. {
  1197. vec.Z += BulletXScene.Gravity*timeStep;
  1198. }
  1199. //Lowgravity with movement
  1200. else if ((_position.Z > BulletXScene.HeightLevel0)
  1201. && (_position.Z <= BulletXScene.HeightLevel1))
  1202. {
  1203. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1204. }
  1205. //Lowgravity with...
  1206. else if (_position.Z > BulletXScene.HeightLevel1)
  1207. {
  1208. if (vec.Z > 0) //no movement
  1209. vec.Z = BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1210. else
  1211. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1212. }
  1213. }
  1214. rigidBody.LinearVelocity = vec;
  1215. }
  1216. //This validation is very basic
  1217. internal override void ValidateHeight(float heighmapPositionValue)
  1218. {
  1219. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1220. {
  1221. Matrix m = rigidBody.WorldTransform;
  1222. Vector3 v3 = m.Translation;
  1223. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1224. m.Translation = v3;
  1225. rigidBody.WorldTransform = m;
  1226. //When an Avie touch the ground it's vertical velocity it's reduced to ZERO
  1227. Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1228. }
  1229. }
  1230. internal override void UpdateKinetics()
  1231. {
  1232. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1233. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1234. //Orientation it seems that it will be the default.
  1235. ReOrient();
  1236. }
  1237. }
  1238. /// <summary>
  1239. /// PhysicsActor Prim Class for BulletX
  1240. /// </summary>
  1241. public class BulletXPrim : BulletXActor
  1242. {
  1243. //Density it will depends of material.
  1244. //For now all prims have the same density, all prims are made of water. Be water my friend! :D
  1245. private const float _density = 1000.0f;
  1246. private BulletXScene _parent_scene;
  1247. private PhysicsVector m_prev_position = new PhysicsVector(0, 0, 0);
  1248. private bool m_lastUpdateSent = false;
  1249. //added by jed zhu
  1250. private IMesh _mesh;
  1251. public IMesh GetMesh() { return _mesh; }
  1252. public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector size,
  1253. OpenMetaverse.Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
  1254. : this(
  1255. primName, parent_scene, pos, new PhysicsVector(), size, new PhysicsVector(), rotation, mesh, pbs,
  1256. isPhysical)
  1257. {
  1258. }
  1259. public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
  1260. PhysicsVector size,
  1261. PhysicsVector acceleration, OpenMetaverse.Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs,
  1262. bool isPhysical)
  1263. : base(primName)
  1264. {
  1265. if ((size.X == 0) || (size.Y == 0) || (size.Z == 0))
  1266. throw new Exception("Size 0");
  1267. if (OpenMetaverse.Quaternion.Normalize(rotation).Length() == 0f)
  1268. rotation = OpenMetaverse.Quaternion.Identity;
  1269. _position = pos;
  1270. _physical = isPhysical;
  1271. _velocity = _physical ? velocity : new PhysicsVector();
  1272. _size = size;
  1273. _acceleration = acceleration;
  1274. _orientation = rotation;
  1275. _parent_scene = parent_scene;
  1276. CreateRigidBody(parent_scene, mesh, pos, size);
  1277. }
  1278. public override int PhysicsActorType
  1279. {
  1280. get { return (int) ActorTypes.Prim; }
  1281. set { return; }
  1282. }
  1283. public override PhysicsVector Position
  1284. {
  1285. get { return base.Position; }
  1286. set { base.Position = value; }
  1287. }
  1288. public override PhysicsVector Velocity
  1289. {
  1290. get { return base.Velocity; }
  1291. set { base.Velocity = value; }
  1292. }
  1293. public override PhysicsVector Size
  1294. {
  1295. get { return _size; }
  1296. set
  1297. {
  1298. lock (BulletXScene.BulletXLock)
  1299. {
  1300. _size = value;
  1301. ReSize();
  1302. }
  1303. }
  1304. }
  1305. public override PhysicsVector Acceleration
  1306. {
  1307. get { return base.Acceleration; }
  1308. }
  1309. public override OpenMetaverse.Quaternion Orientation
  1310. {
  1311. get { return base.Orientation; }
  1312. set { base.Orientation = value; }
  1313. }
  1314. public override float ActorMass
  1315. {
  1316. get
  1317. {
  1318. //For now all prims are boxes
  1319. return (_physical ? 1 : 0)*_density*_size.X*_size.Y*_size.Z;
  1320. }
  1321. }
  1322. public override bool IsPhysical
  1323. {
  1324. get { return base.IsPhysical; }
  1325. set
  1326. {
  1327. base.IsPhysical = value;
  1328. if (value)
  1329. {
  1330. //---
  1331. PhysicsPluginManager.PhysicsPluginMessage("Physical - Recreate", true);
  1332. //---
  1333. ReCreateRigidBody(_size);
  1334. }
  1335. else
  1336. {
  1337. //---
  1338. PhysicsPluginManager.PhysicsPluginMessage("Physical - SetMassProps", true);
  1339. //---
  1340. rigidBody.SetMassProps(Mass, new Vector3());
  1341. }
  1342. }
  1343. }
  1344. public override bool Flying
  1345. {
  1346. get { return base.Flying; }
  1347. set { base.Flying = value; }
  1348. }
  1349. public override bool IsColliding
  1350. {
  1351. get { return base.IsColliding; }
  1352. set { base.IsColliding = value; }
  1353. }
  1354. public override bool Kinematic
  1355. {
  1356. get { return base.Kinematic; }
  1357. set { base.Kinematic = value; }
  1358. }
  1359. public override void SetAcceleration(PhysicsVector accel)
  1360. {
  1361. lock (BulletXScene.BulletXLock)
  1362. {
  1363. _acceleration = accel;
  1364. }
  1365. }
  1366. public override void AddForce(PhysicsVector force, bool pushforce)
  1367. {
  1368. base.AddForce(force,pushforce);
  1369. }
  1370. public override void SetMomentum(PhysicsVector momentum)
  1371. {
  1372. base.SetMomentum(momentum);
  1373. }
  1374. internal override void ValidateHeight(float heighmapPositionValue)
  1375. {
  1376. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1377. {
  1378. Matrix m = rigidBody.WorldTransform;
  1379. Vector3 v3 = m.Translation;
  1380. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1381. m.Translation = v3;
  1382. rigidBody.WorldTransform = m;
  1383. //When a Prim touch the ground it's vertical velocity it's reduced to ZERO
  1384. //Static objects don't have linear velocity
  1385. if (_physical)
  1386. Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1387. }
  1388. }
  1389. internal override void UpdateKinetics()
  1390. {
  1391. if (_physical) //Updates properties. Prim updates its properties physically
  1392. {
  1393. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1394. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1395. _orientation = BulletXMaths.XnaQuaternionToQuaternion(rigidBody.Orientation);
  1396. if ((Math.Abs(m_prev_position.X - _position.X) < 0.03)
  1397. && (Math.Abs(m_prev_position.Y - _position.Y) < 0.03)
  1398. && (Math.Abs(m_prev_position.Z - _position.Z) < 0.03))
  1399. {
  1400. if (!m_lastUpdateSent)
  1401. {
  1402. _velocity = new PhysicsVector(0, 0, 0);
  1403. base.ScheduleTerseUpdate();
  1404. m_lastUpdateSent = true;
  1405. }
  1406. }
  1407. else
  1408. {
  1409. m_lastUpdateSent = false;
  1410. base.ScheduleTerseUpdate();
  1411. }
  1412. m_prev_position = _position;
  1413. }
  1414. else //Doesn't updates properties. That's a cancel
  1415. {
  1416. Translate();
  1417. //Speed(); //<- Static objects don't have linear velocity
  1418. ReOrient();
  1419. }
  1420. }
  1421. #region Methods for updating values of RigidBody
  1422. protected internal void CreateRigidBody(BulletXScene parent_scene, IMesh mesh, PhysicsVector pos,
  1423. PhysicsVector size)
  1424. {
  1425. //For RigidBody Constructor. The next values might change
  1426. float _linearDamping = 0.0f;
  1427. float _angularDamping = 0.0f;
  1428. float _friction = 1.0f;
  1429. float _restitution = 0.0f;
  1430. Matrix _startTransform = Matrix.Identity;
  1431. Matrix _centerOfMassOffset = Matrix.Identity;
  1432. //added by jed zhu
  1433. _mesh = mesh;
  1434. lock (BulletXScene.BulletXLock)
  1435. {
  1436. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1437. //For now all prims are boxes
  1438. CollisionShape _collisionShape;
  1439. if (mesh == null)
  1440. {
  1441. _collisionShape = new BoxShape(BulletXMaths.PhysicsVectorToXnaVector3(size)/2.0f);
  1442. }
  1443. else
  1444. {
  1445. int iVertexCount = mesh.getVertexList().Count;
  1446. int[] indices = mesh.getIndexListAsInt();
  1447. Vector3[] v3Vertices = new Vector3[iVertexCount];
  1448. for (int i = 0; i < iVertexCount; i++)
  1449. {
  1450. PhysicsVector v = mesh.getVertexList()[i];
  1451. if (v != null) // Note, null has special meaning. See meshing code for details
  1452. v3Vertices[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
  1453. else
  1454. v3Vertices[i] = Vector3.Zero;
  1455. }
  1456. TriangleIndexVertexArray triMesh = new TriangleIndexVertexArray(indices, v3Vertices);
  1457. _collisionShape = new TriangleMeshShape(triMesh);
  1458. }
  1459. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1460. Vector3 _localInertia = new Vector3();
  1461. if (_physical) _collisionShape.CalculateLocalInertia(Mass, out _localInertia); //Always when mass > 0
  1462. rigidBody =
  1463. new RigidBody(Mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1464. _friction, _restitution);
  1465. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1466. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1467. Vector3 _vDebugTranslation;
  1468. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1469. rigidBody.Translate(_vDebugTranslation);
  1470. //---
  1471. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1472. }
  1473. }
  1474. protected internal void ReCreateRigidBody(PhysicsVector size)
  1475. {
  1476. //There is a bug when trying to remove a rigidBody that is colliding with something..
  1477. try
  1478. {
  1479. _parent_scene.ddWorld.RemoveRigidBody(rigidBody);
  1480. }
  1481. catch (Exception ex)
  1482. {
  1483. BulletXScene.BulletXMessage(_parent_scene.is_ex_message + ex.Message, true);
  1484. rigidBody.ActivationState = ActivationState.DisableSimulation;
  1485. _parent_scene.AddForgottenRigidBody(rigidBody);
  1486. }
  1487. CreateRigidBody(_parent_scene, null, _position, size);
  1488. // Note, null for the meshing definitely is wrong. It's here for the moment to apease the compiler
  1489. if (_physical) Speed(); //Static objects don't have linear velocity
  1490. ReOrient();
  1491. GC.Collect();
  1492. }
  1493. protected internal override void ReSize(PhysicsVector _newSize)
  1494. {
  1495. //I wonder to know how to resize with a simple instruction in BulletX. It seems that for now there isn't
  1496. //so i have to do it manually. That's recreating rigidbody
  1497. ReCreateRigidBody(_newSize);
  1498. }
  1499. #endregion
  1500. }
  1501. /// <summary>
  1502. /// This Class manage a HeighField as a RigidBody. This is for to be added in the BulletXScene
  1503. /// </summary>
  1504. internal class BulletXPlanet
  1505. {
  1506. private PhysicsVector _staticPosition;
  1507. // private PhysicsVector _staticVelocity;
  1508. // private OpenMetaverse.Quaternion _staticOrientation;
  1509. private float _mass;
  1510. // private BulletXScene _parentscene;
  1511. internal float[] _heightField;
  1512. private RigidBody _flatPlanet;
  1513. internal RigidBody RigidBody
  1514. {
  1515. get { return _flatPlanet; }
  1516. }
  1517. internal BulletXPlanet(BulletXScene parent_scene, float[] heightField)
  1518. {
  1519. _staticPosition = new PhysicsVector(BulletXScene.MaxXY/2, BulletXScene.MaxXY/2, 0);
  1520. // _staticVelocity = new PhysicsVector();
  1521. // _staticOrientation = OpenMetaverse.Quaternion.Identity;
  1522. _mass = 0; //No active
  1523. // _parentscene = parent_scene;
  1524. _heightField = heightField;
  1525. float _linearDamping = 0.0f;
  1526. float _angularDamping = 0.0f;
  1527. float _friction = 0.5f;
  1528. float _restitution = 0.0f;
  1529. Matrix _startTransform = Matrix.Identity;
  1530. Matrix _centerOfMassOffset = Matrix.Identity;
  1531. lock (BulletXScene.BulletXLock)
  1532. {
  1533. try
  1534. {
  1535. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(_staticPosition);
  1536. CollisionShape _collisionShape =
  1537. new HeightfieldTerrainShape(BulletXScene.MaxXY, BulletXScene.MaxXY, _heightField,
  1538. (float) BulletXScene.MaxZ, 2, true, false);
  1539. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1540. Vector3 _localInertia = new Vector3();
  1541. //_collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1542. _flatPlanet =
  1543. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping,
  1544. _angularDamping, _friction, _restitution);
  1545. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1546. Vector3 _vDebugTranslation;
  1547. _vDebugTranslation = _startTransform.Translation - _flatPlanet.CenterOfMassPosition;
  1548. _flatPlanet.Translate(_vDebugTranslation);
  1549. parent_scene.ddWorld.AddRigidBody(_flatPlanet);
  1550. }
  1551. catch (Exception ex)
  1552. {
  1553. BulletXScene.BulletXMessage(ex.Message, true);
  1554. }
  1555. }
  1556. BulletXScene.BulletXMessage("BulletXPlanet created.", false);
  1557. }
  1558. internal float HeightValue(Vector3 position)
  1559. {
  1560. int li_x, li_y;
  1561. float height;
  1562. li_x = (int) Math.Round(position.X);
  1563. if (li_x < 0) li_x = 0;
  1564. if (li_x >= BulletXScene.MaxXY) li_x = BulletXScene.MaxXY - 1;
  1565. li_y = (int) Math.Round(position.Y);
  1566. if (li_y < 0) li_y = 0;
  1567. if (li_y >= BulletXScene.MaxXY) li_y = BulletXScene.MaxXY - 1;
  1568. height = ((HeightfieldTerrainShape) _flatPlanet.CollisionShape).getHeightFieldValue(li_x, li_y);
  1569. if (height < 0) height = 0;
  1570. else if (height > BulletXScene.MaxZ) height = BulletXScene.MaxZ;
  1571. return height;
  1572. }
  1573. }
  1574. }