aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs')
-rwxr-xr-xOpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs2166
1 files changed, 2166 insertions, 0 deletions
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs
new file mode 100755
index 0000000..04e77b8
--- /dev/null
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs
@@ -0,0 +1,2166 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyrightD
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Collections.Generic;
29using System.IO;
30using System.Runtime.InteropServices;
31using System.Text;
32
33using OpenSim.Framework;
34
35using OpenMetaverse;
36
37using BulletXNA;
38using BulletXNA.LinearMath;
39using BulletXNA.BulletCollision;
40using BulletXNA.BulletDynamics;
41using BulletXNA.BulletCollision.CollisionDispatch;
42
43namespace OpenSim.Region.Physics.BulletSPlugin
44{
45public sealed class BSAPIXNA : BSAPITemplate
46{
47private sealed class BulletWorldXNA : BulletWorld
48{
49 public DiscreteDynamicsWorld world;
50 public BulletWorldXNA(uint id, BSScene physScene, DiscreteDynamicsWorld xx)
51 : base(id, physScene)
52 {
53 world = xx;
54 }
55}
56
57private sealed class BulletBodyXNA : BulletBody
58{
59 public CollisionObject body;
60 public RigidBody rigidBody { get { return RigidBody.Upcast(body); } }
61
62 public BulletBodyXNA(uint id, CollisionObject xx)
63 : base(id)
64 {
65 body = xx;
66 }
67 public override bool HasPhysicalBody
68 {
69 get { return body != null; }
70 }
71 public override void Clear()
72 {
73 body = null;
74 }
75 public override string AddrString
76 {
77 get { return "XNARigidBody"; }
78 }
79}
80
81private sealed class BulletShapeXNA : BulletShape
82{
83 public CollisionShape shape;
84 public BulletShapeXNA(CollisionShape xx, BSPhysicsShapeType typ)
85 : base()
86 {
87 shape = xx;
88 type = typ;
89 }
90 public override bool HasPhysicalShape
91 {
92 get { return shape != null; }
93 }
94 public override void Clear()
95 {
96 shape = null;
97 }
98 public override BulletShape Clone()
99 {
100 return new BulletShapeXNA(shape, type);
101 }
102 public override bool ReferenceSame(BulletShape other)
103 {
104 BulletShapeXNA otheru = other as BulletShapeXNA;
105 return (otheru != null) && (this.shape == otheru.shape);
106
107 }
108 public override string AddrString
109 {
110 get { return "XNACollisionShape"; }
111 }
112}
113private sealed class BulletConstraintXNA : BulletConstraint
114{
115 public TypedConstraint constrain;
116 public BulletConstraintXNA(TypedConstraint xx) : base()
117 {
118 constrain = xx;
119 }
120
121 public override void Clear()
122 {
123 constrain = null;
124 }
125 public override bool HasPhysicalConstraint { get { return constrain != null; } }
126
127 // Used for log messages for a unique display of the memory/object allocated to this instance
128 public override string AddrString
129 {
130 get { return "XNAConstraint"; }
131 }
132}
133 internal int m_maxCollisions;
134 internal CollisionDesc[] UpdatedCollisions;
135 internal int LastCollisionDesc = 0;
136 internal int m_maxUpdatesPerFrame;
137 internal int LastEntityProperty = 0;
138
139 internal EntityProperties[] UpdatedObjects;
140 internal Dictionary<uint, GhostObject> specialCollisionObjects;
141
142 private static int m_collisionsThisFrame;
143 private BSScene PhysicsScene { get; set; }
144
145 public override string BulletEngineName { get { return "BulletXNA"; } }
146 public override string BulletEngineVersion { get; protected set; }
147
148 public BSAPIXNA(string paramName, BSScene physScene)
149 {
150 PhysicsScene = physScene;
151 }
152
153 /// <summary>
154 ///
155 /// </summary>
156 /// <param name="p"></param>
157 /// <param name="p_2"></param>
158 public override bool RemoveObjectFromWorld(BulletWorld pWorld, BulletBody pBody)
159 {
160 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
161 RigidBody body = ((BulletBodyXNA)pBody).rigidBody;
162 CollisionObject collisionObject = ((BulletBodyXNA)pBody).body;
163 if (body != null)
164 world.RemoveRigidBody(body);
165 else if (collisionObject != null)
166 world.RemoveCollisionObject(collisionObject);
167 else
168 return false;
169 return true;
170 }
171
172 public override bool AddConstraintToWorld(BulletWorld pWorld, BulletConstraint pConstraint, bool pDisableCollisionsBetweenLinkedObjects)
173 {
174 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
175 TypedConstraint constraint = (pConstraint as BulletConstraintXNA).constrain;
176 world.AddConstraint(constraint, pDisableCollisionsBetweenLinkedObjects);
177
178 return true;
179
180 }
181
182 public override bool RemoveConstraintFromWorld(BulletWorld pWorld, BulletConstraint pConstraint)
183 {
184 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
185 TypedConstraint constraint = (pConstraint as BulletConstraintXNA).constrain;
186 world.RemoveConstraint(constraint);
187 return true;
188 }
189
190 public override void SetRestitution(BulletBody pCollisionObject, float pRestitution)
191 {
192 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
193 collisionObject.SetRestitution(pRestitution);
194 }
195
196 public override int GetShapeType(BulletShape pShape)
197 {
198 CollisionShape shape = (pShape as BulletShapeXNA).shape;
199 return (int)shape.GetShapeType();
200 }
201 public override void SetMargin(BulletShape pShape, float pMargin)
202 {
203 CollisionShape shape = (pShape as BulletShapeXNA).shape;
204 shape.SetMargin(pMargin);
205 }
206
207 public override float GetMargin(BulletShape pShape)
208 {
209 CollisionShape shape = (pShape as BulletShapeXNA).shape;
210 return shape.GetMargin();
211 }
212
213 public override void SetLocalScaling(BulletShape pShape, Vector3 pScale)
214 {
215 CollisionShape shape = (pShape as BulletShapeXNA).shape;
216 IndexedVector3 vec = new IndexedVector3(pScale.X, pScale.Y, pScale.Z);
217 shape.SetLocalScaling(ref vec);
218
219 }
220
221 public override void SetContactProcessingThreshold(BulletBody pCollisionObject, float contactprocessingthreshold)
222 {
223 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
224 collisionObject.SetContactProcessingThreshold(contactprocessingthreshold);
225 }
226
227 public override void SetCcdMotionThreshold(BulletBody pCollisionObject, float pccdMotionThreashold)
228 {
229 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
230 collisionObject.SetCcdMotionThreshold(pccdMotionThreashold);
231 }
232
233 public override void SetCcdSweptSphereRadius(BulletBody pCollisionObject, float pCcdSweptSphereRadius)
234 {
235 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
236 collisionObject.SetCcdSweptSphereRadius(pCcdSweptSphereRadius);
237 }
238
239 public override void SetAngularFactorV(BulletBody pBody, Vector3 pAngularFactor)
240 {
241 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
242 body.SetAngularFactor(new IndexedVector3(pAngularFactor.X, pAngularFactor.Y, pAngularFactor.Z));
243 }
244
245 public override CollisionFlags AddToCollisionFlags(BulletBody pCollisionObject, CollisionFlags pcollisionFlags)
246 {
247 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
248 CollisionFlags existingcollisionFlags = (CollisionFlags)(uint)collisionObject.GetCollisionFlags();
249 existingcollisionFlags |= pcollisionFlags;
250 collisionObject.SetCollisionFlags((BulletXNA.BulletCollision.CollisionFlags)(uint)existingcollisionFlags);
251 return (CollisionFlags) (uint) existingcollisionFlags;
252 }
253
254 public override bool AddObjectToWorld(BulletWorld pWorld, BulletBody pBody)
255 {
256 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
257 CollisionObject cbody = (pBody as BulletBodyXNA).body;
258 RigidBody rbody = cbody as RigidBody;
259
260 // Bullet resets several variables when an object is added to the world. In particular,
261 // BulletXNA resets position and rotation. Gravity is also reset depending on the static/dynamic
262 // type. Of course, the collision flags in the broadphase proxy are initialized to default.
263 IndexedMatrix origPos = cbody.GetWorldTransform();
264 if (rbody != null)
265 {
266 IndexedVector3 origGrav = rbody.GetGravity();
267 world.AddRigidBody(rbody);
268 rbody.SetGravity(origGrav);
269 }
270 else
271 {
272 world.AddCollisionObject(cbody);
273 }
274 cbody.SetWorldTransform(origPos);
275
276 pBody.ApplyCollisionMask(pWorld.physicsScene);
277
278 //if (body.GetBroadphaseHandle() != null)
279 // world.UpdateSingleAabb(body);
280 return true;
281 }
282
283 public override void ForceActivationState(BulletBody pCollisionObject, ActivationState pActivationState)
284 {
285 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
286 collisionObject.ForceActivationState((BulletXNA.BulletCollision.ActivationState)(uint)pActivationState);
287 }
288
289 public override void UpdateSingleAabb(BulletWorld pWorld, BulletBody pCollisionObject)
290 {
291 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
292 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
293 world.UpdateSingleAabb(collisionObject);
294 }
295
296 public override void UpdateAabbs(BulletWorld pWorld) {
297 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
298 world.UpdateAabbs();
299 }
300 public override bool GetForceUpdateAllAabbs(BulletWorld pWorld) {
301 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
302 return world.GetForceUpdateAllAabbs();
303
304 }
305 public override void SetForceUpdateAllAabbs(BulletWorld pWorld, bool pForce)
306 {
307 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
308 world.SetForceUpdateAllAabbs(pForce);
309 }
310
311 public override bool SetCollisionGroupMask(BulletBody pCollisionObject, uint pGroup, uint pMask)
312 {
313 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
314 collisionObject.GetBroadphaseHandle().m_collisionFilterGroup = (BulletXNA.BulletCollision.CollisionFilterGroups) pGroup;
315 collisionObject.GetBroadphaseHandle().m_collisionFilterGroup = (BulletXNA.BulletCollision.CollisionFilterGroups) pGroup;
316 if ((uint) collisionObject.GetBroadphaseHandle().m_collisionFilterGroup == 0)
317 return false;
318 return true;
319 }
320
321 public override void ClearAllForces(BulletBody pCollisionObject)
322 {
323 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
324 IndexedVector3 zeroVector = new IndexedVector3(0, 0, 0);
325 collisionObject.SetInterpolationLinearVelocity(ref zeroVector);
326 collisionObject.SetInterpolationAngularVelocity(ref zeroVector);
327 IndexedMatrix bodytransform = collisionObject.GetWorldTransform();
328
329 collisionObject.SetInterpolationWorldTransform(ref bodytransform);
330
331 if (collisionObject is RigidBody)
332 {
333 RigidBody rigidbody = collisionObject as RigidBody;
334 rigidbody.SetLinearVelocity(zeroVector);
335 rigidbody.SetAngularVelocity(zeroVector);
336 rigidbody.ClearForces();
337 }
338 }
339
340 public override void SetInterpolationAngularVelocity(BulletBody pCollisionObject, Vector3 pVector3)
341 {
342 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
343 IndexedVector3 vec = new IndexedVector3(pVector3.X, pVector3.Y, pVector3.Z);
344 collisionObject.SetInterpolationAngularVelocity(ref vec);
345 }
346
347 public override void SetAngularVelocity(BulletBody pBody, Vector3 pVector3)
348 {
349 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
350 IndexedVector3 vec = new IndexedVector3(pVector3.X, pVector3.Y, pVector3.Z);
351 body.SetAngularVelocity(ref vec);
352 }
353 public override Vector3 GetTotalForce(BulletBody pBody)
354 {
355 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
356 IndexedVector3 iv3 = body.GetTotalForce();
357 return new Vector3(iv3.X, iv3.Y, iv3.Z);
358 }
359 public override Vector3 GetTotalTorque(BulletBody pBody)
360 {
361 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
362 IndexedVector3 iv3 = body.GetTotalTorque();
363 return new Vector3(iv3.X, iv3.Y, iv3.Z);
364 }
365 public override Vector3 GetInvInertiaDiagLocal(BulletBody pBody)
366 {
367 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
368 IndexedVector3 iv3 = body.GetInvInertiaDiagLocal();
369 return new Vector3(iv3.X, iv3.Y, iv3.Z);
370 }
371 public override void SetInvInertiaDiagLocal(BulletBody pBody, Vector3 inert)
372 {
373 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
374 IndexedVector3 iv3 = new IndexedVector3(inert.X, inert.Y, inert.Z);
375 body.SetInvInertiaDiagLocal(ref iv3);
376 }
377 public override void ApplyForce(BulletBody pBody, Vector3 force, Vector3 pos)
378 {
379 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
380 IndexedVector3 forceiv3 = new IndexedVector3(force.X, force.Y, force.Z);
381 IndexedVector3 posiv3 = new IndexedVector3(pos.X, pos.Y, pos.Z);
382 body.ApplyForce(ref forceiv3, ref posiv3);
383 }
384 public override void ApplyImpulse(BulletBody pBody, Vector3 imp, Vector3 pos)
385 {
386 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
387 IndexedVector3 impiv3 = new IndexedVector3(imp.X, imp.Y, imp.Z);
388 IndexedVector3 posiv3 = new IndexedVector3(pos.X, pos.Y, pos.Z);
389 body.ApplyImpulse(ref impiv3, ref posiv3);
390 }
391
392 public override void ClearForces(BulletBody pBody)
393 {
394 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
395 body.ClearForces();
396 }
397
398 public override void SetTranslation(BulletBody pCollisionObject, Vector3 _position, Quaternion _orientation)
399 {
400 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
401 IndexedVector3 vposition = new IndexedVector3(_position.X, _position.Y, _position.Z);
402 IndexedQuaternion vquaternion = new IndexedQuaternion(_orientation.X, _orientation.Y, _orientation.Z,
403 _orientation.W);
404 IndexedMatrix mat = IndexedMatrix.CreateFromQuaternion(vquaternion);
405 mat._origin = vposition;
406 collisionObject.SetWorldTransform(mat);
407
408 }
409
410 public override Vector3 GetPosition(BulletBody pCollisionObject)
411 {
412 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
413 IndexedVector3 pos = collisionObject.GetInterpolationWorldTransform()._origin;
414 return new Vector3(pos.X, pos.Y, pos.Z);
415 }
416
417 public override Vector3 CalculateLocalInertia(BulletShape pShape, float pphysMass)
418 {
419 CollisionShape shape = (pShape as BulletShapeXNA).shape;
420 IndexedVector3 inertia = IndexedVector3.Zero;
421 shape.CalculateLocalInertia(pphysMass, out inertia);
422 return new Vector3(inertia.X, inertia.Y, inertia.Z);
423 }
424
425 public override void SetMassProps(BulletBody pBody, float pphysMass, Vector3 plocalInertia)
426 {
427 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
428 if (body != null) // Can't set mass props on collision object.
429 {
430 IndexedVector3 inertia = new IndexedVector3(plocalInertia.X, plocalInertia.Y, plocalInertia.Z);
431 body.SetMassProps(pphysMass, inertia);
432 }
433 }
434
435
436 public override void SetObjectForce(BulletBody pBody, Vector3 _force)
437 {
438 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
439 IndexedVector3 force = new IndexedVector3(_force.X, _force.Y, _force.Z);
440 body.SetTotalForce(ref force);
441 }
442
443 public override void SetFriction(BulletBody pCollisionObject, float _currentFriction)
444 {
445 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
446 collisionObject.SetFriction(_currentFriction);
447 }
448
449 public override void SetLinearVelocity(BulletBody pBody, Vector3 _velocity)
450 {
451 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
452 IndexedVector3 velocity = new IndexedVector3(_velocity.X, _velocity.Y, _velocity.Z);
453 body.SetLinearVelocity(velocity);
454 }
455
456 public override void Activate(BulletBody pCollisionObject, bool pforceactivation)
457 {
458 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
459 collisionObject.Activate(pforceactivation);
460
461 }
462
463 public override Quaternion GetOrientation(BulletBody pCollisionObject)
464 {
465 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
466 IndexedQuaternion mat = collisionObject.GetInterpolationWorldTransform().GetRotation();
467 return new Quaternion(mat.X, mat.Y, mat.Z, mat.W);
468 }
469
470 public override CollisionFlags RemoveFromCollisionFlags(BulletBody pCollisionObject, CollisionFlags pcollisionFlags)
471 {
472 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
473 CollisionFlags existingcollisionFlags = (CollisionFlags)(uint)collisionObject.GetCollisionFlags();
474 existingcollisionFlags &= ~pcollisionFlags;
475 collisionObject.SetCollisionFlags((BulletXNA.BulletCollision.CollisionFlags)(uint)existingcollisionFlags);
476 return (CollisionFlags)(uint)existingcollisionFlags;
477 }
478
479 public override float GetCcdMotionThreshold(BulletBody pCollisionObject)
480 {
481 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
482 return collisionObject.GetCcdSquareMotionThreshold();
483 }
484
485 public override float GetCcdSweptSphereRadius(BulletBody pCollisionObject)
486 {
487 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
488 return collisionObject.GetCcdSweptSphereRadius();
489
490 }
491
492 public override IntPtr GetUserPointer(BulletBody pCollisionObject)
493 {
494 CollisionObject shape = (pCollisionObject as BulletBodyXNA).body;
495 return (IntPtr)shape.GetUserPointer();
496 }
497
498 public override void SetUserPointer(BulletBody pCollisionObject, IntPtr val)
499 {
500 CollisionObject shape = (pCollisionObject as BulletBodyXNA).body;
501 shape.SetUserPointer(val);
502 }
503
504 public override void SetGravity(BulletBody pBody, Vector3 pGravity)
505 {
506 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
507 if (body != null) // Can't set collisionobject.set gravity
508 {
509 IndexedVector3 gravity = new IndexedVector3(pGravity.X, pGravity.Y, pGravity.Z);
510 body.SetGravity(gravity);
511 }
512 }
513
514 public override bool DestroyConstraint(BulletWorld pWorld, BulletConstraint pConstraint)
515 {
516 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
517 TypedConstraint constraint = (pConstraint as BulletConstraintXNA).constrain;
518 world.RemoveConstraint(constraint);
519 return true;
520 }
521
522 public override bool SetLinearLimits(BulletConstraint pConstraint, Vector3 low, Vector3 high)
523 {
524 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
525 IndexedVector3 lowlimit = new IndexedVector3(low.X, low.Y, low.Z);
526 IndexedVector3 highlimit = new IndexedVector3(high.X, high.Y, high.Z);
527 constraint.SetLinearLowerLimit(lowlimit);
528 constraint.SetLinearUpperLimit(highlimit);
529 return true;
530 }
531
532 public override bool SetAngularLimits(BulletConstraint pConstraint, Vector3 low, Vector3 high)
533 {
534 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
535 IndexedVector3 lowlimit = new IndexedVector3(low.X, low.Y, low.Z);
536 IndexedVector3 highlimit = new IndexedVector3(high.X, high.Y, high.Z);
537 constraint.SetAngularLowerLimit(lowlimit);
538 constraint.SetAngularUpperLimit(highlimit);
539 return true;
540 }
541
542 public override void SetConstraintNumSolverIterations(BulletConstraint pConstraint, float cnt)
543 {
544 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
545 constraint.SetOverrideNumSolverIterations((int)cnt);
546 }
547
548 public override bool CalculateTransforms(BulletConstraint pConstraint)
549 {
550 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
551 constraint.CalculateTransforms();
552 return true;
553 }
554
555 public override void SetConstraintEnable(BulletConstraint pConstraint, float p_2)
556 {
557 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
558 constraint.SetEnabled((p_2 == 0) ? false : true);
559 }
560
561
562 //BulletSimAPI.Create6DofConstraint(m_world.ptr, m_body1.ptr, m_body2.ptr,frame1, frame1rot,frame2, frame2rot,useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies));
563 public override BulletConstraint Create6DofConstraint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, Vector3 pframe1, Quaternion pframe1rot, Vector3 pframe2, Quaternion pframe2rot, bool puseLinearReferenceFrameA, bool pdisableCollisionsBetweenLinkedBodies)
564
565 {
566 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
567 RigidBody body1 = (pBody1 as BulletBodyXNA).rigidBody;
568 RigidBody body2 = (pBody2 as BulletBodyXNA).rigidBody;
569 IndexedVector3 frame1v = new IndexedVector3(pframe1.X, pframe1.Y, pframe1.Z);
570 IndexedQuaternion frame1rot = new IndexedQuaternion(pframe1rot.X, pframe1rot.Y, pframe1rot.Z, pframe1rot.W);
571 IndexedMatrix frame1 = IndexedMatrix.CreateFromQuaternion(frame1rot);
572 frame1._origin = frame1v;
573
574 IndexedVector3 frame2v = new IndexedVector3(pframe2.X, pframe2.Y, pframe2.Z);
575 IndexedQuaternion frame2rot = new IndexedQuaternion(pframe2rot.X, pframe2rot.Y, pframe2rot.Z, pframe2rot.W);
576 IndexedMatrix frame2 = IndexedMatrix.CreateFromQuaternion(frame2rot);
577 frame2._origin = frame1v;
578
579 Generic6DofConstraint consttr = new Generic6DofConstraint(body1, body2, ref frame1, ref frame2,
580 puseLinearReferenceFrameA);
581 consttr.CalculateTransforms();
582 world.AddConstraint(consttr,pdisableCollisionsBetweenLinkedBodies);
583
584 return new BulletConstraintXNA(consttr);
585 }
586
587
588 /// <summary>
589 ///
590 /// </summary>
591 /// <param name="pWorld"></param>
592 /// <param name="pBody1"></param>
593 /// <param name="pBody2"></param>
594 /// <param name="pjoinPoint"></param>
595 /// <param name="puseLinearReferenceFrameA"></param>
596 /// <param name="pdisableCollisionsBetweenLinkedBodies"></param>
597 /// <returns></returns>
598 public override BulletConstraint Create6DofConstraintToPoint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, Vector3 pjoinPoint, bool puseLinearReferenceFrameA, bool pdisableCollisionsBetweenLinkedBodies)
599 {
600 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
601 RigidBody body1 = (pBody1 as BulletBodyXNA).rigidBody;
602 RigidBody body2 = (pBody2 as BulletBodyXNA).rigidBody;
603 IndexedMatrix frame1 = new IndexedMatrix(IndexedBasisMatrix.Identity, new IndexedVector3(0, 0, 0));
604 IndexedMatrix frame2 = new IndexedMatrix(IndexedBasisMatrix.Identity, new IndexedVector3(0, 0, 0));
605
606 IndexedVector3 joinPoint = new IndexedVector3(pjoinPoint.X, pjoinPoint.Y, pjoinPoint.Z);
607 IndexedMatrix mat = IndexedMatrix.Identity;
608 mat._origin = new IndexedVector3(pjoinPoint.X, pjoinPoint.Y, pjoinPoint.Z);
609 frame1._origin = body1.GetWorldTransform().Inverse()*joinPoint;
610 frame2._origin = body2.GetWorldTransform().Inverse()*joinPoint;
611
612 Generic6DofConstraint consttr = new Generic6DofConstraint(body1, body2, ref frame1, ref frame2, puseLinearReferenceFrameA);
613 consttr.CalculateTransforms();
614 world.AddConstraint(consttr, pdisableCollisionsBetweenLinkedBodies);
615
616 return new BulletConstraintXNA(consttr);
617 }
618 //SetFrames(m_constraint.ptr, frameA, frameArot, frameB, frameBrot);
619 public override bool SetFrames(BulletConstraint pConstraint, Vector3 pframe1, Quaternion pframe1rot, Vector3 pframe2, Quaternion pframe2rot)
620 {
621 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
622 IndexedVector3 frame1v = new IndexedVector3(pframe1.X, pframe1.Y, pframe1.Z);
623 IndexedQuaternion frame1rot = new IndexedQuaternion(pframe1rot.X, pframe1rot.Y, pframe1rot.Z, pframe1rot.W);
624 IndexedMatrix frame1 = IndexedMatrix.CreateFromQuaternion(frame1rot);
625 frame1._origin = frame1v;
626
627 IndexedVector3 frame2v = new IndexedVector3(pframe2.X, pframe2.Y, pframe2.Z);
628 IndexedQuaternion frame2rot = new IndexedQuaternion(pframe2rot.X, pframe2rot.Y, pframe2rot.Z, pframe2rot.W);
629 IndexedMatrix frame2 = IndexedMatrix.CreateFromQuaternion(frame2rot);
630 frame2._origin = frame1v;
631 constraint.SetFrames(ref frame1, ref frame2);
632 return true;
633 }
634
635 public override Vector3 GetLinearVelocity(BulletBody pBody)
636 {
637 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
638 IndexedVector3 iv3 = body.GetLinearVelocity();
639 return new Vector3(iv3.X, iv3.Y, iv3.Z);
640 }
641 public override Vector3 GetAngularVelocity(BulletBody pBody)
642 {
643 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
644 IndexedVector3 iv3 = body.GetAngularVelocity();
645 return new Vector3(iv3.X, iv3.Y, iv3.Z);
646 }
647 public override Vector3 GetVelocityInLocalPoint(BulletBody pBody, Vector3 pos)
648 {
649 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
650 IndexedVector3 posiv3 = new IndexedVector3(pos.X, pos.Y, pos.Z);
651 IndexedVector3 iv3 = body.GetVelocityInLocalPoint(ref posiv3);
652 return new Vector3(iv3.X, iv3.Y, iv3.Z);
653 }
654 public override void Translate(BulletBody pCollisionObject, Vector3 trans)
655 {
656 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
657 collisionObject.Translate(new IndexedVector3(trans.X,trans.Y,trans.Z));
658 }
659 public override void UpdateDeactivation(BulletBody pBody, float timeStep)
660 {
661 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
662 body.UpdateDeactivation(timeStep);
663 }
664
665 public override bool WantsSleeping(BulletBody pBody)
666 {
667 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
668 return body.WantsSleeping();
669 }
670
671 public override void SetAngularFactor(BulletBody pBody, float factor)
672 {
673 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
674 body.SetAngularFactor(factor);
675 }
676
677 public override Vector3 GetAngularFactor(BulletBody pBody)
678 {
679 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
680 IndexedVector3 iv3 = body.GetAngularFactor();
681 return new Vector3(iv3.X, iv3.Y, iv3.Z);
682 }
683
684 public override bool IsInWorld(BulletWorld pWorld, BulletBody pCollisionObject)
685 {
686 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
687 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
688 return world.IsInWorld(collisionObject);
689 }
690
691 public override void AddConstraintRef(BulletBody pBody, BulletConstraint pConstraint)
692 {
693 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
694 TypedConstraint constrain = (pConstraint as BulletConstraintXNA).constrain;
695 body.AddConstraintRef(constrain);
696 }
697
698 public override void RemoveConstraintRef(BulletBody pBody, BulletConstraint pConstraint)
699 {
700 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
701 TypedConstraint constrain = (pConstraint as BulletConstraintXNA).constrain;
702 body.RemoveConstraintRef(constrain);
703 }
704
705 public override BulletConstraint GetConstraintRef(BulletBody pBody, int index)
706 {
707 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
708 return new BulletConstraintXNA(body.GetConstraintRef(index));
709 }
710
711 public override int GetNumConstraintRefs(BulletBody pBody)
712 {
713 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
714 return body.GetNumConstraintRefs();
715 }
716
717 public override void SetInterpolationLinearVelocity(BulletBody pCollisionObject, Vector3 VehicleVelocity)
718 {
719 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
720 IndexedVector3 velocity = new IndexedVector3(VehicleVelocity.X, VehicleVelocity.Y, VehicleVelocity.Z);
721 collisionObject.SetInterpolationLinearVelocity(ref velocity);
722 }
723
724 public override bool UseFrameOffset(BulletConstraint pConstraint, float onOff)
725 {
726 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
727 constraint.SetUseFrameOffset((onOff == 0) ? false : true);
728 return true;
729 }
730 //SetBreakingImpulseThreshold(m_constraint.ptr, threshold);
731 public override bool SetBreakingImpulseThreshold(BulletConstraint pConstraint, float threshold)
732 {
733 Generic6DofConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
734 constraint.SetBreakingImpulseThreshold(threshold);
735 return true;
736 }
737 //BulletSimAPI.SetAngularDamping(Prim.PhysBody.ptr, angularDamping);
738 public override void SetAngularDamping(BulletBody pBody, float angularDamping)
739 {
740 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
741 float lineardamping = body.GetLinearDamping();
742 body.SetDamping(lineardamping, angularDamping);
743
744 }
745
746 public override void UpdateInertiaTensor(BulletBody pBody)
747 {
748 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
749 if (body != null) // can't update inertia tensor on CollisionObject
750 body.UpdateInertiaTensor();
751 }
752
753 public override void RecalculateCompoundShapeLocalAabb(BulletShape pCompoundShape)
754 {
755 CompoundShape shape = (pCompoundShape as BulletShapeXNA).shape as CompoundShape;
756 shape.RecalculateLocalAabb();
757 }
758
759 //BulletSimAPI.GetCollisionFlags(PhysBody.ptr)
760 public override CollisionFlags GetCollisionFlags(BulletBody pCollisionObject)
761 {
762 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
763 uint flags = (uint)collisionObject.GetCollisionFlags();
764 return (CollisionFlags) flags;
765 }
766
767 public override void SetDamping(BulletBody pBody, float pLinear, float pAngular)
768 {
769 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
770 body.SetDamping(pLinear, pAngular);
771 }
772 //PhysBody.ptr, PhysicsScene.Params.deactivationTime);
773 public override void SetDeactivationTime(BulletBody pCollisionObject, float pDeactivationTime)
774 {
775 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
776 collisionObject.SetDeactivationTime(pDeactivationTime);
777 }
778 //SetSleepingThresholds(PhysBody.ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold);
779 public override void SetSleepingThresholds(BulletBody pBody, float plinearSleepingThreshold, float pangularSleepingThreshold)
780 {
781 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
782 body.SetSleepingThresholds(plinearSleepingThreshold, pangularSleepingThreshold);
783 }
784
785 public override CollisionObjectTypes GetBodyType(BulletBody pCollisionObject)
786 {
787 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
788 return (CollisionObjectTypes)(int) collisionObject.GetInternalType();
789 }
790
791 public override void ApplyGravity(BulletBody pBody)
792 {
793
794 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
795 body.ApplyGravity();
796 }
797
798 public override Vector3 GetGravity(BulletBody pBody)
799 {
800 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
801 IndexedVector3 gravity = body.GetGravity();
802 return new Vector3(gravity.X, gravity.Y, gravity.Z);
803 }
804
805 public override void SetLinearDamping(BulletBody pBody, float lin_damping)
806 {
807 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
808 float angularDamping = body.GetAngularDamping();
809 body.SetDamping(lin_damping, angularDamping);
810 }
811
812 public override float GetLinearDamping(BulletBody pBody)
813 {
814 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
815 return body.GetLinearDamping();
816 }
817
818 public override float GetAngularDamping(BulletBody pBody)
819 {
820 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
821 return body.GetAngularDamping();
822 }
823
824 public override float GetLinearSleepingThreshold(BulletBody pBody)
825 {
826 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
827 return body.GetLinearSleepingThreshold();
828 }
829
830 public override void ApplyDamping(BulletBody pBody, float timeStep)
831 {
832 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
833 body.ApplyDamping(timeStep);
834 }
835
836 public override Vector3 GetLinearFactor(BulletBody pBody)
837 {
838 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
839 IndexedVector3 linearFactor = body.GetLinearFactor();
840 return new Vector3(linearFactor.X, linearFactor.Y, linearFactor.Z);
841 }
842
843 public override void SetLinearFactor(BulletBody pBody, Vector3 factor)
844 {
845 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
846 body.SetLinearFactor(new IndexedVector3(factor.X, factor.Y, factor.Z));
847 }
848
849 public override void SetCenterOfMassByPosRot(BulletBody pBody, Vector3 pos, Quaternion rot)
850 {
851 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
852 IndexedQuaternion quat = new IndexedQuaternion(rot.X, rot.Y, rot.Z,rot.W);
853 IndexedMatrix mat = IndexedMatrix.CreateFromQuaternion(quat);
854 mat._origin = new IndexedVector3(pos.X, pos.Y, pos.Z);
855 body.SetCenterOfMassTransform( ref mat);
856 /* TODO: double check this */
857 }
858
859 //BulletSimAPI.ApplyCentralForce(PhysBody.ptr, fSum);
860 public override void ApplyCentralForce(BulletBody pBody, Vector3 pfSum)
861 {
862 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
863 IndexedVector3 fSum = new IndexedVector3(pfSum.X, pfSum.Y, pfSum.Z);
864 body.ApplyCentralForce(ref fSum);
865 }
866 public override void ApplyCentralImpulse(BulletBody pBody, Vector3 pfSum)
867 {
868 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
869 IndexedVector3 fSum = new IndexedVector3(pfSum.X, pfSum.Y, pfSum.Z);
870 body.ApplyCentralImpulse(ref fSum);
871 }
872 public override void ApplyTorque(BulletBody pBody, Vector3 pfSum)
873 {
874 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
875 IndexedVector3 fSum = new IndexedVector3(pfSum.X, pfSum.Y, pfSum.Z);
876 body.ApplyTorque(ref fSum);
877 }
878 public override void ApplyTorqueImpulse(BulletBody pBody, Vector3 pfSum)
879 {
880 RigidBody body = (pBody as BulletBodyXNA).rigidBody;
881 IndexedVector3 fSum = new IndexedVector3(pfSum.X, pfSum.Y, pfSum.Z);
882 body.ApplyTorqueImpulse(ref fSum);
883 }
884
885 public override void DestroyObject(BulletWorld pWorld, BulletBody pBody)
886 {
887 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
888 CollisionObject co = (pBody as BulletBodyXNA).rigidBody;
889 RigidBody bo = co as RigidBody;
890 if (bo == null)
891 {
892
893 if (world.IsInWorld(co))
894 {
895 world.RemoveCollisionObject(co);
896 }
897 }
898 else
899 {
900
901 if (world.IsInWorld(bo))
902 {
903 world.RemoveRigidBody(bo);
904 }
905 }
906 if (co != null)
907 {
908 if (co.GetUserPointer() != null)
909 {
910 uint localId = (uint) co.GetUserPointer();
911 if (specialCollisionObjects.ContainsKey(localId))
912 {
913 specialCollisionObjects.Remove(localId);
914 }
915 }
916 }
917
918 }
919
920 public override void Shutdown(BulletWorld pWorld)
921 {
922 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
923 world.Cleanup();
924 }
925
926 public override BulletShape DuplicateCollisionShape(BulletWorld pWorld, BulletShape pShape, uint id)
927 {
928 CollisionShape shape1 = (pShape as BulletShapeXNA).shape;
929
930 // TODO: Turn this from a reference copy to a Value Copy.
931 BulletShapeXNA shape2 = new BulletShapeXNA(shape1, BSShapeTypeFromBroadPhaseNativeType(shape1.GetShapeType()));
932
933 return shape2;
934 }
935
936 public override bool DeleteCollisionShape(BulletWorld pWorld, BulletShape pShape)
937 {
938 //TODO:
939 return false;
940 }
941 //(sim.ptr, shape.ptr, prim.LocalID, prim.RawPosition, prim.RawOrientation);
942
943 public override BulletBody CreateBodyFromShape(BulletWorld pWorld, BulletShape pShape, uint pLocalID, Vector3 pRawPosition, Quaternion pRawOrientation)
944 {
945 CollisionWorld world = (pWorld as BulletWorldXNA).world;
946 IndexedMatrix mat =
947 IndexedMatrix.CreateFromQuaternion(new IndexedQuaternion(pRawOrientation.X, pRawOrientation.Y,
948 pRawOrientation.Z, pRawOrientation.W));
949 mat._origin = new IndexedVector3(pRawPosition.X, pRawPosition.Y, pRawPosition.Z);
950 CollisionShape shape = (pShape as BulletShapeXNA).shape;
951 //UpdateSingleAabb(world, shape);
952 // TODO: Feed Update array into null
953 SimMotionState motionState = new SimMotionState(this, pLocalID, mat, null);
954 RigidBody body = new RigidBody(0,motionState,shape,IndexedVector3.Zero);
955 RigidBodyConstructionInfo constructionInfo = new RigidBodyConstructionInfo(0, motionState, shape, IndexedVector3.Zero)
956 {
957 m_mass = 0
958 };
959 /*
960 m_mass = mass;
961 m_motionState =motionState;
962 m_collisionShape = collisionShape;
963 m_localInertia = localInertia;
964 m_linearDamping = 0f;
965 m_angularDamping = 0f;
966 m_friction = 0.5f;
967 m_restitution = 0f;
968 m_linearSleepingThreshold = 0.8f;
969 m_angularSleepingThreshold = 1f;
970 m_additionalDamping = false;
971 m_additionalDampingFactor = 0.005f;
972 m_additionalLinearDampingThresholdSqr = 0.01f;
973 m_additionalAngularDampingThresholdSqr = 0.01f;
974 m_additionalAngularDampingFactor = 0.01f;
975 m_startWorldTransform = IndexedMatrix.Identity;
976 */
977 body.SetUserPointer(pLocalID);
978
979 return new BulletBodyXNA(pLocalID, body);
980 }
981
982
983 public override BulletBody CreateBodyWithDefaultMotionState( BulletShape pShape, uint pLocalID, Vector3 pRawPosition, Quaternion pRawOrientation)
984 {
985
986 IndexedMatrix mat =
987 IndexedMatrix.CreateFromQuaternion(new IndexedQuaternion(pRawOrientation.X, pRawOrientation.Y,
988 pRawOrientation.Z, pRawOrientation.W));
989 mat._origin = new IndexedVector3(pRawPosition.X, pRawPosition.Y, pRawPosition.Z);
990
991 CollisionShape shape = (pShape as BulletShapeXNA).shape;
992
993 // TODO: Feed Update array into null
994 RigidBody body = new RigidBody(0, new DefaultMotionState( mat, IndexedMatrix.Identity), shape, IndexedVector3.Zero);
995 body.SetWorldTransform(mat);
996 body.SetUserPointer(pLocalID);
997 return new BulletBodyXNA(pLocalID, body);
998 }
999 //(m_mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT);
1000 public override CollisionFlags SetCollisionFlags(BulletBody pCollisionObject, CollisionFlags collisionFlags)
1001 {
1002 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1003 collisionObject.SetCollisionFlags((BulletXNA.BulletCollision.CollisionFlags) (uint) collisionFlags);
1004 return (CollisionFlags)collisionObject.GetCollisionFlags();
1005 }
1006
1007 public override Vector3 GetAnisotripicFriction(BulletConstraint pconstrain)
1008 {
1009
1010 /* TODO */
1011 return Vector3.Zero;
1012 }
1013 public override Vector3 SetAnisotripicFriction(BulletConstraint pconstrain, Vector3 frict) { /* TODO */ return Vector3.Zero; }
1014 public override bool HasAnisotripicFriction(BulletConstraint pconstrain) { /* TODO */ return false; }
1015 public override float GetContactProcessingThreshold(BulletBody pBody) { /* TODO */ return 0f; }
1016 public override bool IsStaticObject(BulletBody pCollisionObject)
1017 {
1018 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1019 return collisionObject.IsStaticObject();
1020
1021 }
1022 public override bool IsKinematicObject(BulletBody pCollisionObject)
1023 {
1024 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1025 return collisionObject.IsKinematicObject();
1026 }
1027 public override bool IsStaticOrKinematicObject(BulletBody pCollisionObject)
1028 {
1029 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1030 return collisionObject.IsStaticOrKinematicObject();
1031 }
1032 public override bool HasContactResponse(BulletBody pCollisionObject)
1033 {
1034 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1035 return collisionObject.HasContactResponse();
1036 }
1037 public override int GetActivationState(BulletBody pBody) { /* TODO */ return 0; }
1038 public override void SetActivationState(BulletBody pBody, int state) { /* TODO */ }
1039 public override float GetDeactivationTime(BulletBody pBody) { /* TODO */ return 0f; }
1040 public override bool IsActive(BulletBody pBody) { /* TODO */ return false; }
1041 public override float GetRestitution(BulletBody pBody) { /* TODO */ return 0f; }
1042 public override float GetFriction(BulletBody pBody) { /* TODO */ return 0f; }
1043 public override void SetInterpolationVelocity(BulletBody pBody, Vector3 linearVel, Vector3 angularVel) { /* TODO */ }
1044 public override float GetHitFraction(BulletBody pBody) { /* TODO */ return 0f; }
1045
1046 //(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainHitFraction);
1047 public override void SetHitFraction(BulletBody pCollisionObject, float pHitFraction)
1048 {
1049 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1050 collisionObject.SetHitFraction(pHitFraction);
1051 }
1052 //BuildCapsuleShape(physicsScene.World.ptr, 1f, 1f, prim.Scale);
1053 public override BulletShape BuildCapsuleShape(BulletWorld pWorld, float pRadius, float pHeight, Vector3 pScale)
1054 {
1055 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1056 IndexedVector3 scale = new IndexedVector3(pScale.X, pScale.Y, pScale.Z);
1057 CapsuleShapeZ capsuleShapeZ = new CapsuleShapeZ(pRadius, pHeight);
1058 capsuleShapeZ.SetMargin(world.WorldSettings.Params.collisionMargin);
1059 capsuleShapeZ.SetLocalScaling(ref scale);
1060
1061 return new BulletShapeXNA(capsuleShapeZ, BSPhysicsShapeType.SHAPE_CAPSULE); ;
1062 }
1063
1064 public override BulletWorld Initialize(Vector3 maxPosition, ConfigurationParameters parms,
1065 int maxCollisions, ref CollisionDesc[] collisionArray,
1066 int maxUpdates, ref EntityProperties[] updateArray
1067 )
1068 {
1069
1070 UpdatedObjects = updateArray;
1071 UpdatedCollisions = collisionArray;
1072 /* TODO */
1073 ConfigurationParameters[] configparms = new ConfigurationParameters[1];
1074 configparms[0] = parms;
1075 Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight);
1076 m_maxCollisions = maxCollisions;
1077 m_maxUpdatesPerFrame = maxUpdates;
1078 specialCollisionObjects = new Dictionary<uint, GhostObject>();
1079
1080 return new BulletWorldXNA(1, PhysicsScene, BSAPIXNA.Initialize2(worldExtent, configparms, maxCollisions, ref collisionArray, maxUpdates, ref updateArray, null));
1081 }
1082
1083 private static DiscreteDynamicsWorld Initialize2(Vector3 worldExtent,
1084 ConfigurationParameters[] o,
1085 int mMaxCollisionsPerFrame, ref CollisionDesc[] collisionArray,
1086 int mMaxUpdatesPerFrame, ref EntityProperties[] updateArray,
1087 object mDebugLogCallbackHandle)
1088 {
1089 CollisionWorld.WorldData.ParamData p = new CollisionWorld.WorldData.ParamData();
1090
1091 p.angularDamping = o[0].XangularDamping;
1092 p.defaultFriction = o[0].defaultFriction;
1093 p.defaultFriction = o[0].defaultFriction;
1094 p.defaultDensity = o[0].defaultDensity;
1095 p.defaultRestitution = o[0].defaultRestitution;
1096 p.collisionMargin = o[0].collisionMargin;
1097 p.gravity = o[0].gravity;
1098
1099 p.linearDamping = o[0].XlinearDamping;
1100 p.angularDamping = o[0].XangularDamping;
1101 p.deactivationTime = o[0].XdeactivationTime;
1102 p.linearSleepingThreshold = o[0].XlinearSleepingThreshold;
1103 p.angularSleepingThreshold = o[0].XangularSleepingThreshold;
1104 p.ccdMotionThreshold = o[0].XccdMotionThreshold;
1105 p.ccdSweptSphereRadius = o[0].XccdSweptSphereRadius;
1106 p.contactProcessingThreshold = o[0].XcontactProcessingThreshold;
1107
1108 p.terrainImplementation = o[0].XterrainImplementation;
1109 p.terrainFriction = o[0].XterrainFriction;
1110
1111 p.terrainHitFraction = o[0].XterrainHitFraction;
1112 p.terrainRestitution = o[0].XterrainRestitution;
1113 p.terrainCollisionMargin = o[0].XterrainCollisionMargin;
1114
1115 p.avatarFriction = o[0].XavatarFriction;
1116 p.avatarStandingFriction = o[0].XavatarStandingFriction;
1117 p.avatarDensity = o[0].XavatarDensity;
1118 p.avatarRestitution = o[0].XavatarRestitution;
1119 p.avatarCapsuleWidth = o[0].XavatarCapsuleWidth;
1120 p.avatarCapsuleDepth = o[0].XavatarCapsuleDepth;
1121 p.avatarCapsuleHeight = o[0].XavatarCapsuleHeight;
1122 p.avatarContactProcessingThreshold = o[0].XavatarContactProcessingThreshold;
1123
1124 p.vehicleAngularDamping = o[0].XvehicleAngularDamping;
1125
1126 p.maxPersistantManifoldPoolSize = o[0].maxPersistantManifoldPoolSize;
1127 p.maxCollisionAlgorithmPoolSize = o[0].maxCollisionAlgorithmPoolSize;
1128 p.shouldDisableContactPoolDynamicAllocation = o[0].shouldDisableContactPoolDynamicAllocation;
1129 p.shouldForceUpdateAllAabbs = o[0].shouldForceUpdateAllAabbs;
1130 p.shouldRandomizeSolverOrder = o[0].shouldRandomizeSolverOrder;
1131 p.shouldSplitSimulationIslands = o[0].shouldSplitSimulationIslands;
1132 p.shouldEnableFrictionCaching = o[0].shouldEnableFrictionCaching;
1133 p.numberOfSolverIterations = o[0].numberOfSolverIterations;
1134
1135 p.linksetImplementation = o[0].XlinksetImplementation;
1136 p.linkConstraintUseFrameOffset = o[0].XlinkConstraintUseFrameOffset;
1137 p.linkConstraintEnableTransMotor = o[0].XlinkConstraintEnableTransMotor;
1138 p.linkConstraintTransMotorMaxVel = o[0].XlinkConstraintTransMotorMaxVel;
1139 p.linkConstraintTransMotorMaxForce = o[0].XlinkConstraintTransMotorMaxForce;
1140 p.linkConstraintERP = o[0].XlinkConstraintERP;
1141 p.linkConstraintCFM = o[0].XlinkConstraintCFM;
1142 p.linkConstraintSolverIterations = o[0].XlinkConstraintSolverIterations;
1143 p.physicsLoggingFrames = o[0].XphysicsLoggingFrames;
1144 DefaultCollisionConstructionInfo ccci = new DefaultCollisionConstructionInfo();
1145
1146 DefaultCollisionConfiguration cci = new DefaultCollisionConfiguration();
1147 CollisionDispatcher m_dispatcher = new CollisionDispatcher(cci);
1148
1149
1150 if (p.maxPersistantManifoldPoolSize > 0)
1151 cci.m_persistentManifoldPoolSize = (int)p.maxPersistantManifoldPoolSize;
1152 if (p.shouldDisableContactPoolDynamicAllocation !=0)
1153 m_dispatcher.SetDispatcherFlags(DispatcherFlags.CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION);
1154 //if (p.maxCollisionAlgorithmPoolSize >0 )
1155
1156 DbvtBroadphase m_broadphase = new DbvtBroadphase();
1157 //IndexedVector3 aabbMin = new IndexedVector3(0, 0, 0);
1158 //IndexedVector3 aabbMax = new IndexedVector3(256, 256, 256);
1159
1160 //AxisSweep3Internal m_broadphase2 = new AxisSweep3Internal(ref aabbMin, ref aabbMax, Convert.ToInt32(0xfffe), 0xffff, ushort.MaxValue/2, null, true);
1161 m_broadphase.GetOverlappingPairCache().SetInternalGhostPairCallback(new GhostPairCallback());
1162
1163 SequentialImpulseConstraintSolver m_solver = new SequentialImpulseConstraintSolver();
1164
1165 DiscreteDynamicsWorld world = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, cci);
1166
1167 world.LastCollisionDesc = 0;
1168 world.LastEntityProperty = 0;
1169
1170 world.WorldSettings.Params = p;
1171 world.SetForceUpdateAllAabbs(p.shouldForceUpdateAllAabbs != 0);
1172 world.GetSolverInfo().m_solverMode = SolverMode.SOLVER_USE_WARMSTARTING | SolverMode.SOLVER_SIMD;
1173 if (p.shouldRandomizeSolverOrder != 0)
1174 world.GetSolverInfo().m_solverMode |= SolverMode.SOLVER_RANDMIZE_ORDER;
1175
1176 world.GetSimulationIslandManager().SetSplitIslands(p.shouldSplitSimulationIslands != 0);
1177 //world.GetDispatchInfo().m_enableSatConvex Not implemented in C# port
1178
1179 if (p.shouldEnableFrictionCaching != 0)
1180 world.GetSolverInfo().m_solverMode |= SolverMode.SOLVER_ENABLE_FRICTION_DIRECTION_CACHING;
1181
1182 if (p.numberOfSolverIterations > 0)
1183 world.GetSolverInfo().m_numIterations = (int) p.numberOfSolverIterations;
1184
1185
1186 world.GetSolverInfo().m_damping = world.WorldSettings.Params.linearDamping;
1187 world.GetSolverInfo().m_restitution = world.WorldSettings.Params.defaultRestitution;
1188 world.GetSolverInfo().m_globalCfm = 0.0f;
1189 world.GetSolverInfo().m_tau = 0.6f;
1190 world.GetSolverInfo().m_friction = 0.3f;
1191 world.GetSolverInfo().m_maxErrorReduction = 20f;
1192 world.GetSolverInfo().m_numIterations = 10;
1193 world.GetSolverInfo().m_erp = 0.2f;
1194 world.GetSolverInfo().m_erp2 = 0.1f;
1195 world.GetSolverInfo().m_sor = 1.0f;
1196 world.GetSolverInfo().m_splitImpulse = false;
1197 world.GetSolverInfo().m_splitImpulsePenetrationThreshold = -0.02f;
1198 world.GetSolverInfo().m_linearSlop = 0.0f;
1199 world.GetSolverInfo().m_warmstartingFactor = 0.85f;
1200 world.GetSolverInfo().m_restingContactRestitutionThreshold = 2;
1201 world.SetForceUpdateAllAabbs(true);
1202
1203 //BSParam.TerrainImplementation = 0;
1204 world.SetGravity(new IndexedVector3(0,0,p.gravity));
1205
1206 return world;
1207 }
1208 //m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_CFM, cfm, ConstraintParamAxis.AXIS_ALL
1209 public override bool SetConstraintParam(BulletConstraint pConstraint, ConstraintParams paramIndex, float paramvalue, ConstraintParamAxis axis)
1210 {
1211 Generic6DofConstraint constrain = (pConstraint as BulletConstraintXNA).constrain as Generic6DofConstraint;
1212 if (axis == ConstraintParamAxis.AXIS_LINEAR_ALL || axis == ConstraintParamAxis.AXIS_ALL)
1213 {
1214 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams) (int) paramIndex, paramvalue, 0);
1215 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams) (int) paramIndex, paramvalue, 1);
1216 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams) (int) paramIndex, paramvalue, 2);
1217 }
1218 if (axis == ConstraintParamAxis.AXIS_ANGULAR_ALL || axis == ConstraintParamAxis.AXIS_ALL)
1219 {
1220 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams)(int)paramIndex, paramvalue, 3);
1221 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams)(int)paramIndex, paramvalue, 4);
1222 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams)(int)paramIndex, paramvalue, 5);
1223 }
1224 if (axis == ConstraintParamAxis.AXIS_LINEAR_ALL)
1225 {
1226 constrain.SetParam((BulletXNA.BulletDynamics.ConstraintParams)(int)paramIndex, paramvalue, (int)axis);
1227 }
1228 return true;
1229 }
1230
1231 public override bool PushUpdate(BulletBody pCollisionObject)
1232 {
1233 bool ret = false;
1234 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1235 RigidBody rb = collisionObject as RigidBody;
1236 if (rb != null)
1237 {
1238 SimMotionState sms = rb.GetMotionState() as SimMotionState;
1239 if (sms != null)
1240 {
1241 IndexedMatrix wt = IndexedMatrix.Identity;
1242 sms.GetWorldTransform(out wt);
1243 sms.SetWorldTransform(ref wt, true);
1244 ret = true;
1245 }
1246 }
1247 return ret;
1248
1249 }
1250
1251 public override float GetAngularMotionDisc(BulletShape pShape)
1252 {
1253 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1254 return shape.GetAngularMotionDisc();
1255 }
1256 public override float GetContactBreakingThreshold(BulletShape pShape, float defaultFactor)
1257 {
1258 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1259 return shape.GetContactBreakingThreshold(defaultFactor);
1260 }
1261 public override bool IsCompound(BulletShape pShape)
1262 {
1263 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1264 return shape.IsCompound();
1265 }
1266 public override bool IsSoftBody(BulletShape pShape)
1267 {
1268 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1269 return shape.IsSoftBody();
1270 }
1271 public override bool IsPolyhedral(BulletShape pShape)
1272 {
1273 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1274 return shape.IsPolyhedral();
1275 }
1276 public override bool IsConvex2d(BulletShape pShape)
1277 {
1278 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1279 return shape.IsConvex2d();
1280 }
1281 public override bool IsConvex(BulletShape pShape)
1282 {
1283 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1284 return shape.IsConvex();
1285 }
1286 public override bool IsNonMoving(BulletShape pShape)
1287 {
1288 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1289 return shape.IsNonMoving();
1290 }
1291 public override bool IsConcave(BulletShape pShape)
1292 {
1293 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1294 return shape.IsConcave();
1295 }
1296 public override bool IsInfinite(BulletShape pShape)
1297 {
1298 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1299 return shape.IsInfinite();
1300 }
1301 public override bool IsNativeShape(BulletShape pShape)
1302 {
1303 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1304 bool ret;
1305 switch (shape.GetShapeType())
1306 {
1307 case BroadphaseNativeTypes.BOX_SHAPE_PROXYTYPE:
1308 case BroadphaseNativeTypes.CONE_SHAPE_PROXYTYPE:
1309 case BroadphaseNativeTypes.SPHERE_SHAPE_PROXYTYPE:
1310 case BroadphaseNativeTypes.CYLINDER_SHAPE_PROXYTYPE:
1311 ret = true;
1312 break;
1313 default:
1314 ret = false;
1315 break;
1316 }
1317 return ret;
1318 }
1319
1320 public override void SetShapeCollisionMargin(BulletShape pShape, float pMargin)
1321 {
1322 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1323 shape.SetMargin(pMargin);
1324 }
1325
1326 //sim.ptr, shape.ptr,prim.LocalID, prim.RawPosition, prim.RawOrientation
1327 public override BulletBody CreateGhostFromShape(BulletWorld pWorld, BulletShape pShape, uint pLocalID, Vector3 pRawPosition, Quaternion pRawOrientation)
1328 {
1329 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1330 IndexedMatrix bodyTransform = new IndexedMatrix();
1331 bodyTransform._origin = new IndexedVector3(pRawPosition.X, pRawPosition.Y, pRawPosition.Z);
1332 bodyTransform.SetRotation(new IndexedQuaternion(pRawOrientation.X,pRawOrientation.Y,pRawOrientation.Z,pRawOrientation.W));
1333 GhostObject gObj = new PairCachingGhostObject();
1334 gObj.SetWorldTransform(bodyTransform);
1335 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1336 gObj.SetCollisionShape(shape);
1337 gObj.SetUserPointer(pLocalID);
1338
1339 if (specialCollisionObjects.ContainsKey(pLocalID))
1340 specialCollisionObjects[pLocalID] = gObj;
1341 else
1342 specialCollisionObjects.Add(pLocalID, gObj);
1343
1344 // TODO: Add to Special CollisionObjects!
1345 return new BulletBodyXNA(pLocalID, gObj);
1346 }
1347
1348 public override void SetCollisionShape(BulletWorld pWorld, BulletBody pCollisionObject, BulletShape pShape)
1349 {
1350 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1351 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body;
1352 if (pShape == null)
1353 {
1354 collisionObject.SetCollisionShape(new EmptyShape());
1355 }
1356 else
1357 {
1358 CollisionShape shape = (pShape as BulletShapeXNA).shape;
1359 collisionObject.SetCollisionShape(shape);
1360 }
1361 }
1362 public override BulletShape GetCollisionShape(BulletBody pCollisionObject)
1363 {
1364 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1365 CollisionShape shape = collisionObject.GetCollisionShape();
1366 return new BulletShapeXNA(shape, BSShapeTypeFromBroadPhaseNativeType(shape.GetShapeType()));
1367 }
1368
1369 //(PhysicsScene.World.ptr, nativeShapeData)
1370 public override BulletShape BuildNativeShape(BulletWorld pWorld, ShapeData pShapeData)
1371 {
1372 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1373 CollisionShape shape = null;
1374 switch (pShapeData.Type)
1375 {
1376 case BSPhysicsShapeType.SHAPE_BOX:
1377 shape = new BoxShape(new IndexedVector3(0.5f,0.5f,0.5f));
1378 break;
1379 case BSPhysicsShapeType.SHAPE_CONE:
1380 shape = new ConeShapeZ(0.5f, 1.0f);
1381 break;
1382 case BSPhysicsShapeType.SHAPE_CYLINDER:
1383 shape = new CylinderShapeZ(new IndexedVector3(0.5f, 0.5f, 0.5f));
1384 break;
1385 case BSPhysicsShapeType.SHAPE_SPHERE:
1386 shape = new SphereShape(0.5f);
1387 break;
1388
1389 }
1390 if (shape != null)
1391 {
1392 IndexedVector3 scaling = new IndexedVector3(pShapeData.Scale.X, pShapeData.Scale.Y, pShapeData.Scale.Z);
1393 shape.SetMargin(world.WorldSettings.Params.collisionMargin);
1394 shape.SetLocalScaling(ref scaling);
1395
1396 }
1397 return new BulletShapeXNA(shape, pShapeData.Type);
1398 }
1399 //PhysicsScene.World.ptr, false
1400 public override BulletShape CreateCompoundShape(BulletWorld pWorld, bool enableDynamicAabbTree)
1401 {
1402 return new BulletShapeXNA(new CompoundShape(enableDynamicAabbTree), BSPhysicsShapeType.SHAPE_COMPOUND);
1403 }
1404
1405 public override int GetNumberOfCompoundChildren(BulletShape pCompoundShape)
1406 {
1407 CompoundShape compoundshape = (pCompoundShape as BulletShapeXNA).shape as CompoundShape;
1408 return compoundshape.GetNumChildShapes();
1409 }
1410 //LinksetRoot.PhysShape.ptr, newShape.ptr, displacementPos, displacementRot
1411 public override void AddChildShapeToCompoundShape(BulletShape pCShape, BulletShape paddShape, Vector3 displacementPos, Quaternion displacementRot)
1412 {
1413 IndexedMatrix relativeTransform = new IndexedMatrix();
1414 CompoundShape compoundshape = (pCShape as BulletShapeXNA).shape as CompoundShape;
1415 CollisionShape addshape = (paddShape as BulletShapeXNA).shape;
1416
1417 relativeTransform._origin = new IndexedVector3(displacementPos.X, displacementPos.Y, displacementPos.Z);
1418 relativeTransform.SetRotation(new IndexedQuaternion(displacementRot.X,displacementRot.Y,displacementRot.Z,displacementRot.W));
1419 compoundshape.AddChildShape(ref relativeTransform, addshape);
1420
1421 }
1422
1423 public override BulletShape RemoveChildShapeFromCompoundShapeIndex(BulletShape pCShape, int pii)
1424 {
1425 CompoundShape compoundshape = (pCShape as BulletShapeXNA).shape as CompoundShape;
1426 CollisionShape ret = null;
1427 ret = compoundshape.GetChildShape(pii);
1428 compoundshape.RemoveChildShapeByIndex(pii);
1429 return new BulletShapeXNA(ret, BSShapeTypeFromBroadPhaseNativeType(ret.GetShapeType()));
1430 }
1431
1432 public override BulletShape GetChildShapeFromCompoundShapeIndex(BulletShape cShape, int indx) {
1433
1434 if (cShape == null)
1435 return null;
1436 CompoundShape compoundShape = (cShape as BulletShapeXNA).shape as CompoundShape;
1437 CollisionShape shape = compoundShape.GetChildShape(indx);
1438 BulletShape retShape = new BulletShapeXNA(shape, BSShapeTypeFromBroadPhaseNativeType(shape.GetShapeType()));
1439
1440
1441 return retShape;
1442 }
1443
1444 public BSPhysicsShapeType BSShapeTypeFromBroadPhaseNativeType(BroadphaseNativeTypes pin)
1445 {
1446 switch (pin)
1447 {
1448 case BroadphaseNativeTypes.BOX_SHAPE_PROXYTYPE:
1449 return BSPhysicsShapeType.SHAPE_BOX;
1450 break;
1451 case BroadphaseNativeTypes.TRIANGLE_SHAPE_PROXYTYPE:
1452 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1453 break;
1454
1455 case BroadphaseNativeTypes.TETRAHEDRAL_SHAPE_PROXYTYPE:
1456 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1457 break;
1458 case BroadphaseNativeTypes.CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE:
1459 return BSPhysicsShapeType.SHAPE_MESH;
1460 break;
1461 case BroadphaseNativeTypes.CONVEX_HULL_SHAPE_PROXYTYPE:
1462 return BSPhysicsShapeType.SHAPE_HULL;
1463 break;
1464 case BroadphaseNativeTypes.CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE:
1465 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1466 break;
1467 case BroadphaseNativeTypes.CUSTOM_POLYHEDRAL_SHAPE_TYPE:
1468 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1469 break;
1470 //implicit convex shapes
1471 case BroadphaseNativeTypes.IMPLICIT_CONVEX_SHAPES_START_HERE:
1472 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1473 break;
1474 case BroadphaseNativeTypes.SPHERE_SHAPE_PROXYTYPE:
1475 return BSPhysicsShapeType.SHAPE_SPHERE;
1476 break;
1477 case BroadphaseNativeTypes.MULTI_SPHERE_SHAPE_PROXYTYPE:
1478 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1479 break;
1480 case BroadphaseNativeTypes.CAPSULE_SHAPE_PROXYTYPE:
1481 return BSPhysicsShapeType.SHAPE_CAPSULE;
1482 break;
1483 case BroadphaseNativeTypes.CONE_SHAPE_PROXYTYPE:
1484 return BSPhysicsShapeType.SHAPE_CONE;
1485 break;
1486 case BroadphaseNativeTypes.CONVEX_SHAPE_PROXYTYPE:
1487 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1488 break;
1489 case BroadphaseNativeTypes.CYLINDER_SHAPE_PROXYTYPE:
1490 return BSPhysicsShapeType.SHAPE_CYLINDER;
1491 break;
1492 case BroadphaseNativeTypes.UNIFORM_SCALING_SHAPE_PROXYTYPE:
1493 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1494 break;
1495 case BroadphaseNativeTypes.MINKOWSKI_SUM_SHAPE_PROXYTYPE:
1496 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1497 break;
1498 case BroadphaseNativeTypes.MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE:
1499 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1500 break;
1501 case BroadphaseNativeTypes.BOX_2D_SHAPE_PROXYTYPE:
1502 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1503 break;
1504 case BroadphaseNativeTypes.CONVEX_2D_SHAPE_PROXYTYPE:
1505 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1506 break;
1507 case BroadphaseNativeTypes.CUSTOM_CONVEX_SHAPE_TYPE:
1508 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1509 break;
1510 //concave shape
1511 case BroadphaseNativeTypes.CONCAVE_SHAPES_START_HERE:
1512 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1513 break;
1514 //keep all the convex shapetype below here, for the check IsConvexShape in broadphase proxy!
1515 case BroadphaseNativeTypes.TRIANGLE_MESH_SHAPE_PROXYTYPE:
1516 return BSPhysicsShapeType.SHAPE_MESH;
1517 break;
1518 case BroadphaseNativeTypes.SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE:
1519 return BSPhysicsShapeType.SHAPE_MESH;
1520 break;
1521 ///used for demo integration FAST/Swift collision library and Bullet
1522 case BroadphaseNativeTypes.FAST_CONCAVE_MESH_PROXYTYPE:
1523 return BSPhysicsShapeType.SHAPE_MESH;
1524 break;
1525 //terrain
1526 case BroadphaseNativeTypes.TERRAIN_SHAPE_PROXYTYPE:
1527 return BSPhysicsShapeType.SHAPE_HEIGHTMAP;
1528 break;
1529 ///Used for GIMPACT Trimesh integration
1530 case BroadphaseNativeTypes.GIMPACT_SHAPE_PROXYTYPE:
1531 return BSPhysicsShapeType.SHAPE_MESH;
1532 break;
1533 ///Multimaterial mesh
1534 case BroadphaseNativeTypes.MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE:
1535 return BSPhysicsShapeType.SHAPE_MESH;
1536 break;
1537
1538 case BroadphaseNativeTypes.EMPTY_SHAPE_PROXYTYPE:
1539 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1540 break;
1541 case BroadphaseNativeTypes.STATIC_PLANE_PROXYTYPE:
1542 return BSPhysicsShapeType.SHAPE_GROUNDPLANE;
1543 break;
1544 case BroadphaseNativeTypes.CUSTOM_CONCAVE_SHAPE_TYPE:
1545 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1546 break;
1547 case BroadphaseNativeTypes.CONCAVE_SHAPES_END_HERE:
1548 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1549 break;
1550
1551 case BroadphaseNativeTypes.COMPOUND_SHAPE_PROXYTYPE:
1552 return BSPhysicsShapeType.SHAPE_COMPOUND;
1553 break;
1554
1555 case BroadphaseNativeTypes.SOFTBODY_SHAPE_PROXYTYPE:
1556 return BSPhysicsShapeType.SHAPE_MESH;
1557 break;
1558 case BroadphaseNativeTypes.HFFLUID_SHAPE_PROXYTYPE:
1559 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1560 break;
1561 case BroadphaseNativeTypes.HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE:
1562 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1563 break;
1564 case BroadphaseNativeTypes.INVALID_SHAPE_PROXYTYPE:
1565 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1566 break;
1567 }
1568 return BSPhysicsShapeType.SHAPE_UNKNOWN;
1569 }
1570
1571 public override void RemoveChildShapeFromCompoundShape(BulletShape cShape, BulletShape removeShape) { /* TODO */ }
1572 public override void UpdateChildTransform(BulletShape pShape, int childIndex, Vector3 pos, Quaternion rot, bool shouldRecalculateLocalAabb) { /* TODO */ }
1573
1574 public override BulletShape CreateGroundPlaneShape(uint pLocalId, float pheight, float pcollisionMargin)
1575 {
1576 StaticPlaneShape m_planeshape = new StaticPlaneShape(new IndexedVector3(0,0,1),(int)pheight );
1577 m_planeshape.SetMargin(pcollisionMargin);
1578 m_planeshape.SetUserPointer(pLocalId);
1579 return new BulletShapeXNA(m_planeshape, BSPhysicsShapeType.SHAPE_GROUNDPLANE);
1580 }
1581
1582 public override BulletConstraint CreateHingeConstraint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, Vector3 ppivotInA, Vector3 ppivotInB, Vector3 paxisInA, Vector3 paxisInB, bool puseLinearReferenceFrameA, bool pdisableCollisionsBetweenLinkedBodies)
1583 {
1584 HingeConstraint constrain = null;
1585 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1586 RigidBody rb1 = (pBody1 as BulletBodyXNA).rigidBody;
1587 RigidBody rb2 = (pBody2 as BulletBodyXNA).rigidBody;
1588 if (rb1 != null && rb2 != null)
1589 {
1590 IndexedVector3 pivotInA = new IndexedVector3(ppivotInA.X, ppivotInA.Y, ppivotInA.Z);
1591 IndexedVector3 pivotInB = new IndexedVector3(ppivotInB.X, ppivotInB.Y, ppivotInB.Z);
1592 IndexedVector3 axisInA = new IndexedVector3(paxisInA.X, paxisInA.Y, paxisInA.Z);
1593 IndexedVector3 axisInB = new IndexedVector3(paxisInB.X, paxisInB.Y, paxisInB.Z);
1594 world.AddConstraint(constrain, pdisableCollisionsBetweenLinkedBodies);
1595 }
1596 return new BulletConstraintXNA(constrain);
1597 }
1598
1599 public override BulletShape CreateHullShape(BulletWorld pWorld, int pHullCount, float[] pConvHulls)
1600 {
1601 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1602 CompoundShape compoundshape = new CompoundShape(false);
1603
1604 compoundshape.SetMargin(world.WorldSettings.Params.collisionMargin);
1605 int ii = 1;
1606
1607 for (int i = 0; i < pHullCount; i++)
1608 {
1609 int vertexCount = (int) pConvHulls[ii];
1610
1611 IndexedVector3 centroid = new IndexedVector3(pConvHulls[ii + 1], pConvHulls[ii + 2], pConvHulls[ii + 3]);
1612 IndexedMatrix childTrans = IndexedMatrix.Identity;
1613 childTrans._origin = centroid;
1614
1615 List<IndexedVector3> virts = new List<IndexedVector3>();
1616 int ender = ((ii + 4) + (vertexCount*3));
1617 for (int iii = ii + 4; iii < ender; iii+=3)
1618 {
1619
1620 virts.Add(new IndexedVector3(pConvHulls[iii], pConvHulls[iii + 1], pConvHulls[iii +2]));
1621 }
1622 ConvexHullShape convexShape = new ConvexHullShape(virts, vertexCount);
1623 convexShape.SetMargin(world.WorldSettings.Params.collisionMargin);
1624 compoundshape.AddChildShape(ref childTrans, convexShape);
1625 ii += (vertexCount*3 + 4);
1626 }
1627
1628 return new BulletShapeXNA(compoundshape, BSPhysicsShapeType.SHAPE_HULL);
1629 }
1630
1631 public override BulletShape BuildHullShapeFromMesh(BulletWorld world, BulletShape meshShape)
1632 {
1633 /* TODO */ return null;
1634
1635 }
1636
1637 public override BulletShape CreateMeshShape(BulletWorld pWorld, int pIndicesCount, int[] indices, int pVerticesCount, float[] verticesAsFloats)
1638 {
1639 //DumpRaw(indices,verticesAsFloats,pIndicesCount,pVerticesCount);
1640
1641 for (int iter = 0; iter < pVerticesCount; iter++)
1642 {
1643 if (verticesAsFloats[iter] > 0 && verticesAsFloats[iter] < 0.0001) verticesAsFloats[iter] = 0;
1644 if (verticesAsFloats[iter] < 0 && verticesAsFloats[iter] > -0.0001) verticesAsFloats[iter] = 0;
1645 }
1646
1647 ObjectArray<int> indicesarr = new ObjectArray<int>(indices);
1648 ObjectArray<float> vertices = new ObjectArray<float>(verticesAsFloats);
1649 DumpRaw(indicesarr,vertices,pIndicesCount,pVerticesCount);
1650 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1651 IndexedMesh mesh = new IndexedMesh();
1652 mesh.m_indexType = PHY_ScalarType.PHY_INTEGER;
1653 mesh.m_numTriangles = pIndicesCount/3;
1654 mesh.m_numVertices = pVerticesCount;
1655 mesh.m_triangleIndexBase = indicesarr;
1656 mesh.m_vertexBase = vertices;
1657 mesh.m_vertexStride = 3;
1658 mesh.m_vertexType = PHY_ScalarType.PHY_FLOAT;
1659 mesh.m_triangleIndexStride = 3;
1660
1661 TriangleIndexVertexArray tribuilder = new TriangleIndexVertexArray();
1662 tribuilder.AddIndexedMesh(mesh, PHY_ScalarType.PHY_INTEGER);
1663 BvhTriangleMeshShape meshShape = new BvhTriangleMeshShape(tribuilder, true,true);
1664 meshShape.SetMargin(world.WorldSettings.Params.collisionMargin);
1665 // world.UpdateSingleAabb(meshShape);
1666 return new BulletShapeXNA(meshShape, BSPhysicsShapeType.SHAPE_MESH);
1667
1668 }
1669 public static void DumpRaw(ObjectArray<int>indices, ObjectArray<float> vertices, int pIndicesCount,int pVerticesCount )
1670 {
1671
1672 String fileName = "objTest3.raw";
1673 String completePath = System.IO.Path.Combine(Util.configDir(), fileName);
1674 StreamWriter sw = new StreamWriter(completePath);
1675 IndexedMesh mesh = new IndexedMesh();
1676
1677 mesh.m_indexType = PHY_ScalarType.PHY_INTEGER;
1678 mesh.m_numTriangles = pIndicesCount / 3;
1679 mesh.m_numVertices = pVerticesCount;
1680 mesh.m_triangleIndexBase = indices;
1681 mesh.m_vertexBase = vertices;
1682 mesh.m_vertexStride = 3;
1683 mesh.m_vertexType = PHY_ScalarType.PHY_FLOAT;
1684 mesh.m_triangleIndexStride = 3;
1685
1686 TriangleIndexVertexArray tribuilder = new TriangleIndexVertexArray();
1687 tribuilder.AddIndexedMesh(mesh, PHY_ScalarType.PHY_INTEGER);
1688
1689
1690
1691 for (int i = 0; i < pVerticesCount; i++)
1692 {
1693
1694 string s = vertices[indices[i * 3]].ToString("0.0000");
1695 s += " " + vertices[indices[i * 3 + 1]].ToString("0.0000");
1696 s += " " + vertices[indices[i * 3 + 2]].ToString("0.0000");
1697
1698 sw.Write(s + "\n");
1699 }
1700
1701 sw.Close();
1702 }
1703 public static void DumpRaw(int[] indices, float[] vertices, int pIndicesCount, int pVerticesCount)
1704 {
1705
1706 String fileName = "objTest6.raw";
1707 String completePath = System.IO.Path.Combine(Util.configDir(), fileName);
1708 StreamWriter sw = new StreamWriter(completePath);
1709 IndexedMesh mesh = new IndexedMesh();
1710
1711 mesh.m_indexType = PHY_ScalarType.PHY_INTEGER;
1712 mesh.m_numTriangles = pIndicesCount / 3;
1713 mesh.m_numVertices = pVerticesCount;
1714 mesh.m_triangleIndexBase = indices;
1715 mesh.m_vertexBase = vertices;
1716 mesh.m_vertexStride = 3;
1717 mesh.m_vertexType = PHY_ScalarType.PHY_FLOAT;
1718 mesh.m_triangleIndexStride = 3;
1719
1720 TriangleIndexVertexArray tribuilder = new TriangleIndexVertexArray();
1721 tribuilder.AddIndexedMesh(mesh, PHY_ScalarType.PHY_INTEGER);
1722
1723
1724 sw.WriteLine("Indices");
1725 sw.WriteLine(string.Format("int[] indices = new int[{0}];",pIndicesCount));
1726 for (int iter = 0; iter < indices.Length; iter++)
1727 {
1728 sw.WriteLine(string.Format("indices[{0}]={1};",iter,indices[iter]));
1729 }
1730 sw.WriteLine("VerticesFloats");
1731 sw.WriteLine(string.Format("float[] vertices = new float[{0}];", pVerticesCount));
1732 for (int iter = 0; iter < vertices.Length; iter++)
1733 {
1734 sw.WriteLine(string.Format("Vertices[{0}]={1};", iter, vertices[iter].ToString("0.0000")));
1735 }
1736
1737 // for (int i = 0; i < pVerticesCount; i++)
1738 // {
1739 //
1740 // string s = vertices[indices[i * 3]].ToString("0.0000");
1741 // s += " " + vertices[indices[i * 3 + 1]].ToString("0.0000");
1742 // s += " " + vertices[indices[i * 3 + 2]].ToString("0.0000");
1743 //
1744 // sw.Write(s + "\n");
1745 //}
1746
1747 sw.Close();
1748 }
1749
1750 public override BulletShape CreateTerrainShape(uint id, Vector3 size, float minHeight, float maxHeight, float[] heightMap,
1751 float scaleFactor, float collisionMargin)
1752 {
1753 const int upAxis = 2;
1754 HeightfieldTerrainShape terrainShape = new HeightfieldTerrainShape((int)size.X, (int)size.Y,
1755 heightMap, scaleFactor,
1756 minHeight, maxHeight, upAxis,
1757 false);
1758 terrainShape.SetMargin(collisionMargin + 0.5f);
1759 terrainShape.SetUseDiamondSubdivision(true);
1760 terrainShape.SetUserPointer(id);
1761 return new BulletShapeXNA(terrainShape, BSPhysicsShapeType.SHAPE_TERRAIN);
1762 }
1763
1764 public override bool TranslationalLimitMotor(BulletConstraint pConstraint, float ponOff, float targetVelocity, float maxMotorForce)
1765 {
1766 TypedConstraint tconstrain = (pConstraint as BulletConstraintXNA).constrain;
1767 bool onOff = ponOff != 0;
1768 bool ret = false;
1769
1770 switch (tconstrain.GetConstraintType())
1771 {
1772 case TypedConstraintType.D6_CONSTRAINT_TYPE:
1773 Generic6DofConstraint constrain = tconstrain as Generic6DofConstraint;
1774 constrain.GetTranslationalLimitMotor().m_enableMotor[0] = onOff;
1775 constrain.GetTranslationalLimitMotor().m_targetVelocity[0] = targetVelocity;
1776 constrain.GetTranslationalLimitMotor().m_maxMotorForce[0] = maxMotorForce;
1777 ret = true;
1778 break;
1779 }
1780
1781
1782 return ret;
1783
1784 }
1785
1786 public override int PhysicsStep(BulletWorld world, float timeStep, int maxSubSteps, float fixedTimeStep,
1787 out int updatedEntityCount, out int collidersCount)
1788 {
1789 /* TODO */
1790 updatedEntityCount = 0;
1791 collidersCount = 0;
1792
1793
1794 int ret = PhysicsStep2(world,timeStep,maxSubSteps,fixedTimeStep,out updatedEntityCount,out world.physicsScene.m_updateArray, out collidersCount, out world.physicsScene.m_collisionArray);
1795
1796 return ret;
1797 }
1798
1799 private int PhysicsStep2(BulletWorld pWorld, float timeStep, int m_maxSubSteps, float m_fixedTimeStep,
1800 out int updatedEntityCount, out EntityProperties[] updatedEntities,
1801 out int collidersCount, out CollisionDesc[] colliders)
1802 {
1803 int epic = PhysicsStepint(pWorld, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out updatedEntities,
1804 out collidersCount, out colliders, m_maxCollisions, m_maxUpdatesPerFrame);
1805 return epic;
1806 }
1807
1808 private int PhysicsStepint(BulletWorld pWorld,float timeStep, int m_maxSubSteps, float m_fixedTimeStep, out int updatedEntityCount,
1809 out EntityProperties[] updatedEntities, out int collidersCount, out CollisionDesc[] colliders, int maxCollisions, int maxUpdates)
1810 {
1811 int numSimSteps = 0;
1812 Array.Clear(UpdatedObjects, 0, UpdatedObjects.Length);
1813 Array.Clear(UpdatedCollisions, 0, UpdatedCollisions.Length);
1814 LastEntityProperty=0;
1815
1816
1817
1818
1819
1820
1821 LastCollisionDesc=0;
1822
1823 updatedEntityCount = 0;
1824 collidersCount = 0;
1825
1826
1827 if (pWorld is BulletWorldXNA)
1828 {
1829 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1830
1831 world.LastCollisionDesc = 0;
1832 world.LastEntityProperty = 0;
1833 numSimSteps = world.StepSimulation(timeStep, m_maxSubSteps, m_fixedTimeStep);
1834 int updates = 0;
1835
1836 PersistentManifold contactManifold;
1837 CollisionObject objA;
1838 CollisionObject objB;
1839 ManifoldPoint manifoldPoint;
1840 PairCachingGhostObject pairCachingGhostObject;
1841
1842 m_collisionsThisFrame = 0;
1843 int numManifolds = world.GetDispatcher().GetNumManifolds();
1844 for (int j = 0; j < numManifolds; j++)
1845 {
1846 contactManifold = world.GetDispatcher().GetManifoldByIndexInternal(j);
1847 int numContacts = contactManifold.GetNumContacts();
1848 if (numContacts == 0)
1849 continue;
1850
1851 objA = contactManifold.GetBody0() as CollisionObject;
1852 objB = contactManifold.GetBody1() as CollisionObject;
1853
1854 manifoldPoint = contactManifold.GetContactPoint(0);
1855 //IndexedVector3 contactPoint = manifoldPoint.GetPositionWorldOnB();
1856 // IndexedVector3 contactNormal = -manifoldPoint.m_normalWorldOnB; // make relative to A
1857
1858 RecordCollision(this, objA, objB, manifoldPoint.GetPositionWorldOnB(), -manifoldPoint.m_normalWorldOnB, manifoldPoint.GetDistance());
1859 m_collisionsThisFrame ++;
1860 if (m_collisionsThisFrame >= 9999999)
1861 break;
1862
1863
1864 }
1865
1866 foreach (GhostObject ghostObject in specialCollisionObjects.Values)
1867 {
1868 pairCachingGhostObject = ghostObject as PairCachingGhostObject;
1869 if (pairCachingGhostObject != null)
1870 {
1871 RecordGhostCollisions(pairCachingGhostObject);
1872 }
1873
1874 }
1875
1876
1877 updatedEntityCount = LastEntityProperty;
1878 updatedEntities = UpdatedObjects;
1879
1880 collidersCount = LastCollisionDesc;
1881 colliders = UpdatedCollisions;
1882
1883
1884 }
1885 else
1886 {
1887 //if (updatedEntities is null)
1888 //updatedEntities = new List<BulletXNA.EntityProperties>();
1889 //updatedEntityCount = 0;
1890
1891
1892 //collidersCount = 0;
1893
1894 updatedEntities = new EntityProperties[0];
1895
1896
1897 colliders = new CollisionDesc[0];
1898
1899 }
1900 return numSimSteps;
1901 }
1902 public void RecordGhostCollisions(PairCachingGhostObject obj)
1903 {
1904 IOverlappingPairCache cache = obj.GetOverlappingPairCache();
1905 ObjectArray<BroadphasePair> pairs = cache.GetOverlappingPairArray();
1906
1907 DiscreteDynamicsWorld world = (PhysicsScene.World as BulletWorldXNA).world;
1908 PersistentManifoldArray manifoldArray = new PersistentManifoldArray();
1909 BroadphasePair collisionPair;
1910 PersistentManifold contactManifold;
1911
1912 CollisionObject objA;
1913 CollisionObject objB;
1914
1915 ManifoldPoint pt;
1916
1917 int numPairs = pairs.Count;
1918
1919 for (int i = 0; i < numPairs; i++)
1920 {
1921 manifoldArray.Clear();
1922 if (LastCollisionDesc < UpdatedCollisions.Length)
1923 break;
1924 collisionPair = world.GetPairCache().FindPair(pairs[i].m_pProxy0, pairs[i].m_pProxy1);
1925 if (collisionPair == null)
1926 continue;
1927
1928 collisionPair.m_algorithm.GetAllContactManifolds(manifoldArray);
1929 for (int j = 0; j < manifoldArray.Count; j++)
1930 {
1931 contactManifold = manifoldArray[j];
1932 int numContacts = contactManifold.GetNumContacts();
1933 objA = contactManifold.GetBody0() as CollisionObject;
1934 objB = contactManifold.GetBody1() as CollisionObject;
1935 for (int p = 0; p < numContacts; p++)
1936 {
1937 pt = contactManifold.GetContactPoint(p);
1938 if (pt.GetDistance() < 0.0f)
1939 {
1940 RecordCollision(this, objA, objB, pt.GetPositionWorldOnA(), -pt.m_normalWorldOnB,pt.GetDistance());
1941 break;
1942 }
1943 }
1944 }
1945 }
1946
1947 }
1948 private static void RecordCollision(BSAPIXNA world, CollisionObject objA, CollisionObject objB, IndexedVector3 contact, IndexedVector3 norm, float penetration)
1949 {
1950
1951 IndexedVector3 contactNormal = norm;
1952 if ((objA.GetCollisionFlags() & BulletXNA.BulletCollision.CollisionFlags.BS_WANTS_COLLISIONS) == 0 &&
1953 (objB.GetCollisionFlags() & BulletXNA.BulletCollision.CollisionFlags.BS_WANTS_COLLISIONS) == 0)
1954 {
1955 return;
1956 }
1957 uint idA = (uint)objA.GetUserPointer();
1958 uint idB = (uint)objB.GetUserPointer();
1959 if (idA > idB)
1960 {
1961 uint temp = idA;
1962 idA = idB;
1963 idB = temp;
1964 contactNormal = -contactNormal;
1965 }
1966
1967 //ulong collisionID = ((ulong) idA << 32) | idB;
1968
1969 CollisionDesc cDesc = new CollisionDesc()
1970 {
1971 aID = idA,
1972 bID = idB,
1973 point = new Vector3(contact.X,contact.Y,contact.Z),
1974 normal = new Vector3(contactNormal.X,contactNormal.Y,contactNormal.Z),
1975 penetration = penetration
1976
1977 };
1978 if (world.LastCollisionDesc < world.UpdatedCollisions.Length)
1979 world.UpdatedCollisions[world.LastCollisionDesc++] = (cDesc);
1980 m_collisionsThisFrame++;
1981
1982
1983 }
1984 private static EntityProperties GetDebugProperties(BulletWorld pWorld, BulletBody pCollisionObject)
1985 {
1986 EntityProperties ent = new EntityProperties();
1987 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
1988 CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody;
1989 IndexedMatrix transform = collisionObject.GetWorldTransform();
1990 IndexedVector3 LinearVelocity = collisionObject.GetInterpolationLinearVelocity();
1991 IndexedVector3 AngularVelocity = collisionObject.GetInterpolationAngularVelocity();
1992 IndexedQuaternion rotation = transform.GetRotation();
1993 ent.Acceleration = Vector3.Zero;
1994 ent.ID = (uint)collisionObject.GetUserPointer();
1995 ent.Position = new Vector3(transform._origin.X,transform._origin.Y,transform._origin.Z);
1996 ent.Rotation = new Quaternion(rotation.X,rotation.Y,rotation.Z,rotation.W);
1997 ent.Velocity = new Vector3(LinearVelocity.X, LinearVelocity.Y, LinearVelocity.Z);
1998 ent.RotationalVelocity = new Vector3(AngularVelocity.X, AngularVelocity.Y, AngularVelocity.Z);
1999 return ent;
2000 }
2001
2002 public override bool UpdateParameter(BulletWorld world, uint localID, String parm, float value) { /* TODO */
2003 return false; }
2004
2005 public override Vector3 GetLocalScaling(BulletShape pShape)
2006 {
2007 CollisionShape shape = (pShape as BulletShapeXNA).shape;
2008 IndexedVector3 scale = shape.GetLocalScaling();
2009 return new Vector3(scale.X,scale.Y,scale.Z);
2010 }
2011
2012 public bool RayCastGround(BulletWorld pWorld, Vector3 _RayOrigin, float pRayHeight, BulletBody NotMe)
2013 {
2014 DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world;
2015 if (world != null)
2016 {
2017 if (NotMe is BulletBodyXNA && NotMe.HasPhysicalBody)
2018 {
2019 CollisionObject AvoidBody = (NotMe as BulletBodyXNA).body;
2020
2021 IndexedVector3 rOrigin = new IndexedVector3(_RayOrigin.X, _RayOrigin.Y, _RayOrigin.Z);
2022 IndexedVector3 rEnd = new IndexedVector3(_RayOrigin.X, _RayOrigin.Y, _RayOrigin.Z - pRayHeight);
2023 using (
2024 ClosestNotMeRayResultCallback rayCallback =
2025 new ClosestNotMeRayResultCallback(rOrigin, rEnd, AvoidBody)
2026 )
2027 {
2028 world.RayTest(ref rOrigin, ref rEnd, rayCallback);
2029 if (rayCallback.HasHit())
2030 {
2031 IndexedVector3 hitLocation = rayCallback.m_hitPointWorld;
2032 }
2033 return rayCallback.HasHit();
2034 }
2035 }
2036 }
2037 return false;
2038 }
2039}
2040
2041
2042
2043
2044 public class SimMotionState : DefaultMotionState
2045 {
2046 public RigidBody Rigidbody;
2047 public Vector3 ZeroVect;
2048
2049 private IndexedMatrix m_xform;
2050
2051 private EntityProperties m_properties;
2052 private EntityProperties m_lastProperties;
2053 private BSAPIXNA m_world;
2054
2055 const float POSITION_TOLERANCE = 0.05f;
2056 const float VELOCITY_TOLERANCE = 0.001f;
2057 const float ROTATION_TOLERANCE = 0.01f;
2058 const float ANGULARVELOCITY_TOLERANCE = 0.01f;
2059
2060 public SimMotionState(BSAPIXNA pWorld, uint id, IndexedMatrix starTransform, object frameUpdates)
2061 {
2062 IndexedQuaternion OrientationQuaterion = starTransform.GetRotation();
2063 m_properties = new EntityProperties()
2064 {
2065 ID = id,
2066 Position = new Vector3(starTransform._origin.X, starTransform._origin.Y,starTransform._origin.Z),
2067 Rotation = new Quaternion(OrientationQuaterion.X,OrientationQuaterion.Y,OrientationQuaterion.Z,OrientationQuaterion.W)
2068 };
2069 m_lastProperties = new EntityProperties()
2070 {
2071 ID = id,
2072 Position = new Vector3(starTransform._origin.X, starTransform._origin.Y, starTransform._origin.Z),
2073 Rotation = new Quaternion(OrientationQuaterion.X, OrientationQuaterion.Y, OrientationQuaterion.Z, OrientationQuaterion.W)
2074 };
2075 m_world = pWorld;
2076 m_xform = starTransform;
2077 }
2078
2079 public override void GetWorldTransform(out IndexedMatrix worldTrans)
2080 {
2081 worldTrans = m_xform;
2082 }
2083
2084 public override void SetWorldTransform(IndexedMatrix worldTrans)
2085 {
2086 SetWorldTransform(ref worldTrans);
2087 }
2088
2089 public override void SetWorldTransform(ref IndexedMatrix worldTrans)
2090 {
2091 SetWorldTransform(ref worldTrans, false);
2092 }
2093 public void SetWorldTransform(ref IndexedMatrix worldTrans, bool force)
2094 {
2095 m_xform = worldTrans;
2096 // Put the new transform into m_properties
2097 IndexedQuaternion OrientationQuaternion = m_xform.GetRotation();
2098 IndexedVector3 LinearVelocityVector = Rigidbody.GetLinearVelocity();
2099 IndexedVector3 AngularVelocityVector = Rigidbody.GetAngularVelocity();
2100 m_properties.Position = new Vector3(m_xform._origin.X, m_xform._origin.Y, m_xform._origin.Z);
2101 m_properties.Rotation = new Quaternion(OrientationQuaternion.X, OrientationQuaternion.Y,
2102 OrientationQuaternion.Z, OrientationQuaternion.W);
2103 // A problem with stock Bullet is that we don't get an event when an object is deactivated.
2104 // This means that the last non-zero values for linear and angular velocity
2105 // are left in the viewer who does dead reconning and the objects look like
2106 // they float off.
2107 // BulletSim ships with a patch to Bullet which creates such an event.
2108 m_properties.Velocity = new Vector3(LinearVelocityVector.X, LinearVelocityVector.Y, LinearVelocityVector.Z);
2109 m_properties.RotationalVelocity = new Vector3(AngularVelocityVector.X, AngularVelocityVector.Y, AngularVelocityVector.Z);
2110
2111 if (force
2112
2113 || !AlmostEqual(ref m_lastProperties.Position, ref m_properties.Position, POSITION_TOLERANCE)
2114 || !AlmostEqual(ref m_properties.Rotation, ref m_lastProperties.Rotation, ROTATION_TOLERANCE)
2115 // If the Velocity and AngularVelocity are zero, most likely the object has
2116 // been deactivated. If they both are zero and they have become zero recently,
2117 // make sure a property update is sent so the zeros make it to the viewer.
2118 || ((m_properties.Velocity == ZeroVect && m_properties.RotationalVelocity == ZeroVect)
2119 &&
2120 (m_properties.Velocity != m_lastProperties.Velocity ||
2121 m_properties.RotationalVelocity != m_lastProperties.RotationalVelocity))
2122 // If Velocity and AngularVelocity are non-zero but have changed, send an update.
2123 || !AlmostEqual(ref m_properties.Velocity, ref m_lastProperties.Velocity, VELOCITY_TOLERANCE)
2124 ||
2125 !AlmostEqual(ref m_properties.RotationalVelocity, ref m_lastProperties.RotationalVelocity,
2126 ANGULARVELOCITY_TOLERANCE)
2127 )
2128
2129
2130 {
2131 // Add this update to the list of updates for this frame.
2132 m_lastProperties = m_properties;
2133 if (m_world.LastEntityProperty < m_world.UpdatedObjects.Length)
2134 m_world.UpdatedObjects[m_world.LastEntityProperty++]=(m_properties);
2135
2136 //(*m_updatesThisFrame)[m_properties.ID] = &m_properties;
2137 }
2138
2139
2140
2141
2142 }
2143 public override void SetRigidBody(RigidBody body)
2144 {
2145 Rigidbody = body;
2146 }
2147 internal static bool AlmostEqual(ref Vector3 v1, ref Vector3 v2, float nEpsilon)
2148 {
2149 return
2150 (((v1.X - nEpsilon) < v2.X) && (v2.X < (v1.X + nEpsilon))) &&
2151 (((v1.Y - nEpsilon) < v2.Y) && (v2.Y < (v1.Y + nEpsilon))) &&
2152 (((v1.Z - nEpsilon) < v2.Z) && (v2.Z < (v1.Z + nEpsilon)));
2153 }
2154
2155 internal static bool AlmostEqual(ref Quaternion v1, ref Quaternion v2, float nEpsilon)
2156 {
2157 return
2158 (((v1.X - nEpsilon) < v2.X) && (v2.X < (v1.X + nEpsilon))) &&
2159 (((v1.Y - nEpsilon) < v2.Y) && (v2.Y < (v1.Y + nEpsilon))) &&
2160 (((v1.Z - nEpsilon) < v2.Z) && (v2.Z < (v1.Z + nEpsilon))) &&
2161 (((v1.W - nEpsilon) < v2.W) && (v2.W < (v1.W + nEpsilon)));
2162 }
2163
2164 }
2165}
2166