BulletXPlugin.cs 59 KB

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