BulletXPlugin.cs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  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)
  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. lock (BulletXLock)
  495. {
  496. newAv = new BulletXCharacter(avName, this, pos);
  497. _characters.Add(newAv.RigidBody, newAv);
  498. }
  499. return newAv;
  500. }
  501. public override void RemoveAvatar(PhysicsActor actor)
  502. {
  503. if (actor is BulletXCharacter)
  504. {
  505. lock (BulletXLock)
  506. {
  507. try
  508. {
  509. ddWorld.RemoveRigidBody(((BulletXCharacter) actor).RigidBody);
  510. }
  511. catch (Exception ex)
  512. {
  513. BulletXMessage(is_ex_message + ex.Message, true);
  514. ((BulletXCharacter) actor).RigidBody.ActivationState = ActivationState.DisableSimulation;
  515. AddForgottenRigidBody(((BulletXCharacter) actor).RigidBody);
  516. }
  517. _characters.Remove(((BulletXCharacter) actor).RigidBody);
  518. }
  519. GC.Collect();
  520. }
  521. }
  522. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
  523. PhysicsVector size, OpenMetaverse.Quaternion rotation)
  524. {
  525. return AddPrimShape(primName, pbs, position, size, rotation, false);
  526. }
  527. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
  528. PhysicsVector size, OpenMetaverse.Quaternion rotation, bool isPhysical)
  529. {
  530. PhysicsActor result;
  531. switch (pbs.ProfileShape)
  532. {
  533. case ProfileShape.Square:
  534. /// support simple box & hollow box now; later, more shapes
  535. if (pbs.ProfileHollow == 0)
  536. {
  537. result = AddPrim(primName, position, size, rotation, null, null, isPhysical);
  538. }
  539. else
  540. {
  541. IMesh mesh = mesher.CreateMesh(primName, pbs, size, 32f, isPhysical);
  542. result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical);
  543. }
  544. break;
  545. default:
  546. result = AddPrim(primName, position, size, rotation, null, null, isPhysical);
  547. break;
  548. }
  549. return result;
  550. }
  551. public PhysicsActor AddPrim(String name, PhysicsVector position, PhysicsVector size, OpenMetaverse.Quaternion rotation,
  552. IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
  553. {
  554. BulletXPrim newPrim = null;
  555. lock (BulletXLock)
  556. {
  557. newPrim = new BulletXPrim(name, this, position, size, rotation, mesh, pbs, isPhysical);
  558. _prims.Add(newPrim.RigidBody, newPrim);
  559. }
  560. return newPrim;
  561. }
  562. public override void RemovePrim(PhysicsActor prim)
  563. {
  564. if (prim is BulletXPrim)
  565. {
  566. lock (BulletXLock)
  567. {
  568. try
  569. {
  570. ddWorld.RemoveRigidBody(((BulletXPrim) prim).RigidBody);
  571. }
  572. catch (Exception ex)
  573. {
  574. BulletXMessage(is_ex_message + ex.Message, true);
  575. ((BulletXPrim) prim).RigidBody.ActivationState = ActivationState.DisableSimulation;
  576. AddForgottenRigidBody(((BulletXPrim) prim).RigidBody);
  577. }
  578. _prims.Remove(((BulletXPrim) prim).RigidBody);
  579. }
  580. GC.Collect();
  581. }
  582. }
  583. public override void AddPhysicsActorTaint(PhysicsActor prim)
  584. {
  585. }
  586. public override float Simulate(float timeStep)
  587. {
  588. float fps = 0;
  589. lock (BulletXLock)
  590. {
  591. //Try to remove garbage
  592. RemoveForgottenRigidBodies();
  593. //End of remove
  594. MoveAPrimitives(timeStep);
  595. fps = (timeStep*simulationSubSteps);
  596. ddWorld.StepSimulation(timeStep, simulationSubSteps, timeStep);
  597. //Extra Heightmap Validation: BulletX's HeightFieldTerrain somestimes doesn't work so fine.
  598. ValidateHeightForAll();
  599. //End heightmap validation.
  600. UpdateKineticsForAll();
  601. }
  602. return fps;
  603. }
  604. private void MoveAPrimitives(float timeStep)
  605. {
  606. foreach (BulletXCharacter actor in _characters.Values)
  607. {
  608. actor.Move(timeStep);
  609. }
  610. }
  611. private void ValidateHeightForAll()
  612. {
  613. float _height;
  614. foreach (BulletXCharacter actor in _characters.Values)
  615. {
  616. //_height = HeightValue(actor.RigidBodyPosition);
  617. _height = _simFlatPlanet.HeightValue(actor.RigidBodyPosition);
  618. actor.ValidateHeight(_height);
  619. //if (_simFlatPlanet.heightIsNotValid(actor.RigidBodyPosition, out _height)) actor.ValidateHeight(_height);
  620. }
  621. foreach (BulletXPrim prim in _prims.Values)
  622. {
  623. //_height = HeightValue(prim.RigidBodyPosition);
  624. _height = _simFlatPlanet.HeightValue(prim.RigidBodyPosition);
  625. prim.ValidateHeight(_height);
  626. //if (_simFlatPlanet.heightIsNotValid(prim.RigidBodyPosition, out _height)) prim.ValidateHeight(_height);
  627. }
  628. //foreach (BulletXCharacter actor in _characters)
  629. //{
  630. // actor.ValidateHeight(0);
  631. //}
  632. //foreach (BulletXPrim prim in _prims)
  633. //{
  634. // prim.ValidateHeight(0);
  635. //}
  636. }
  637. private void UpdateKineticsForAll()
  638. {
  639. //UpdatePosition > UpdateKinetics.
  640. //Not only position will be updated, also velocity cause acceleration.
  641. foreach (BulletXCharacter actor in _characters.Values)
  642. {
  643. actor.UpdateKinetics();
  644. }
  645. foreach (BulletXPrim prim in _prims.Values)
  646. {
  647. prim.UpdateKinetics();
  648. }
  649. //if (this._simFlatPlanet!=null) this._simFlatPlanet.Restore();
  650. }
  651. public override void GetResults()
  652. {
  653. }
  654. public override bool IsThreaded
  655. {
  656. get
  657. {
  658. return (false); // for now we won't be multithreaded
  659. }
  660. }
  661. public override void SetTerrain(float[] heightMap)
  662. {
  663. ////As the same as ODE, heightmap (x,y) must be swapped for BulletX
  664. //for (int i = 0; i < 65536; i++)
  665. //{
  666. // // this._heightmap[i] = (double)heightMap[i];
  667. // // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
  668. // int x = i & 0xff;
  669. // int y = i >> 8;
  670. // this._heightmap[i] = heightMap[x * 256 + y];
  671. //}
  672. //float[] swappedHeightMap = new float[65536];
  673. ////As the same as ODE, heightmap (x,y) must be swapped for BulletX
  674. //for (int i = 0; i < 65536; i++)
  675. //{
  676. // // this._heightmap[i] = (double)heightMap[i];
  677. // // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
  678. // int x = i & 0xff;
  679. // int y = i >> 8;
  680. // swappedHeightMap[i] = heightMap[x * 256 + y];
  681. //}
  682. DeleteTerrain();
  683. //There is a BulletXLock inside the constructor of BulletXPlanet
  684. //this._simFlatPlanet = new BulletXPlanet(this, swappedHeightMap);
  685. _simFlatPlanet = new BulletXPlanet(this, heightMap);
  686. //this._heightmap = heightMap;
  687. }
  688. public override void DeleteTerrain()
  689. {
  690. if (_simFlatPlanet != null)
  691. {
  692. lock (BulletXLock)
  693. {
  694. try
  695. {
  696. ddWorld.RemoveRigidBody(_simFlatPlanet.RigidBody);
  697. }
  698. catch (Exception ex)
  699. {
  700. BulletXMessage(is_ex_message + ex.Message, true);
  701. _simFlatPlanet.RigidBody.ActivationState = ActivationState.DisableSimulation;
  702. AddForgottenRigidBody(_simFlatPlanet.RigidBody);
  703. }
  704. }
  705. _simFlatPlanet = null;
  706. GC.Collect();
  707. BulletXMessage("Terrain erased!", false);
  708. }
  709. //this._heightmap = null;
  710. }
  711. internal void AddForgottenRigidBody(RigidBody forgottenRigidBody)
  712. {
  713. _forgottenRigidBodies.Add(forgottenRigidBody);
  714. }
  715. private void RemoveForgottenRigidBodies()
  716. {
  717. RigidBody forgottenRigidBody;
  718. int nRigidBodies = _forgottenRigidBodies.Count;
  719. for (int i = nRigidBodies - 1; i >= 0; i--)
  720. {
  721. forgottenRigidBody = _forgottenRigidBodies[i];
  722. try
  723. {
  724. ddWorld.RemoveRigidBody(forgottenRigidBody);
  725. _forgottenRigidBodies.Remove(forgottenRigidBody);
  726. BulletXMessage("Forgotten Rigid Body Removed", false);
  727. }
  728. catch (Exception ex)
  729. {
  730. BulletXMessage("Can't remove forgottenRigidBody!: " + ex.Message, false);
  731. }
  732. }
  733. GC.Collect();
  734. }
  735. internal static void BulletXMessage(string message, bool isWarning)
  736. {
  737. PhysicsPluginManager.PhysicsPluginMessage("[Modified BulletX]:\t" + message, isWarning);
  738. }
  739. //temp
  740. //private float HeightValue(MonoXnaCompactMaths.Vector3 position)
  741. //{
  742. // int li_x, li_y;
  743. // float height;
  744. // li_x = (int)Math.Round(position.X); if (li_x < 0) li_x = 0;
  745. // li_y = (int)Math.Round(position.Y); if (li_y < 0) li_y = 0;
  746. // height = this._heightmap[li_y * 256 + li_x];
  747. // if (height < 0) height = 0;
  748. // else if (height > maxZ) height = maxZ;
  749. // return height;
  750. //}
  751. }
  752. /// <summary>
  753. /// Generic Physics Actor for BulletX inherit from PhysicActor
  754. /// </summary>
  755. public class BulletXActor : PhysicsActor
  756. {
  757. protected bool flying = false;
  758. protected bool _physical = false;
  759. protected PhysicsVector _position;
  760. protected PhysicsVector _velocity;
  761. protected PhysicsVector _size;
  762. protected PhysicsVector _acceleration;
  763. protected OpenMetaverse.Quaternion _orientation;
  764. protected PhysicsVector m_rotationalVelocity = PhysicsVector.Zero;
  765. protected RigidBody rigidBody;
  766. protected int m_PhysicsActorType;
  767. private Boolean iscolliding = false;
  768. internal string _name;
  769. public BulletXActor(String name)
  770. {
  771. _name = name;
  772. }
  773. public override bool Stopped
  774. {
  775. get { return false; }
  776. }
  777. public override PhysicsVector Position
  778. {
  779. get { return _position; }
  780. set
  781. {
  782. lock (BulletXScene.BulletXLock)
  783. {
  784. _position = value;
  785. Translate();
  786. }
  787. }
  788. }
  789. public override PhysicsVector RotationalVelocity
  790. {
  791. get { return m_rotationalVelocity; }
  792. set { m_rotationalVelocity = value; }
  793. }
  794. public override PhysicsVector Velocity
  795. {
  796. get { return _velocity; }
  797. set
  798. {
  799. lock (BulletXScene.BulletXLock)
  800. {
  801. //Static objects don' have linear velocity
  802. if (_physical)
  803. {
  804. _velocity = value;
  805. Speed();
  806. }
  807. else
  808. {
  809. _velocity = new PhysicsVector();
  810. }
  811. }
  812. }
  813. }
  814. public override float CollisionScore
  815. {
  816. get { return 0f; }
  817. set { }
  818. }
  819. public override PhysicsVector Size
  820. {
  821. get { return _size; }
  822. set
  823. {
  824. lock (BulletXScene.BulletXLock)
  825. {
  826. _size = value;
  827. }
  828. }
  829. }
  830. public override PhysicsVector Force
  831. {
  832. get { return PhysicsVector.Zero; }
  833. set { return; }
  834. }
  835. public override int VehicleType
  836. {
  837. get { return 0; }
  838. set { return; }
  839. }
  840. public override void VehicleFloatParam(int param, float value)
  841. {
  842. }
  843. public override void VehicleVectorParam(int param, PhysicsVector value)
  844. {
  845. }
  846. public override void VehicleRotationParam(int param, OpenMetaverse.Quaternion rotation)
  847. {
  848. }
  849. public override void SetVolumeDetect(int param)
  850. {
  851. }
  852. public override PhysicsVector CenterOfMass
  853. {
  854. get { return PhysicsVector.Zero; }
  855. }
  856. public override PhysicsVector GeometricCenter
  857. {
  858. get { return PhysicsVector.Zero; }
  859. }
  860. public override PrimitiveBaseShape Shape
  861. {
  862. set { return; }
  863. }
  864. public override bool SetAlwaysRun
  865. {
  866. get { return false; }
  867. set { return; }
  868. }
  869. public override PhysicsVector Acceleration
  870. {
  871. get { return _acceleration; }
  872. }
  873. public override OpenMetaverse.Quaternion Orientation
  874. {
  875. get { return _orientation; }
  876. set
  877. {
  878. lock (BulletXScene.BulletXLock)
  879. {
  880. _orientation = value;
  881. ReOrient();
  882. }
  883. }
  884. }
  885. public override void link(PhysicsActor obj)
  886. {
  887. }
  888. public override void delink()
  889. {
  890. }
  891. public override void LockAngularMotion(PhysicsVector axis)
  892. {
  893. }
  894. public override float Mass
  895. {
  896. get { return ActorMass; }
  897. }
  898. public virtual float ActorMass
  899. {
  900. get { return 0; }
  901. }
  902. public override int PhysicsActorType
  903. {
  904. get { return (int) m_PhysicsActorType; }
  905. set { m_PhysicsActorType = value; }
  906. }
  907. public RigidBody RigidBody
  908. {
  909. get { return rigidBody; }
  910. }
  911. public Vector3 RigidBodyPosition
  912. {
  913. get { return rigidBody.CenterOfMassPosition; }
  914. }
  915. public override bool IsPhysical
  916. {
  917. get { return _physical; }
  918. set { _physical = value; }
  919. }
  920. public override bool Flying
  921. {
  922. get { return flying; }
  923. set { flying = value; }
  924. }
  925. public override bool ThrottleUpdates
  926. {
  927. get { return false; }
  928. set { return; }
  929. }
  930. public override bool IsColliding
  931. {
  932. get { return iscolliding; }
  933. set { iscolliding = value; }
  934. }
  935. public override bool CollidingGround
  936. {
  937. get { return false; }
  938. set { return; }
  939. }
  940. public override bool CollidingObj
  941. {
  942. get { return false; }
  943. set { return; }
  944. }
  945. public override uint LocalID
  946. {
  947. set { return; }
  948. }
  949. public override bool Grabbed
  950. {
  951. set { return; }
  952. }
  953. public override bool Selected
  954. {
  955. set { return; }
  956. }
  957. public override float Buoyancy
  958. {
  959. get { return 0f; }
  960. set { return; }
  961. }
  962. public override bool FloatOnWater
  963. {
  964. set { return; }
  965. }
  966. public virtual void SetAcceleration(PhysicsVector accel)
  967. {
  968. lock (BulletXScene.BulletXLock)
  969. {
  970. _acceleration = accel;
  971. }
  972. }
  973. public override bool Kinematic
  974. {
  975. get { return false; }
  976. set { }
  977. }
  978. public override void AddForce(PhysicsVector force, bool pushforce)
  979. {
  980. }
  981. public override PhysicsVector Torque
  982. {
  983. get { return PhysicsVector.Zero; }
  984. set { return; }
  985. }
  986. public override void AddAngularForce(PhysicsVector force, bool pushforce)
  987. {
  988. }
  989. public override void SetMomentum(PhysicsVector momentum)
  990. {
  991. }
  992. internal virtual void ValidateHeight(float heighmapPositionValue)
  993. {
  994. }
  995. internal virtual void UpdateKinetics()
  996. {
  997. }
  998. #region Methods for updating values of RigidBody
  999. protected internal void Translate()
  1000. {
  1001. Translate(_position);
  1002. }
  1003. protected internal void Translate(PhysicsVector _newPos)
  1004. {
  1005. Vector3 _translation;
  1006. _translation = BulletXMaths.PhysicsVectorToXnaVector3(_newPos) - rigidBody.CenterOfMassPosition;
  1007. rigidBody.Translate(_translation);
  1008. }
  1009. protected internal void Speed()
  1010. {
  1011. Speed(_velocity);
  1012. }
  1013. protected internal void Speed(PhysicsVector _newSpeed)
  1014. {
  1015. Vector3 _speed;
  1016. _speed = BulletXMaths.PhysicsVectorToXnaVector3(_newSpeed);
  1017. rigidBody.LinearVelocity = _speed;
  1018. }
  1019. protected internal void ReOrient()
  1020. {
  1021. ReOrient(_orientation);
  1022. }
  1023. protected internal void ReOrient(OpenMetaverse.Quaternion _newOrient)
  1024. {
  1025. Quaternion _newOrientation;
  1026. _newOrientation = BulletXMaths.QuaternionToXnaQuaternion(_newOrient);
  1027. Matrix _comTransform = rigidBody.CenterOfMassTransform;
  1028. BulletXMaths.SetRotation(ref _comTransform, _newOrientation);
  1029. rigidBody.CenterOfMassTransform = _comTransform;
  1030. }
  1031. protected internal void ReSize()
  1032. {
  1033. ReSize(_size);
  1034. }
  1035. protected internal virtual void ReSize(PhysicsVector _newSize)
  1036. {
  1037. }
  1038. public virtual void ScheduleTerseUpdate()
  1039. {
  1040. base.RequestPhysicsterseUpdate();
  1041. }
  1042. #endregion
  1043. public override void CrossingFailure()
  1044. {
  1045. }
  1046. public override PhysicsVector PIDTarget { set { return; } }
  1047. public override bool PIDActive { set { return; } }
  1048. public override float PIDTau { set { return; } }
  1049. public override void SubscribeEvents(int ms)
  1050. {
  1051. }
  1052. public override void UnSubscribeEvents()
  1053. {
  1054. }
  1055. public override bool SubscribedEvents()
  1056. {
  1057. return false;
  1058. }
  1059. }
  1060. /// <summary>
  1061. /// PhysicsActor Character Class for BulletX
  1062. /// </summary>
  1063. public class BulletXCharacter : BulletXActor
  1064. {
  1065. public BulletXCharacter(BulletXScene parent_scene, PhysicsVector pos)
  1066. : this(String.Empty, parent_scene, pos)
  1067. {
  1068. }
  1069. public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos)
  1070. : this(avName, parent_scene, pos, new PhysicsVector(), new PhysicsVector(), new PhysicsVector(),
  1071. OpenMetaverse.Quaternion.Identity)
  1072. {
  1073. }
  1074. public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
  1075. PhysicsVector size, PhysicsVector acceleration, OpenMetaverse.Quaternion orientation)
  1076. : base(avName)
  1077. {
  1078. //This fields will be removed. They're temporal
  1079. float _sizeX = 0.5f;
  1080. float _sizeY = 0.5f;
  1081. float _sizeZ = 1.6f;
  1082. //.
  1083. _position = pos;
  1084. _velocity = velocity;
  1085. _size = size;
  1086. //---
  1087. _size.X = _sizeX;
  1088. _size.Y = _sizeY;
  1089. _size.Z = _sizeZ;
  1090. //.
  1091. _acceleration = acceleration;
  1092. _orientation = orientation;
  1093. _physical = true;
  1094. float _mass = 50.0f; //This depends of avatar's dimensions
  1095. //For RigidBody Constructor. The next values might change
  1096. float _linearDamping = 0.0f;
  1097. float _angularDamping = 0.0f;
  1098. float _friction = 0.5f;
  1099. float _restitution = 0.0f;
  1100. Matrix _startTransform = Matrix.Identity;
  1101. Matrix _centerOfMassOffset = Matrix.Identity;
  1102. lock (BulletXScene.BulletXLock)
  1103. {
  1104. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1105. //CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(1.0f, 1.0f, 1.60f));
  1106. //For now, like ODE, collisionShape = sphere of radious = 1.0
  1107. CollisionShape _collisionShape = new SphereShape(1.0f);
  1108. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1109. Vector3 _localInertia = new Vector3();
  1110. _collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1111. rigidBody =
  1112. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1113. _friction, _restitution);
  1114. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1115. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1116. Vector3 _vDebugTranslation;
  1117. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1118. rigidBody.Translate(_vDebugTranslation);
  1119. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1120. }
  1121. }
  1122. public override int PhysicsActorType
  1123. {
  1124. get { return (int) ActorTypes.Agent; }
  1125. set { return; }
  1126. }
  1127. public override PhysicsVector Position
  1128. {
  1129. get { return base.Position; }
  1130. set { base.Position = value; }
  1131. }
  1132. public override PhysicsVector Velocity
  1133. {
  1134. get { return base.Velocity; }
  1135. set { base.Velocity = value; }
  1136. }
  1137. public override PhysicsVector Size
  1138. {
  1139. get { return base.Size; }
  1140. set { base.Size = value; }
  1141. }
  1142. public override PhysicsVector Acceleration
  1143. {
  1144. get { return base.Acceleration; }
  1145. }
  1146. public override OpenMetaverse.Quaternion Orientation
  1147. {
  1148. get { return base.Orientation; }
  1149. set { base.Orientation = value; }
  1150. }
  1151. public override bool Flying
  1152. {
  1153. get { return base.Flying; }
  1154. set { base.Flying = value; }
  1155. }
  1156. public override bool IsColliding
  1157. {
  1158. get { return base.IsColliding; }
  1159. set { base.IsColliding = value; }
  1160. }
  1161. public override bool Kinematic
  1162. {
  1163. get { return base.Kinematic; }
  1164. set { base.Kinematic = value; }
  1165. }
  1166. public override void SetAcceleration(PhysicsVector accel)
  1167. {
  1168. base.SetAcceleration(accel);
  1169. }
  1170. public override void AddForce(PhysicsVector force, bool pushforce)
  1171. {
  1172. base.AddForce(force, pushforce);
  1173. }
  1174. public override void SetMomentum(PhysicsVector momentum)
  1175. {
  1176. base.SetMomentum(momentum);
  1177. }
  1178. internal void Move(float timeStep)
  1179. {
  1180. Vector3 vec = new Vector3();
  1181. //At this point it's supossed that:
  1182. //_velocity == rigidBody.LinearVelocity
  1183. vec.X = _velocity.X;
  1184. vec.Y = _velocity.Y;
  1185. vec.Z = _velocity.Z;
  1186. if ((vec.X != 0.0f) || (vec.Y != 0.0f) || (vec.Z != 0.0f)) rigidBody.Activate();
  1187. if (flying)
  1188. {
  1189. //Antigravity with movement
  1190. if (_position.Z <= BulletXScene.HeightLevel0)
  1191. {
  1192. vec.Z += BulletXScene.Gravity*timeStep;
  1193. }
  1194. //Lowgravity with movement
  1195. else if ((_position.Z > BulletXScene.HeightLevel0)
  1196. && (_position.Z <= BulletXScene.HeightLevel1))
  1197. {
  1198. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1199. }
  1200. //Lowgravity with...
  1201. else if (_position.Z > BulletXScene.HeightLevel1)
  1202. {
  1203. if (vec.Z > 0) //no movement
  1204. vec.Z = BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1205. else
  1206. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1207. }
  1208. }
  1209. rigidBody.LinearVelocity = vec;
  1210. }
  1211. //This validation is very basic
  1212. internal override void ValidateHeight(float heighmapPositionValue)
  1213. {
  1214. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1215. {
  1216. Matrix m = rigidBody.WorldTransform;
  1217. Vector3 v3 = m.Translation;
  1218. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1219. m.Translation = v3;
  1220. rigidBody.WorldTransform = m;
  1221. //When an Avie touch the ground it's vertical velocity it's reduced to ZERO
  1222. Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1223. }
  1224. }
  1225. internal override void UpdateKinetics()
  1226. {
  1227. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1228. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1229. //Orientation it seems that it will be the default.
  1230. ReOrient();
  1231. }
  1232. }
  1233. /// <summary>
  1234. /// PhysicsActor Prim Class for BulletX
  1235. /// </summary>
  1236. public class BulletXPrim : BulletXActor
  1237. {
  1238. //Density it will depends of material.
  1239. //For now all prims have the same density, all prims are made of water. Be water my friend! :D
  1240. private const float _density = 1000.0f;
  1241. private BulletXScene _parent_scene;
  1242. private PhysicsVector m_prev_position = new PhysicsVector(0, 0, 0);
  1243. private bool m_lastUpdateSent = false;
  1244. //added by jed zhu
  1245. private IMesh _mesh;
  1246. public IMesh GetMesh() { return _mesh; }
  1247. public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector size,
  1248. OpenMetaverse.Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
  1249. : this(
  1250. primName, parent_scene, pos, new PhysicsVector(), size, new PhysicsVector(), rotation, mesh, pbs,
  1251. isPhysical)
  1252. {
  1253. }
  1254. public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
  1255. PhysicsVector size,
  1256. PhysicsVector acceleration, OpenMetaverse.Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs,
  1257. bool isPhysical)
  1258. : base(primName)
  1259. {
  1260. if ((size.X == 0) || (size.Y == 0) || (size.Z == 0))
  1261. throw new Exception("Size 0");
  1262. if (OpenMetaverse.Quaternion.Normalize(rotation).Length() == 0f)
  1263. rotation = OpenMetaverse.Quaternion.Identity;
  1264. _position = pos;
  1265. _physical = isPhysical;
  1266. _velocity = _physical ? velocity : new PhysicsVector();
  1267. _size = size;
  1268. _acceleration = acceleration;
  1269. _orientation = rotation;
  1270. _parent_scene = parent_scene;
  1271. CreateRigidBody(parent_scene, mesh, pos, size);
  1272. }
  1273. public override int PhysicsActorType
  1274. {
  1275. get { return (int) ActorTypes.Prim; }
  1276. set { return; }
  1277. }
  1278. public override PhysicsVector Position
  1279. {
  1280. get { return base.Position; }
  1281. set { base.Position = value; }
  1282. }
  1283. public override PhysicsVector Velocity
  1284. {
  1285. get { return base.Velocity; }
  1286. set { base.Velocity = value; }
  1287. }
  1288. public override PhysicsVector Size
  1289. {
  1290. get { return _size; }
  1291. set
  1292. {
  1293. lock (BulletXScene.BulletXLock)
  1294. {
  1295. _size = value;
  1296. ReSize();
  1297. }
  1298. }
  1299. }
  1300. public override PhysicsVector Acceleration
  1301. {
  1302. get { return base.Acceleration; }
  1303. }
  1304. public override OpenMetaverse.Quaternion Orientation
  1305. {
  1306. get { return base.Orientation; }
  1307. set { base.Orientation = value; }
  1308. }
  1309. public override float ActorMass
  1310. {
  1311. get
  1312. {
  1313. //For now all prims are boxes
  1314. return (_physical ? 1 : 0)*_density*_size.X*_size.Y*_size.Z;
  1315. }
  1316. }
  1317. public override bool IsPhysical
  1318. {
  1319. get { return base.IsPhysical; }
  1320. set
  1321. {
  1322. base.IsPhysical = value;
  1323. if (value)
  1324. {
  1325. //---
  1326. PhysicsPluginManager.PhysicsPluginMessage("Physical - Recreate", true);
  1327. //---
  1328. ReCreateRigidBody(_size);
  1329. }
  1330. else
  1331. {
  1332. //---
  1333. PhysicsPluginManager.PhysicsPluginMessage("Physical - SetMassProps", true);
  1334. //---
  1335. rigidBody.SetMassProps(Mass, new Vector3());
  1336. }
  1337. }
  1338. }
  1339. public override bool Flying
  1340. {
  1341. get { return base.Flying; }
  1342. set { base.Flying = value; }
  1343. }
  1344. public override bool IsColliding
  1345. {
  1346. get { return base.IsColliding; }
  1347. set { base.IsColliding = value; }
  1348. }
  1349. public override bool Kinematic
  1350. {
  1351. get { return base.Kinematic; }
  1352. set { base.Kinematic = value; }
  1353. }
  1354. public override void SetAcceleration(PhysicsVector accel)
  1355. {
  1356. lock (BulletXScene.BulletXLock)
  1357. {
  1358. _acceleration = accel;
  1359. }
  1360. }
  1361. public override void AddForce(PhysicsVector force, bool pushforce)
  1362. {
  1363. base.AddForce(force,pushforce);
  1364. }
  1365. public override void SetMomentum(PhysicsVector momentum)
  1366. {
  1367. base.SetMomentum(momentum);
  1368. }
  1369. internal override void ValidateHeight(float heighmapPositionValue)
  1370. {
  1371. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1372. {
  1373. Matrix m = rigidBody.WorldTransform;
  1374. Vector3 v3 = m.Translation;
  1375. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1376. m.Translation = v3;
  1377. rigidBody.WorldTransform = m;
  1378. //When a Prim touch the ground it's vertical velocity it's reduced to ZERO
  1379. //Static objects don't have linear velocity
  1380. if (_physical)
  1381. Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1382. }
  1383. }
  1384. internal override void UpdateKinetics()
  1385. {
  1386. if (_physical) //Updates properties. Prim updates its properties physically
  1387. {
  1388. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1389. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1390. _orientation = BulletXMaths.XnaQuaternionToQuaternion(rigidBody.Orientation);
  1391. if ((Math.Abs(m_prev_position.X - _position.X) < 0.03)
  1392. && (Math.Abs(m_prev_position.Y - _position.Y) < 0.03)
  1393. && (Math.Abs(m_prev_position.Z - _position.Z) < 0.03))
  1394. {
  1395. if (!m_lastUpdateSent)
  1396. {
  1397. _velocity = new PhysicsVector(0, 0, 0);
  1398. base.ScheduleTerseUpdate();
  1399. m_lastUpdateSent = true;
  1400. }
  1401. }
  1402. else
  1403. {
  1404. m_lastUpdateSent = false;
  1405. base.ScheduleTerseUpdate();
  1406. }
  1407. m_prev_position = _position;
  1408. }
  1409. else //Doesn't updates properties. That's a cancel
  1410. {
  1411. Translate();
  1412. //Speed(); //<- Static objects don't have linear velocity
  1413. ReOrient();
  1414. }
  1415. }
  1416. #region Methods for updating values of RigidBody
  1417. protected internal void CreateRigidBody(BulletXScene parent_scene, IMesh mesh, PhysicsVector pos,
  1418. PhysicsVector size)
  1419. {
  1420. //For RigidBody Constructor. The next values might change
  1421. float _linearDamping = 0.0f;
  1422. float _angularDamping = 0.0f;
  1423. float _friction = 1.0f;
  1424. float _restitution = 0.0f;
  1425. Matrix _startTransform = Matrix.Identity;
  1426. Matrix _centerOfMassOffset = Matrix.Identity;
  1427. //added by jed zhu
  1428. _mesh = mesh;
  1429. lock (BulletXScene.BulletXLock)
  1430. {
  1431. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1432. //For now all prims are boxes
  1433. CollisionShape _collisionShape;
  1434. if (mesh == null)
  1435. {
  1436. _collisionShape = new BoxShape(BulletXMaths.PhysicsVectorToXnaVector3(size)/2.0f);
  1437. }
  1438. else
  1439. {
  1440. int iVertexCount = mesh.getVertexList().Count;
  1441. int[] indices = mesh.getIndexListAsInt();
  1442. Vector3[] v3Vertices = new Vector3[iVertexCount];
  1443. for (int i = 0; i < iVertexCount; i++)
  1444. {
  1445. PhysicsVector v = mesh.getVertexList()[i];
  1446. if (v != null) // Note, null has special meaning. See meshing code for details
  1447. v3Vertices[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
  1448. else
  1449. v3Vertices[i] = Vector3.Zero;
  1450. }
  1451. TriangleIndexVertexArray triMesh = new TriangleIndexVertexArray(indices, v3Vertices);
  1452. _collisionShape = new TriangleMeshShape(triMesh);
  1453. }
  1454. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1455. Vector3 _localInertia = new Vector3();
  1456. if (_physical) _collisionShape.CalculateLocalInertia(Mass, out _localInertia); //Always when mass > 0
  1457. rigidBody =
  1458. new RigidBody(Mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1459. _friction, _restitution);
  1460. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1461. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1462. Vector3 _vDebugTranslation;
  1463. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1464. rigidBody.Translate(_vDebugTranslation);
  1465. //---
  1466. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1467. }
  1468. }
  1469. protected internal void ReCreateRigidBody(PhysicsVector size)
  1470. {
  1471. //There is a bug when trying to remove a rigidBody that is colliding with something..
  1472. try
  1473. {
  1474. _parent_scene.ddWorld.RemoveRigidBody(rigidBody);
  1475. }
  1476. catch (Exception ex)
  1477. {
  1478. BulletXScene.BulletXMessage(_parent_scene.is_ex_message + ex.Message, true);
  1479. rigidBody.ActivationState = ActivationState.DisableSimulation;
  1480. _parent_scene.AddForgottenRigidBody(rigidBody);
  1481. }
  1482. CreateRigidBody(_parent_scene, null, _position, size);
  1483. // Note, null for the meshing definitely is wrong. It's here for the moment to apease the compiler
  1484. if (_physical) Speed(); //Static objects don't have linear velocity
  1485. ReOrient();
  1486. GC.Collect();
  1487. }
  1488. protected internal override void ReSize(PhysicsVector _newSize)
  1489. {
  1490. //I wonder to know how to resize with a simple instruction in BulletX. It seems that for now there isn't
  1491. //so i have to do it manually. That's recreating rigidbody
  1492. ReCreateRigidBody(_newSize);
  1493. }
  1494. #endregion
  1495. }
  1496. /// <summary>
  1497. /// This Class manage a HeighField as a RigidBody. This is for to be added in the BulletXScene
  1498. /// </summary>
  1499. internal class BulletXPlanet
  1500. {
  1501. private PhysicsVector _staticPosition;
  1502. // private PhysicsVector _staticVelocity;
  1503. // private OpenMetaverse.Quaternion _staticOrientation;
  1504. private float _mass;
  1505. // private BulletXScene _parentscene;
  1506. internal float[] _heightField;
  1507. private RigidBody _flatPlanet;
  1508. internal RigidBody RigidBody
  1509. {
  1510. get { return _flatPlanet; }
  1511. }
  1512. internal BulletXPlanet(BulletXScene parent_scene, float[] heightField)
  1513. {
  1514. _staticPosition = new PhysicsVector(BulletXScene.MaxXY/2, BulletXScene.MaxXY/2, 0);
  1515. // _staticVelocity = new PhysicsVector();
  1516. // _staticOrientation = OpenMetaverse.Quaternion.Identity;
  1517. _mass = 0; //No active
  1518. // _parentscene = parent_scene;
  1519. _heightField = heightField;
  1520. float _linearDamping = 0.0f;
  1521. float _angularDamping = 0.0f;
  1522. float _friction = 0.5f;
  1523. float _restitution = 0.0f;
  1524. Matrix _startTransform = Matrix.Identity;
  1525. Matrix _centerOfMassOffset = Matrix.Identity;
  1526. lock (BulletXScene.BulletXLock)
  1527. {
  1528. try
  1529. {
  1530. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(_staticPosition);
  1531. CollisionShape _collisionShape =
  1532. new HeightfieldTerrainShape(BulletXScene.MaxXY, BulletXScene.MaxXY, _heightField,
  1533. (float) BulletXScene.MaxZ, 2, true, false);
  1534. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1535. Vector3 _localInertia = new Vector3();
  1536. //_collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1537. _flatPlanet =
  1538. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping,
  1539. _angularDamping, _friction, _restitution);
  1540. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1541. Vector3 _vDebugTranslation;
  1542. _vDebugTranslation = _startTransform.Translation - _flatPlanet.CenterOfMassPosition;
  1543. _flatPlanet.Translate(_vDebugTranslation);
  1544. parent_scene.ddWorld.AddRigidBody(_flatPlanet);
  1545. }
  1546. catch (Exception ex)
  1547. {
  1548. BulletXScene.BulletXMessage(ex.Message, true);
  1549. }
  1550. }
  1551. BulletXScene.BulletXMessage("BulletXPlanet created.", false);
  1552. }
  1553. internal float HeightValue(Vector3 position)
  1554. {
  1555. int li_x, li_y;
  1556. float height;
  1557. li_x = (int) Math.Round(position.X);
  1558. if (li_x < 0) li_x = 0;
  1559. if (li_x >= BulletXScene.MaxXY) li_x = BulletXScene.MaxXY - 1;
  1560. li_y = (int) Math.Round(position.Y);
  1561. if (li_y < 0) li_y = 0;
  1562. if (li_y >= BulletXScene.MaxXY) li_y = BulletXScene.MaxXY - 1;
  1563. height = ((HeightfieldTerrainShape) _flatPlanet.CollisionShape).getHeightFieldValue(li_x, li_y);
  1564. if (height < 0) height = 0;
  1565. else if (height > BulletXScene.MaxZ) height = BulletXScene.MaxZ;
  1566. return height;
  1567. }
  1568. }
  1569. }