aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Physics
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Physics')
-rw-r--r--OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs124
-rwxr-xr-xOpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs3
-rw-r--r--OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs9
-rwxr-xr-xOpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs50
-rwxr-xr-xOpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs60
-rw-r--r--OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs86
-rw-r--r--OpenSim/Region/Physics/BulletSPlugin/BSScene.cs371
-rwxr-xr-xOpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs464
-rw-r--r--OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs115
9 files changed, 961 insertions, 321 deletions
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
index 1b23a36..747ae71 100644
--- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
@@ -34,13 +34,12 @@ using OpenSim.Region.Physics.Manager;
34 34
35namespace OpenSim.Region.Physics.BulletSPlugin 35namespace OpenSim.Region.Physics.BulletSPlugin
36{ 36{
37public class BSCharacter : PhysicsActor 37public class BSCharacter : BSPhysObject
38{ 38{
39 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 39 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
40 private static readonly string LogHeader = "[BULLETS CHAR]"; 40 private static readonly string LogHeader = "[BULLETS CHAR]";
41 41
42 private BSScene _scene; 42 public BSScene Scene { get; private set; }
43 public BSScene Scene { get { return _scene; } }
44 private String _avName; 43 private String _avName;
45 // private bool _stopped; 44 // private bool _stopped;
46 private Vector3 _size; 45 private Vector3 _size;
@@ -74,11 +73,8 @@ public class BSCharacter : PhysicsActor
74 private bool _kinematic; 73 private bool _kinematic;
75 private float _buoyancy; 74 private float _buoyancy;
76 75
77 private BulletBody m_body; 76 public override BulletBody Body { get; set; }
78 public BulletBody Body { 77 public override BSLinkset Linkset { get; set; }
79 get { return m_body; }
80 set { m_body = value; }
81 }
82 78
83 private int _subscribedEventsMs = 0; 79 private int _subscribedEventsMs = 0;
84 private int _nextCollisionOkTime = 0; 80 private int _nextCollisionOkTime = 0;
@@ -95,7 +91,7 @@ public class BSCharacter : PhysicsActor
95 { 91 {
96 _localID = localID; 92 _localID = localID;
97 _avName = avName; 93 _avName = avName;
98 _scene = parent_scene; 94 Scene = parent_scene;
99 _position = pos; 95 _position = pos;
100 _size = size; 96 _size = size;
101 _flying = isFlying; 97 _flying = isFlying;
@@ -104,10 +100,12 @@ public class BSCharacter : PhysicsActor
104 _buoyancy = ComputeBuoyancyFromFlying(isFlying); 100 _buoyancy = ComputeBuoyancyFromFlying(isFlying);
105 // The dimensions of the avatar capsule are kept in the scale. 101 // The dimensions of the avatar capsule are kept in the scale.
106 // Physics creates a unit capsule which is scaled by the physics engine. 102 // Physics creates a unit capsule which is scaled by the physics engine.
107 _scale = new Vector3(_scene.Params.avatarCapsuleRadius, _scene.Params.avatarCapsuleRadius, size.Z); 103 _scale = new Vector3(Scene.Params.avatarCapsuleRadius, Scene.Params.avatarCapsuleRadius, size.Z);
108 _density = _scene.Params.avatarDensity; 104 _density = Scene.Params.avatarDensity;
109 ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale 105 ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale
110 106
107 Linkset = new BSLinkset(Scene, this);
108
111 ShapeData shapeData = new ShapeData(); 109 ShapeData shapeData = new ShapeData();
112 shapeData.ID = _localID; 110 shapeData.ID = _localID;
113 shapeData.Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR; 111 shapeData.Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR;
@@ -118,19 +116,19 @@ public class BSCharacter : PhysicsActor
118 shapeData.Mass = _mass; 116 shapeData.Mass = _mass;
119 shapeData.Buoyancy = _buoyancy; 117 shapeData.Buoyancy = _buoyancy;
120 shapeData.Static = ShapeData.numericFalse; 118 shapeData.Static = ShapeData.numericFalse;
121 shapeData.Friction = _scene.Params.avatarFriction; 119 shapeData.Friction = Scene.Params.avatarFriction;
122 shapeData.Restitution = _scene.Params.avatarRestitution; 120 shapeData.Restitution = Scene.Params.avatarRestitution;
123 121
124 // do actual create at taint time 122 // do actual create at taint time
125 _scene.TaintedObject("BSCharacter.create", delegate() 123 Scene.TaintedObject("BSCharacter.create", delegate()
126 { 124 {
127 DetailLog("{0},BSCharacter.create", _localID); 125 DetailLog("{0},BSCharacter.create", _localID);
128 BulletSimAPI.CreateObject(parent_scene.WorldID, shapeData); 126 BulletSimAPI.CreateObject(Scene.WorldID, shapeData);
129 127
130 // Set the buoyancy for flying. This will be refactored when all the settings happen in C# 128 // Set the buoyancy for flying. This will be refactored when all the settings happen in C#
131 BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _buoyancy); 129 BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy);
132 130
133 m_body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); 131 Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(Scene.World.Ptr, LocalID));
134 // avatars get all collisions no matter what (makes walking on ground and such work) 132 // avatars get all collisions no matter what (makes walking on ground and such work)
135 BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); 133 BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
136 }); 134 });
@@ -139,12 +137,12 @@ public class BSCharacter : PhysicsActor
139 } 137 }
140 138
141 // called when this character is being destroyed and the resources should be released 139 // called when this character is being destroyed and the resources should be released
142 public void Destroy() 140 public override void Destroy()
143 { 141 {
144 DetailLog("{0},BSCharacter.Destroy", LocalID); 142 DetailLog("{0},BSCharacter.Destroy", LocalID);
145 _scene.TaintedObject("BSCharacter.destroy", delegate() 143 Scene.TaintedObject("BSCharacter.destroy", delegate()
146 { 144 {
147 BulletSimAPI.DestroyObject(_scene.WorldID, _localID); 145 BulletSimAPI.DestroyObject(Scene.WorldID, _localID);
148 }); 146 });
149 } 147 }
150 148
@@ -173,9 +171,9 @@ public class BSCharacter : PhysicsActor
173 171
174 ComputeAvatarVolumeAndMass(); 172 ComputeAvatarVolumeAndMass();
175 173
176 _scene.TaintedObject("BSCharacter.setSize", delegate() 174 Scene.TaintedObject("BSCharacter.setSize", delegate()
177 { 175 {
178 BulletSimAPI.SetObjectScaleMass(_scene.WorldID, LocalID, _scale, _mass, true); 176 BulletSimAPI.SetObjectScaleMass(Scene.WorldID, LocalID, _scale, _mass, true);
179 }); 177 });
180 178
181 } 179 }
@@ -204,17 +202,17 @@ public class BSCharacter : PhysicsActor
204 202
205 public override Vector3 Position { 203 public override Vector3 Position {
206 get { 204 get {
207 // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); 205 // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID);
208 return _position; 206 return _position;
209 } 207 }
210 set { 208 set {
211 _position = value; 209 _position = value;
212 PositionSanityCheck(); 210 PositionSanityCheck();
213 211
214 _scene.TaintedObject("BSCharacter.setPosition", delegate() 212 Scene.TaintedObject("BSCharacter.setPosition", delegate()
215 { 213 {
216 DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); 214 DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation);
217 BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); 215 BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation);
218 }); 216 });
219 } 217 }
220 } 218 }
@@ -227,16 +225,35 @@ public class BSCharacter : PhysicsActor
227 bool ret = false; 225 bool ret = false;
228 226
229 // If below the ground, move the avatar up 227 // If below the ground, move the avatar up
230 float terrainHeight = Scene.GetTerrainHeightAtXYZ(_position); 228 float terrainHeight = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position);
231 if (_position.Z < terrainHeight) 229 if (Position.Z < terrainHeight)
232 { 230 {
233 DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},orient={2}", LocalID, _position, _orientation); 231 DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight);
234 _position.Z = terrainHeight + 2.0f; 232 _position.Z = terrainHeight + 2.0f;
235 ret = true; 233 ret = true;
236 } 234 }
237 235
238 // TODO: check for out of bounds 236 // TODO: check for out of bounds
237 return ret;
238 }
239 239
240 // A version of the sanity check that also makes sure a new position value is
241 // pushed back to the physics engine. This routine would be used by anyone
242 // who is not already pushing the value.
243 private bool PositionSanityCheck2()
244 {
245 bool ret = false;
246 if (PositionSanityCheck())
247 {
248 // The new position value must be pushed into the physics engine but we can't
249 // just assign to "Position" because of potential call loops.
250 Scene.TaintedObject("BSCharacter.PositionSanityCheck", delegate()
251 {
252 DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation);
253 BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation);
254 });
255 ret = true;
256 }
240 return ret; 257 return ret;
241 } 258 }
242 259
@@ -245,6 +262,10 @@ public class BSCharacter : PhysicsActor
245 return _mass; 262 return _mass;
246 } 263 }
247 } 264 }
265
266 // used when we only want this prim's mass and not the linkset thing
267 public override float MassRaw { get {return _mass; } }
268
248 public override Vector3 Force { 269 public override Vector3 Force {
249 get { return _force; } 270 get { return _force; }
250 set { 271 set {
@@ -277,10 +298,10 @@ public class BSCharacter : PhysicsActor
277 set { 298 set {
278 _velocity = value; 299 _velocity = value;
279 // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity); 300 // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity);
280 _scene.TaintedObject("BSCharacter.setVelocity", delegate() 301 Scene.TaintedObject("BSCharacter.setVelocity", delegate()
281 { 302 {
282 DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); 303 DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity);
283 BulletSimAPI.SetObjectVelocity(_scene.WorldID, _localID, _velocity); 304 BulletSimAPI.SetObjectVelocity(Scene.WorldID, _localID, _velocity);
284 }); 305 });
285 } 306 }
286 } 307 }
@@ -303,10 +324,10 @@ public class BSCharacter : PhysicsActor
303 set { 324 set {
304 _orientation = value; 325 _orientation = value;
305 // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation); 326 // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation);
306 _scene.TaintedObject("BSCharacter.setOrientation", delegate() 327 Scene.TaintedObject("BSCharacter.setOrientation", delegate()
307 { 328 {
308 // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); 329 // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID);
309 BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); 330 BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation);
310 }); 331 });
311 } 332 }
312 } 333 }
@@ -343,11 +364,11 @@ public class BSCharacter : PhysicsActor
343 set { _throttleUpdates = value; } 364 set { _throttleUpdates = value; }
344 } 365 }
345 public override bool IsColliding { 366 public override bool IsColliding {
346 get { return (_collidingStep == _scene.SimulationStep); } 367 get { return (_collidingStep == Scene.SimulationStep); }
347 set { _isColliding = value; } 368 set { _isColliding = value; }
348 } 369 }
349 public override bool CollidingGround { 370 public override bool CollidingGround {
350 get { return (_collidingGroundStep == _scene.SimulationStep); } 371 get { return (_collidingGroundStep == Scene.SimulationStep); }
351 set { _collidingGround = value; } 372 set { _collidingGround = value; }
352 } 373 }
353 public override bool CollidingObj { 374 public override bool CollidingObj {
@@ -369,10 +390,10 @@ public class BSCharacter : PhysicsActor
369 public override float Buoyancy { 390 public override float Buoyancy {
370 get { return _buoyancy; } 391 get { return _buoyancy; }
371 set { _buoyancy = value; 392 set { _buoyancy = value;
372 _scene.TaintedObject("BSCharacter.setBuoyancy", delegate() 393 Scene.TaintedObject("BSCharacter.setBuoyancy", delegate()
373 { 394 {
374 DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); 395 DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
375 BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _buoyancy); 396 BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy);
376 }); 397 });
377 } 398 }
378 } 399 }
@@ -416,7 +437,7 @@ public class BSCharacter : PhysicsActor
416 _force.Y += force.Y; 437 _force.Y += force.Y;
417 _force.Z += force.Z; 438 _force.Z += force.Z;
418 // m_log.DebugFormat("{0}: AddForce. adding={1}, newForce={2}", LogHeader, force, _force); 439 // m_log.DebugFormat("{0}: AddForce. adding={1}, newForce={2}", LogHeader, force, _force);
419 _scene.TaintedObject("BSCharacter.AddForce", delegate() 440 Scene.TaintedObject("BSCharacter.AddForce", delegate()
420 { 441 {
421 DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); 442 DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force);
422 BulletSimAPI.AddObjectForce2(Body.Ptr, _force); 443 BulletSimAPI.AddObjectForce2(Body.Ptr, _force);
@@ -448,6 +469,12 @@ public class BSCharacter : PhysicsActor
448 }); 469 });
449 } 470 }
450 } 471 }
472
473 public override void ZeroMotion()
474 {
475 return;
476 }
477
451 // Stop collision events 478 // Stop collision events
452 public override void UnSubscribeEvents() { 479 public override void UnSubscribeEvents() {
453 _subscribedEventsMs = 0; 480 _subscribedEventsMs = 0;
@@ -481,7 +508,7 @@ public class BSCharacter : PhysicsActor
481 508
482 // The physics engine says that properties have updated. Update same and inform 509 // The physics engine says that properties have updated. Update same and inform
483 // the world that things have changed. 510 // the world that things have changed.
484 public void UpdateProperties(EntityProperties entprop) 511 public override void UpdateProperties(EntityProperties entprop)
485 { 512 {
486 _position = entprop.Position; 513 _position = entprop.Position;
487 _orientation = entprop.Rotation; 514 _orientation = entprop.Rotation;
@@ -491,30 +518,33 @@ public class BSCharacter : PhysicsActor
491 // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. 518 // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
492 // base.RequestPhysicsterseUpdate(); 519 // base.RequestPhysicsterseUpdate();
493 520
494 DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", 521 // Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
495 LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, 522 PositionSanityCheck2();
496 entprop.Acceleration, entprop.RotationalVelocity); 523
524 float heightHere = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); // only for debug
525 DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5},terrain={6}",
526 LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity, heightHere);
497 } 527 }
498 528
499 // Called by the scene when a collision with this object is reported 529 // Called by the scene when a collision with this object is reported
500 // The collision, if it should be reported to the character, is placed in a collection 530 // The collision, if it should be reported to the character, is placed in a collection
501 // that will later be sent to the simulator when SendCollisions() is called. 531 // that will later be sent to the simulator when SendCollisions() is called.
502 CollisionEventUpdate collisionCollection = null; 532 CollisionEventUpdate collisionCollection = null;
503 public void Collide(uint collidingWith, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) 533 public override void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth)
504 { 534 {
505 // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); 535 // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith);
506 536
507 // The following makes IsColliding() and IsCollidingGround() work 537 // The following makes IsColliding() and IsCollidingGround() work
508 _collidingStep = _scene.SimulationStep; 538 _collidingStep = Scene.SimulationStep;
509 if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID) 539 if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID)
510 { 540 {
511 _collidingGroundStep = _scene.SimulationStep; 541 _collidingGroundStep = Scene.SimulationStep;
512 } 542 }
513 // DetailLog("{0},BSCharacter.Collison,call,with={1}", LocalID, collidingWith); 543 // DetailLog("{0},BSCharacter.Collison,call,with={1}", LocalID, collidingWith);
514 544
515 // throttle collisions to the rate specified in the subscription 545 // throttle collisions to the rate specified in the subscription
516 if (_subscribedEventsMs != 0) { 546 if (_subscribedEventsMs != 0) {
517 int nowTime = _scene.SimulationNowTime; 547 int nowTime = Scene.SimulationNowTime;
518 if (nowTime >= _nextCollisionOkTime) { 548 if (nowTime >= _nextCollisionOkTime) {
519 _nextCollisionOkTime = nowTime + _subscribedEventsMs; 549 _nextCollisionOkTime = nowTime + _subscribedEventsMs;
520 550
@@ -525,7 +555,7 @@ public class BSCharacter : PhysicsActor
525 } 555 }
526 } 556 }
527 557
528 public void SendCollisions() 558 public override void SendCollisions()
529 { 559 {
530 /* 560 /*
531 if (collisionCollection != null && collisionCollection.Count > 0) 561 if (collisionCollection != null && collisionCollection.Count > 0)
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs
index 25084d8..d9270d1 100755
--- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs
@@ -48,11 +48,10 @@ public abstract class BSConstraint : IDisposable
48 { 48 {
49 if (m_enabled) 49 if (m_enabled)
50 { 50 {
51 // BulletSimAPI.RemoveConstraint(m_world.ID, m_body1.ID, m_body2.ID); 51 m_enabled = false;
52 bool success = BulletSimAPI.DestroyConstraint2(m_world.Ptr, m_constraint.Ptr); 52 bool success = BulletSimAPI.DestroyConstraint2(m_world.Ptr, m_constraint.Ptr);
53 m_world.scene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success); 53 m_world.scene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success);
54 m_constraint.Ptr = System.IntPtr.Zero; 54 m_constraint.Ptr = System.IntPtr.Zero;
55 m_enabled = false;
56 } 55 }
57 } 56 }
58 57
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs
index d7213fc..8169e99 100644
--- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs
@@ -465,6 +465,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin
465 } 465 }
466 }//end SetDefaultsForType 466 }//end SetDefaultsForType
467 467
468 // One step of the vehicle properties for the next 'pTimestep' seconds.
468 internal void Step(float pTimestep) 469 internal void Step(float pTimestep)
469 { 470 {
470 if (m_type == Vehicle.TYPE_NONE) return; 471 if (m_type == Vehicle.TYPE_NONE) return;
@@ -592,9 +593,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin
592 } 593 }
593 594
594 // If below the terrain, move us above the ground a little. 595 // If below the terrain, move us above the ground a little.
595 if (pos.Z < m_prim.Scene.GetTerrainHeightAtXYZ(pos)) 596 if (pos.Z < m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos))
596 { 597 {
597 pos.Z = m_prim.Scene.GetTerrainHeightAtXYZ(pos) + 2; 598 pos.Z = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos) + 2;
598 m_prim.Position = pos; 599 m_prim.Position = pos;
599 VDetailLog("{0},MoveLinear,terrainHeight,pos={1}", m_prim.LocalID, pos); 600 VDetailLog("{0},MoveLinear,terrainHeight,pos={1}", m_prim.LocalID, pos);
600 } 601 }
@@ -609,7 +610,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin
609 } 610 }
610 if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) 611 if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0)
611 { 612 {
612 m_VhoverTargetHeight = m_prim.Scene.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight; 613 m_VhoverTargetHeight = m_prim.Scene.TerrainManager.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight;
613 } 614 }
614 if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0) 615 if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0)
615 { 616 {
@@ -673,7 +674,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin
673 { 674 {
674 grav.Z = (float)(grav.Z * 1.125); 675 grav.Z = (float)(grav.Z * 1.125);
675 } 676 }
676 float terraintemp = m_prim.Scene.GetTerrainHeightAtXYZ(pos); 677 float terraintemp = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos);
677 float postemp = (pos.Z - terraintemp); 678 float postemp = (pos.Z - terraintemp);
678 if (postemp > 2.5f) 679 if (postemp > 2.5f)
679 { 680 {
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs
index 9e3f0db..b04e1b6 100755
--- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs
@@ -36,8 +36,8 @@ public class BSLinkset
36{ 36{
37 private static string LogHeader = "[BULLETSIM LINKSET]"; 37 private static string LogHeader = "[BULLETSIM LINKSET]";
38 38
39 private BSPrim m_linksetRoot; 39 private BSPhysObject m_linksetRoot;
40 public BSPrim LinksetRoot { get { return m_linksetRoot; } } 40 public BSPhysObject LinksetRoot { get { return m_linksetRoot; } }
41 41
42 private BSScene m_physicsScene; 42 private BSScene m_physicsScene;
43 public BSScene PhysicsScene { get { return m_physicsScene; } } 43 public BSScene PhysicsScene { get { return m_physicsScene; } }
@@ -46,7 +46,7 @@ public class BSLinkset
46 public int LinksetID { get; private set; } 46 public int LinksetID { get; private set; }
47 47
48 // The children under the root in this linkset 48 // The children under the root in this linkset
49 private List<BSPrim> m_children; 49 private List<BSPhysObject> m_children;
50 50
51 // We lock the diddling of linkset classes to prevent any badness. 51 // We lock the diddling of linkset classes to prevent any badness.
52 // This locks the modification of the instances of this class. Changes 52 // This locks the modification of the instances of this class. Changes
@@ -74,7 +74,7 @@ public class BSLinkset
74 get { return ComputeLinksetGeometricCenter(); } 74 get { return ComputeLinksetGeometricCenter(); }
75 } 75 }
76 76
77 public BSLinkset(BSScene scene, BSPrim parent) 77 public BSLinkset(BSScene scene, BSPhysObject parent)
78 { 78 {
79 // A simple linkset of one (no children) 79 // A simple linkset of one (no children)
80 LinksetID = m_nextLinksetID++; 80 LinksetID = m_nextLinksetID++;
@@ -83,14 +83,14 @@ public class BSLinkset
83 m_nextLinksetID = 1; 83 m_nextLinksetID = 1;
84 m_physicsScene = scene; 84 m_physicsScene = scene;
85 m_linksetRoot = parent; 85 m_linksetRoot = parent;
86 m_children = new List<BSPrim>(); 86 m_children = new List<BSPhysObject>();
87 m_mass = parent.MassRaw; 87 m_mass = parent.MassRaw;
88 } 88 }
89 89
90 // Link to a linkset where the child knows the parent. 90 // Link to a linkset where the child knows the parent.
91 // Parent changing should not happen so do some sanity checking. 91 // Parent changing should not happen so do some sanity checking.
92 // We return the parent's linkset so the child can track its membership. 92 // We return the parent's linkset so the child can track its membership.
93 public BSLinkset AddMeToLinkset(BSPrim child) 93 public BSLinkset AddMeToLinkset(BSPhysObject child)
94 { 94 {
95 lock (m_linksetActivityLock) 95 lock (m_linksetActivityLock)
96 { 96 {
@@ -102,7 +102,7 @@ public class BSLinkset
102 // Remove a child from a linkset. 102 // Remove a child from a linkset.
103 // Returns a new linkset for the child which is a linkset of one (just the 103 // Returns a new linkset for the child which is a linkset of one (just the
104 // orphened child). 104 // orphened child).
105 public BSLinkset RemoveMeFromLinkset(BSPrim child) 105 public BSLinkset RemoveMeFromLinkset(BSPhysObject child)
106 { 106 {
107 lock (m_linksetActivityLock) 107 lock (m_linksetActivityLock)
108 { 108 {
@@ -129,7 +129,7 @@ public class BSLinkset
129 } 129 }
130 130
131 // Return 'true' if the passed object is the root object of this linkset 131 // Return 'true' if the passed object is the root object of this linkset
132 public bool IsRoot(BSPrim requestor) 132 public bool IsRoot(BSPhysObject requestor)
133 { 133 {
134 return (requestor.LocalID == m_linksetRoot.LocalID); 134 return (requestor.LocalID == m_linksetRoot.LocalID);
135 } 135 }
@@ -140,12 +140,12 @@ public class BSLinkset
140 public bool HasAnyChildren { get { return (m_children.Count > 0); } } 140 public bool HasAnyChildren { get { return (m_children.Count > 0); } }
141 141
142 // Return 'true' if this child is in this linkset 142 // Return 'true' if this child is in this linkset
143 public bool HasChild(BSPrim child) 143 public bool HasChild(BSPhysObject child)
144 { 144 {
145 bool ret = false; 145 bool ret = false;
146 lock (m_linksetActivityLock) 146 lock (m_linksetActivityLock)
147 { 147 {
148 foreach (BSPrim bp in m_children) 148 foreach (BSPhysObject bp in m_children)
149 { 149 {
150 if (child.LocalID == bp.LocalID) 150 if (child.LocalID == bp.LocalID)
151 { 151 {
@@ -160,7 +160,7 @@ public class BSLinkset
160 private float ComputeLinksetMass() 160 private float ComputeLinksetMass()
161 { 161 {
162 float mass = m_linksetRoot.MassRaw; 162 float mass = m_linksetRoot.MassRaw;
163 foreach (BSPrim bp in m_children) 163 foreach (BSPhysObject bp in m_children)
164 { 164 {
165 mass += bp.MassRaw; 165 mass += bp.MassRaw;
166 } 166 }
@@ -174,7 +174,7 @@ public class BSLinkset
174 174
175 lock (m_linksetActivityLock) 175 lock (m_linksetActivityLock)
176 { 176 {
177 foreach (BSPrim bp in m_children) 177 foreach (BSPhysObject bp in m_children)
178 { 178 {
179 com += bp.Position * bp.MassRaw; 179 com += bp.Position * bp.MassRaw;
180 totalMass += bp.MassRaw; 180 totalMass += bp.MassRaw;
@@ -192,7 +192,7 @@ public class BSLinkset
192 192
193 lock (m_linksetActivityLock) 193 lock (m_linksetActivityLock)
194 { 194 {
195 foreach (BSPrim bp in m_children) 195 foreach (BSPhysObject bp in m_children)
196 { 196 {
197 com += bp.Position * bp.MassRaw; 197 com += bp.Position * bp.MassRaw;
198 } 198 }
@@ -204,7 +204,7 @@ public class BSLinkset
204 204
205 // When physical properties are changed the linkset needs to recalculate 205 // When physical properties are changed the linkset needs to recalculate
206 // its internal properties. 206 // its internal properties.
207 public void Refresh(BSPrim requestor) 207 public void Refresh(BSPhysObject requestor)
208 { 208 {
209 // If there are no children, there aren't any constraints to recompute 209 // If there are no children, there aren't any constraints to recompute
210 if (!HasAnyChildren) 210 if (!HasAnyChildren)
@@ -230,7 +230,7 @@ public class BSLinkset
230 float linksetMass = LinksetMass; 230 float linksetMass = LinksetMass;
231 lock (m_linksetActivityLock) 231 lock (m_linksetActivityLock)
232 { 232 {
233 foreach (BSPrim child in m_children) 233 foreach (BSPhysObject child in m_children)
234 { 234 {
235 BSConstraint constrain; 235 BSConstraint constrain;
236 if (m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.Body, child.Body, out constrain)) 236 if (m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.Body, child.Body, out constrain))
@@ -255,14 +255,14 @@ public class BSLinkset
255 255
256 // I am the root of a linkset and a new child is being added 256 // I am the root of a linkset and a new child is being added
257 // Called while LinkActivity is locked. 257 // Called while LinkActivity is locked.
258 private void AddChildToLinkset(BSPrim child) 258 private void AddChildToLinkset(BSPhysObject child)
259 { 259 {
260 if (!HasChild(child)) 260 if (!HasChild(child))
261 { 261 {
262 m_children.Add(child); 262 m_children.Add(child);
263 263
264 BSPrim rootx = LinksetRoot; // capture the root as of now 264 BSPhysObject rootx = LinksetRoot; // capture the root as of now
265 BSPrim childx = child; 265 BSPhysObject childx = child;
266 m_physicsScene.TaintedObject("AddChildToLinkset", delegate() 266 m_physicsScene.TaintedObject("AddChildToLinkset", delegate()
267 { 267 {
268 DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); 268 DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID);
@@ -277,7 +277,7 @@ public class BSLinkset
277 // it's still connected to the linkset. 277 // it's still connected to the linkset.
278 // Normal OpenSimulator operation will never do this because other SceneObjectPart information 278 // Normal OpenSimulator operation will never do this because other SceneObjectPart information
279 // has to be updated also (like pointer to prim's parent). 279 // has to be updated also (like pointer to prim's parent).
280 private void RemoveChildFromOtherLinkset(BSPrim pchild) 280 private void RemoveChildFromOtherLinkset(BSPhysObject pchild)
281 { 281 {
282 pchild.Linkset = new BSLinkset(m_physicsScene, pchild); 282 pchild.Linkset = new BSLinkset(m_physicsScene, pchild);
283 RemoveChildFromLinkset(pchild); 283 RemoveChildFromLinkset(pchild);
@@ -285,12 +285,12 @@ public class BSLinkset
285 285
286 // I am the root of a linkset and one of my children is being removed. 286 // I am the root of a linkset and one of my children is being removed.
287 // Safe to call even if the child is not really in my linkset. 287 // Safe to call even if the child is not really in my linkset.
288 private void RemoveChildFromLinkset(BSPrim child) 288 private void RemoveChildFromLinkset(BSPhysObject child)
289 { 289 {
290 if (m_children.Remove(child)) 290 if (m_children.Remove(child))
291 { 291 {
292 BSPrim rootx = LinksetRoot; // capture the root as of now 292 BSPhysObject rootx = LinksetRoot; // capture the root as of now
293 BSPrim childx = child; 293 BSPhysObject childx = child;
294 m_physicsScene.TaintedObject("RemoveChildFromLinkset", delegate() 294 m_physicsScene.TaintedObject("RemoveChildFromLinkset", delegate()
295 { 295 {
296 DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); 296 DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID);
@@ -310,7 +310,7 @@ public class BSLinkset
310 310
311 // Create a constraint between me (root of linkset) and the passed prim (the child). 311 // Create a constraint between me (root of linkset) and the passed prim (the child).
312 // Called at taint time! 312 // Called at taint time!
313 private void PhysicallyLinkAChildToRoot(BSPrim rootPrim, BSPrim childPrim) 313 private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim)
314 { 314 {
315 // Zero motion for children so they don't interpolate 315 // Zero motion for children so they don't interpolate
316 childPrim.ZeroMotion(); 316 childPrim.ZeroMotion();
@@ -383,7 +383,7 @@ public class BSLinkset
383 383
384 // Remove linkage between myself and a particular child 384 // Remove linkage between myself and a particular child
385 // Called at taint time! 385 // Called at taint time!
386 private void PhysicallyUnlinkAChildFromRoot(BSPrim rootPrim, BSPrim childPrim) 386 private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim)
387 { 387 {
388 DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); 388 DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID);
389 389
@@ -396,7 +396,7 @@ public class BSLinkset
396 396
397 // Remove linkage between myself and any possible children I might have 397 // Remove linkage between myself and any possible children I might have
398 // Called at taint time! 398 // Called at taint time!
399 private void PhysicallyUnlinkAllChildrenFromRoot(BSPrim rootPrim) 399 private void PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim)
400 { 400 {
401 DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); 401 DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID);
402 402
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs
new file mode 100755
index 0000000..ef463ca
--- /dev/null
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs
@@ -0,0 +1,60 @@
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.Text;
30
31using OMV = OpenMetaverse;
32using OpenSim.Framework;
33using OpenSim.Region.Physics.Manager;
34
35namespace OpenSim.Region.Physics.BulletSPlugin
36{
37// Class to wrap all objects.
38// The rest of BulletSim doesn't need to keep checking for avatars or prims
39// unless the difference is significant.
40public abstract class BSPhysObject : PhysicsActor
41{
42 public abstract BSLinkset Linkset { get; set; }
43
44 public abstract void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type,
45 OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth);
46 public abstract void SendCollisions();
47
48 // Return the object mass without calculating it or side effects
49 public abstract float MassRaw { get; }
50
51 public abstract BulletBody Body { get; set; }
52 public abstract void ZeroMotion();
53
54 public virtual void StepVehicle(float timeStep) { }
55
56 public abstract void UpdateProperties(EntityProperties entprop);
57
58 public abstract void Destroy();
59}
60}
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs
index d3f1e9c..6bfce5c 100644
--- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs
@@ -37,7 +37,7 @@ using OpenSim.Region.Physics.ConvexDecompositionDotNet;
37namespace OpenSim.Region.Physics.BulletSPlugin 37namespace OpenSim.Region.Physics.BulletSPlugin
38{ 38{
39 [Serializable] 39 [Serializable]
40public sealed class BSPrim : PhysicsActor 40public sealed class BSPrim : BSPhysObject
41{ 41{
42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
43 private static readonly string LogHeader = "[BULLETS PRIM]"; 43 private static readonly string LogHeader = "[BULLETS PRIM]";
@@ -88,23 +88,14 @@ public sealed class BSPrim : PhysicsActor
88 private float _buoyancy; 88 private float _buoyancy;
89 89
90 // Membership in a linkset is controlled by this class. 90 // Membership in a linkset is controlled by this class.
91 private BSLinkset _linkset; 91 public override BSLinkset Linkset { get; set; }
92 public BSLinkset Linkset
93 {
94 get { return _linkset; }
95 set { _linkset = value; }
96 }
97 92
98 private int _subscribedEventsMs = 0; 93 private int _subscribedEventsMs = 0;
99 private int _nextCollisionOkTime = 0; 94 private int _nextCollisionOkTime = 0;
100 long _collidingStep; 95 long _collidingStep;
101 long _collidingGroundStep; 96 long _collidingGroundStep;
102 97
103 private BulletBody m_body; 98 public override BulletBody Body { get; set; }
104 public BulletBody Body {
105 get { return m_body; }
106 set { m_body = value; }
107 }
108 99
109 private BSDynamics _vehicle; 100 private BSDynamics _vehicle;
110 101
@@ -139,7 +130,7 @@ public sealed class BSPrim : PhysicsActor
139 _friction = _scene.Params.defaultFriction; // TODO: compute based on object material 130 _friction = _scene.Params.defaultFriction; // TODO: compute based on object material
140 _density = _scene.Params.defaultDensity; // TODO: compute based on object material 131 _density = _scene.Params.defaultDensity; // TODO: compute based on object material
141 _restitution = _scene.Params.defaultRestitution; 132 _restitution = _scene.Params.defaultRestitution;
142 _linkset = new BSLinkset(Scene, this); // a linkset of one 133 Linkset = new BSLinkset(Scene, this); // a linkset of one
143 _vehicle = new BSDynamics(Scene, this); // add vehicleness 134 _vehicle = new BSDynamics(Scene, this); // add vehicleness
144 _mass = CalculateMass(); 135 _mass = CalculateMass();
145 // do the actual object creation at taint time 136 // do the actual object creation at taint time
@@ -151,23 +142,23 @@ public sealed class BSPrim : PhysicsActor
151 // Get the pointer to the physical body for this object. 142 // Get the pointer to the physical body for this object.
152 // At the moment, we're still letting BulletSim manage the creation and destruction 143 // At the moment, we're still letting BulletSim manage the creation and destruction
153 // of the object. Someday we'll move that into the C# code. 144 // of the object. Someday we'll move that into the C# code.
154 m_body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); 145 Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID));
155 }); 146 });
156 } 147 }
157 148
158 // called when this prim is being destroyed and we should free all the resources 149 // called when this prim is being destroyed and we should free all the resources
159 public void Destroy() 150 public override void Destroy()
160 { 151 {
161 // m_log.DebugFormat("{0}: Destroy, id={1}", LogHeader, LocalID); 152 // m_log.DebugFormat("{0}: Destroy, id={1}", LogHeader, LocalID);
162 153
163 // Undo any links between me and any other object 154 // Undo any links between me and any other object
164 BSPrim parentBefore = _linkset.LinksetRoot; 155 BSPhysObject parentBefore = Linkset.LinksetRoot;
165 int childrenBefore = _linkset.NumberOfChildren; 156 int childrenBefore = Linkset.NumberOfChildren;
166 157
167 _linkset = _linkset.RemoveMeFromLinkset(this); 158 Linkset = Linkset.RemoveMeFromLinkset(this);
168 159
169 DetailLog("{0},BSPrim.Destroy,call,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}", 160 DetailLog("{0},BSPrim.Destroy,call,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}",
170 LocalID, parentBefore.LocalID, childrenBefore, _linkset.LinksetRoot.LocalID, _linkset.NumberOfChildren); 161 LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren);
171 162
172 // Undo any vehicle properties 163 // Undo any vehicle properties
173 this.VehicleType = (int)Vehicle.TYPE_NONE; 164 this.VehicleType = (int)Vehicle.TYPE_NONE;
@@ -230,13 +221,13 @@ public sealed class BSPrim : PhysicsActor
230 BSPrim parent = obj as BSPrim; 221 BSPrim parent = obj as BSPrim;
231 if (parent != null) 222 if (parent != null)
232 { 223 {
233 BSPrim parentBefore = _linkset.LinksetRoot; 224 BSPhysObject parentBefore = Linkset.LinksetRoot;
234 int childrenBefore = _linkset.NumberOfChildren; 225 int childrenBefore = Linkset.NumberOfChildren;
235 226
236 _linkset = parent.Linkset.AddMeToLinkset(this); 227 Linkset = parent.Linkset.AddMeToLinkset(this);
237 228
238 DetailLog("{0},BSPrim.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", 229 DetailLog("{0},BSPrim.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}",
239 LocalID, parentBefore.LocalID, childrenBefore, _linkset.LinksetRoot.LocalID, _linkset.NumberOfChildren); 230 LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren);
240 } 231 }
241 return; 232 return;
242 } 233 }
@@ -246,13 +237,13 @@ public sealed class BSPrim : PhysicsActor
246 // TODO: decide if this parent checking needs to happen at taint time 237 // TODO: decide if this parent checking needs to happen at taint time
247 // Race condition here: if link() and delink() in same simulation tick, the delink will not happen 238 // Race condition here: if link() and delink() in same simulation tick, the delink will not happen
248 239
249 BSPrim parentBefore = _linkset.LinksetRoot; 240 BSPhysObject parentBefore = Linkset.LinksetRoot;
250 int childrenBefore = _linkset.NumberOfChildren; 241 int childrenBefore = Linkset.NumberOfChildren;
251 242
252 _linkset = _linkset.RemoveMeFromLinkset(this); 243 Linkset = Linkset.RemoveMeFromLinkset(this);
253 244
254 DetailLog("{0},BSPrim.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", 245 DetailLog("{0},BSPrim.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ",
255 LocalID, parentBefore.LocalID, childrenBefore, _linkset.LinksetRoot.LocalID, _linkset.NumberOfChildren); 246 LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren);
256 return; 247 return;
257 } 248 }
258 249
@@ -260,7 +251,7 @@ public sealed class BSPrim : PhysicsActor
260 // Do it to the properties so the values get set in the physics engine. 251 // Do it to the properties so the values get set in the physics engine.
261 // Push the setting of the values to the viewer. 252 // Push the setting of the values to the viewer.
262 // Called at taint time! 253 // Called at taint time!
263 public void ZeroMotion() 254 public override void ZeroMotion()
264 { 255 {
265 _velocity = OMV.Vector3.Zero; 256 _velocity = OMV.Vector3.Zero;
266 _acceleration = OMV.Vector3.Zero; 257 _acceleration = OMV.Vector3.Zero;
@@ -281,7 +272,7 @@ public sealed class BSPrim : PhysicsActor
281 272
282 public override OMV.Vector3 Position { 273 public override OMV.Vector3 Position {
283 get { 274 get {
284 if (!_linkset.IsRoot(this)) 275 if (!Linkset.IsRoot(this))
285 // child prims move around based on their parent. Need to get the latest location 276 // child prims move around based on their parent. Need to get the latest location
286 _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); 277 _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID);
287 278
@@ -306,23 +297,23 @@ public sealed class BSPrim : PhysicsActor
306 { 297 {
307 get 298 get
308 { 299 {
309 return _linkset.LinksetMass; 300 return Linkset.LinksetMass;
310 } 301 }
311 } 302 }
312 303
313 // used when we only want this prim's mass and not the linkset thing 304 // used when we only want this prim's mass and not the linkset thing
314 public float MassRaw { get { return _mass; } } 305 public override float MassRaw { get { return _mass; } }
315 306
316 // Is this used? 307 // Is this used?
317 public override OMV.Vector3 CenterOfMass 308 public override OMV.Vector3 CenterOfMass
318 { 309 {
319 get { return _linkset.CenterOfMass; } 310 get { return Linkset.CenterOfMass; }
320 } 311 }
321 312
322 // Is this used? 313 // Is this used?
323 public override OMV.Vector3 GeometricCenter 314 public override OMV.Vector3 GeometricCenter
324 { 315 {
325 get { return _linkset.GeometricCenter; } 316 get { return Linkset.GeometricCenter; }
326 } 317 }
327 318
328 public override OMV.Vector3 Force { 319 public override OMV.Vector3 Force {
@@ -386,7 +377,7 @@ public sealed class BSPrim : PhysicsActor
386 377
387 // Called each simulation step to advance vehicle characteristics. 378 // Called each simulation step to advance vehicle characteristics.
388 // Called from Scene when doing simulation step so we're in taint processing time. 379 // Called from Scene when doing simulation step so we're in taint processing time.
389 public void StepVehicle(float timeStep) 380 public override void StepVehicle(float timeStep)
390 { 381 {
391 if (IsPhysical) 382 if (IsPhysical)
392 _vehicle.Step(timeStep); 383 _vehicle.Step(timeStep);
@@ -431,7 +422,7 @@ public sealed class BSPrim : PhysicsActor
431 } 422 }
432 public override OMV.Quaternion Orientation { 423 public override OMV.Quaternion Orientation {
433 get { 424 get {
434 if (!_linkset.IsRoot(this)) 425 if (!Linkset.IsRoot(this))
435 { 426 {
436 // Children move around because tied to parent. Get a fresh value. 427 // Children move around because tied to parent. Get a fresh value.
437 _orientation = BulletSimAPI.GetObjectOrientation(_scene.WorldID, LocalID); 428 _orientation = BulletSimAPI.GetObjectOrientation(_scene.WorldID, LocalID);
@@ -490,7 +481,7 @@ public sealed class BSPrim : PhysicsActor
490 BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); 481 BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass);
491 482
492 // recompute any linkset parameters 483 // recompute any linkset parameters
493 _linkset.Refresh(this); 484 Linkset.Refresh(this);
494 485
495 CollisionFlags cf = BulletSimAPI.GetCollisionFlags2(Body.Ptr); 486 CollisionFlags cf = BulletSimAPI.GetCollisionFlags2(Body.Ptr);
496 DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, cf); 487 DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, cf);
@@ -1299,7 +1290,7 @@ public sealed class BSPrim : PhysicsActor
1299 const float ACCELERATION_TOLERANCE = 0.01f; 1290 const float ACCELERATION_TOLERANCE = 0.01f;
1300 const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f; 1291 const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f;
1301 1292
1302 public void UpdateProperties(EntityProperties entprop) 1293 public override void UpdateProperties(EntityProperties entprop)
1303 { 1294 {
1304 /* 1295 /*
1305 UpdatedProperties changed = 0; 1296 UpdatedProperties changed = 0;
@@ -1347,7 +1338,7 @@ public sealed class BSPrim : PhysicsActor
1347 // Don't check for damping here -- it's done in BulletSim and SceneObjectPart. 1338 // Don't check for damping here -- it's done in BulletSim and SceneObjectPart.
1348 1339
1349 // Updates only for individual prims and for the root object of a linkset. 1340 // Updates only for individual prims and for the root object of a linkset.
1350 if (_linkset.IsRoot(this)) 1341 if (Linkset.IsRoot(this))
1351 { 1342 {
1352 // Assign to the local variables so the normal set action does not happen 1343 // Assign to the local variables so the normal set action does not happen
1353 _position = entprop.Position; 1344 _position = entprop.Position;
@@ -1375,7 +1366,7 @@ public sealed class BSPrim : PhysicsActor
1375 // I've collided with something 1366 // I've collided with something
1376 // Called at taint time from within the Step() function 1367 // Called at taint time from within the Step() function
1377 CollisionEventUpdate collisionCollection; 1368 CollisionEventUpdate collisionCollection;
1378 public void Collide(uint collidingWith, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) 1369 public override void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
1379 { 1370 {
1380 // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); 1371 // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith);
1381 1372
@@ -1387,18 +1378,15 @@ public sealed class BSPrim : PhysicsActor
1387 } 1378 }
1388 1379
1389 // DetailLog("{0},BSPrim.Collison,call,with={1}", LocalID, collidingWith); 1380 // DetailLog("{0},BSPrim.Collison,call,with={1}", LocalID, collidingWith);
1390 BSPrim collidingWithPrim; 1381
1391 if (_scene.Prims.TryGetValue(collidingWith, out collidingWithPrim)) 1382 // prims in the same linkset cannot collide with each other
1383 if (collidee != null && (this.Linkset.LinksetID == collidee.Linkset.LinksetID))
1392 { 1384 {
1393 // prims in the same linkset cannot collide with each other 1385 return;
1394 if (this.Linkset.LinksetID == collidingWithPrim.Linkset.LinksetID)
1395 {
1396 return;
1397 }
1398 } 1386 }
1399 1387
1400 // if someone is subscribed to collision events.... 1388 // if someone has subscribed for collision events....
1401 if (_subscribedEventsMs != 0) { 1389 if (SubscribedEvents()) {
1402 // throttle the collisions to the number of milliseconds specified in the subscription 1390 // throttle the collisions to the number of milliseconds specified in the subscription
1403 int nowTime = _scene.SimulationNowTime; 1391 int nowTime = _scene.SimulationNowTime;
1404 if (nowTime >= _nextCollisionOkTime) { 1392 if (nowTime >= _nextCollisionOkTime) {
@@ -1412,7 +1400,7 @@ public sealed class BSPrim : PhysicsActor
1412 } 1400 }
1413 1401
1414 // The scene is telling us it's time to pass our collected collisions into the simulator 1402 // The scene is telling us it's time to pass our collected collisions into the simulator
1415 public void SendCollisions() 1403 public override void SendCollisions()
1416 { 1404 {
1417 if (collisionCollection != null && collisionCollection.Count > 0) 1405 if (collisionCollection != null && collisionCollection.Count > 0)
1418 { 1406 {
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs
index 56924aa..4a468af 100644
--- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs
@@ -39,8 +39,6 @@ using log4net;
39using OpenMetaverse; 39using OpenMetaverse;
40 40
41// TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim) 41// TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim)
42// Debug linkset
43// Test with multiple regions in one simulator
44// Adjust character capsule size when height is adjusted (ScenePresence.SetHeight) 42// Adjust character capsule size when height is adjusted (ScenePresence.SetHeight)
45// Test sculpties 43// Test sculpties
46// Compute physics FPS reasonably 44// Compute physics FPS reasonably
@@ -54,10 +52,8 @@ using OpenMetaverse;
54// Use collision masks for collision with terrain and phantom objects 52// Use collision masks for collision with terrain and phantom objects
55// Check out llVolumeDetect. Must do something for that. 53// Check out llVolumeDetect. Must do something for that.
56// Should prim.link() and prim.delink() membership checking happen at taint time? 54// Should prim.link() and prim.delink() membership checking happen at taint time?
57// changing the position and orientation of a linked prim must rebuild the constraint with the root.
58// Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once 55// Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once
59// Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect 56// Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect
60// Implement the genCollisions feature in BulletSim::SetObjectProperties (don't pass up unneeded collisions)
61// Implement LockAngularMotion 57// Implement LockAngularMotion
62// Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation) 58// Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation)
63// Does NeedsMeshing() really need to exclude all the different shapes? 59// Does NeedsMeshing() really need to exclude all the different shapes?
@@ -78,27 +74,22 @@ public class BSScene : PhysicsScene, IPhysicsParameters
78 74
79 public string BulletSimVersion = "?"; 75 public string BulletSimVersion = "?";
80 76
81 private Dictionary<uint, BSCharacter> m_avatars = new Dictionary<uint, BSCharacter>(); 77 public Dictionary<uint, BSPhysObject> PhysObjects = new Dictionary<uint, BSPhysObject>();
82 public Dictionary<uint, BSCharacter> Characters { get { return m_avatars; } }
83
84 private Dictionary<uint, BSPrim> m_prims = new Dictionary<uint, BSPrim>();
85 public Dictionary<uint, BSPrim> Prims { get { return m_prims; } }
86 78
79 private HashSet<BSPhysObject> m_objectsWithCollisions = new HashSet<BSPhysObject>();
80 // Following is a kludge and can be removed when avatar animation updating is
81 // moved to a better place.
87 private HashSet<BSCharacter> m_avatarsWithCollisions = new HashSet<BSCharacter>(); 82 private HashSet<BSCharacter> m_avatarsWithCollisions = new HashSet<BSCharacter>();
88 private HashSet<BSPrim> m_primsWithCollisions = new HashSet<BSPrim>();
89
90 private List<BSPrim> m_vehicles = new List<BSPrim>();
91 83
92 private float[] m_heightMap; 84 // List of all the objects that have vehicle properties and should be called
93 private float m_waterLevel; 85 // to update each physics step.
94 private uint m_worldID; 86 private List<BSPhysObject> m_vehicles = new List<BSPhysObject>();
95 public uint WorldID { get { return m_worldID; } }
96 87
97 // let my minuions use my logger 88 // let my minuions use my logger
98 public ILog Logger { get { return m_log; } } 89 public ILog Logger { get { return m_log; } }
99 90
100 private bool m_initialized = false; 91 // If non-zero, the number of simulation steps between calls to the physics
101 92 // engine to output detailed physics stats. Debug logging level must be on also.
102 private int m_detailedStatsStep = 0; 93 private int m_detailedStatsStep = 0;
103 94
104 public IMesher mesher; 95 public IMesher mesher;
@@ -108,29 +99,31 @@ public class BSScene : PhysicsScene, IPhysicsParameters
108 public float MeshMegaPrimThreshold { get; private set; } 99 public float MeshMegaPrimThreshold { get; private set; }
109 public float SculptLOD { get; private set; } 100 public float SculptLOD { get; private set; }
110 101
111 private BulletSim m_worldSim; 102 public uint WorldID { get; private set; }
112 public BulletSim World 103 public BulletSim World { get; private set; }
113 {
114 get { return m_worldSim; }
115 }
116 private BSConstraintCollection m_constraintCollection;
117 public BSConstraintCollection Constraints
118 {
119 get { return m_constraintCollection; }
120 }
121 104
105 // All the constraints that have been allocated in this instance.
106 public BSConstraintCollection Constraints { get; private set; }
107
108 // Simulation parameters
122 private int m_maxSubSteps; 109 private int m_maxSubSteps;
123 private float m_fixedTimeStep; 110 private float m_fixedTimeStep;
124 private long m_simulationStep = 0; 111 private long m_simulationStep = 0;
125 public long SimulationStep { get { return m_simulationStep; } } 112 public long SimulationStep { get { return m_simulationStep; } }
126 113
114 // The length of the last timestep we were asked to simulate.
115 // This is used by the vehicle code. Since the vehicle code is called
116 // once per simulation step, its constants need to be scaled by this.
127 public float LastSimulatedTimestep { get; private set; } 117 public float LastSimulatedTimestep { get; private set; }
128 118
129 // A value of the time now so all the collision and update routines do not have to get their own 119 // A value of the time now so all the collision and update routines do not have to get their own
130 // Set to 'now' just before all the prims and actors are called for collisions and updates 120 // Set to 'now' just before all the prims and actors are called for collisions and updates
131 private int m_simulationNowTime; 121 public int SimulationNowTime { get; private set; }
132 public int SimulationNowTime { get { return m_simulationNowTime; } } 122
123 // True if initialized and ready to do simulation steps
124 private bool m_initialized = false;
133 125
126 // Pinned memory used to pass step information between managed and unmanaged
134 private int m_maxCollisionsPerFrame; 127 private int m_maxCollisionsPerFrame;
135 private CollisionDesc[] m_collisionArray; 128 private CollisionDesc[] m_collisionArray;
136 private GCHandle m_collisionArrayPinnedHandle; 129 private GCHandle m_collisionArrayPinnedHandle;
@@ -147,6 +140,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters
147 140
148 public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero 141 public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
149 public const uint GROUNDPLANE_ID = 1; 142 public const uint GROUNDPLANE_ID = 1;
143 public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here
144
145 private float m_waterLevel;
146 public BSTerrainManager TerrainManager { get; private set; }
150 147
151 public ConfigurationParameters Params 148 public ConfigurationParameters Params
152 { 149 {
@@ -157,12 +154,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters
157 get { return new Vector3(0f, 0f, Params.gravity); } 154 get { return new Vector3(0f, 0f, Params.gravity); }
158 } 155 }
159 156
160 private float m_maximumObjectMass; 157 public float MaximumObjectMass { get; private set; }
161 public float MaximumObjectMass
162 {
163 get { return m_maximumObjectMass; }
164 }
165 158
159 // When functions in the unmanaged code must be called, it is only
160 // done at a known time just before the simulation step. The taint
161 // system saves all these function calls and executes them in
162 // order before the simulation.
166 public delegate void TaintCallback(); 163 public delegate void TaintCallback();
167 private struct TaintCallbackEntry 164 private struct TaintCallbackEntry
168 { 165 {
@@ -178,6 +175,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
178 private Object _taintLock = new Object(); 175 private Object _taintLock = new Object();
179 176
180 // A pointer to an instance if this structure is passed to the C++ code 177 // A pointer to an instance if this structure is passed to the C++ code
178 // Used to pass basic configuration values to the unmanaged code.
181 ConfigurationParameters[] m_params; 179 ConfigurationParameters[] m_params;
182 GCHandle m_paramsHandle; 180 GCHandle m_paramsHandle;
183 181
@@ -192,10 +190,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters
192 private string m_physicsLoggingDir; 190 private string m_physicsLoggingDir;
193 private string m_physicsLoggingPrefix; 191 private string m_physicsLoggingPrefix;
194 private int m_physicsLoggingFileMinutes; 192 private int m_physicsLoggingFileMinutes;
193 // 'true' of the vehicle code is to log lots of details
194 public bool VehicleLoggingEnabled { get; private set; }
195 195
196 private bool m_vehicleLoggingEnabled; 196 #region Construction and Initialization
197 public bool VehicleLoggingEnabled { get { return m_vehicleLoggingEnabled; } }
198
199 public BSScene(string identifier) 197 public BSScene(string identifier)
200 { 198 {
201 m_initialized = false; 199 m_initialized = false;
@@ -218,6 +216,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters
218 m_updateArray = new EntityProperties[m_maxUpdatesPerFrame]; 216 m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
219 m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned); 217 m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned);
220 218
219 mesher = meshmerizer;
220 _taintedObjects = new List<TaintCallbackEntry>();
221
221 // Enable very detailed logging. 222 // Enable very detailed logging.
222 // By creating an empty logger when not logging, the log message invocation code 223 // By creating an empty logger when not logging, the log message invocation code
223 // can be left in and every call doesn't have to check for null. 224 // can be left in and every call doesn't have to check for null.
@@ -230,38 +231,43 @@ public class BSScene : PhysicsScene, IPhysicsParameters
230 PhysicsLogging = new Logging.LogWriter(); 231 PhysicsLogging = new Logging.LogWriter();
231 } 232 }
232 233
233 // Get the version of the DLL 234 // If Debug logging level, enable logging from the unmanaged code
234 // TODO: this doesn't work yet. Something wrong with marshaling the returned string. 235 m_DebugLogCallbackHandle = null;
235 // BulletSimVersion = BulletSimAPI.GetVersion();
236 // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion);
237
238 // if Debug, enable logging from the unmanaged code
239 if (m_log.IsDebugEnabled || PhysicsLogging.Enabled) 236 if (m_log.IsDebugEnabled || PhysicsLogging.Enabled)
240 { 237 {
241 m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader); 238 m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader);
242 if (PhysicsLogging.Enabled) 239 if (PhysicsLogging.Enabled)
240 // The handle is saved in a variable to make sure it doesn't get freed after this call
243 m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLoggerPhysLog); 241 m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLoggerPhysLog);
244 else 242 else
245 m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger); 243 m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger);
246 // the handle is saved in a variable to make sure it doesn't get freed after this call
247 BulletSimAPI.SetDebugLogCallback(m_DebugLogCallbackHandle);
248 } 244 }
249 245
250 _taintedObjects = new List<TaintCallbackEntry>(); 246 // Get the version of the DLL
247 // TODO: this doesn't work yet. Something wrong with marshaling the returned string.
248 // BulletSimVersion = BulletSimAPI.GetVersion();
249 // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion);
251 250
252 mesher = meshmerizer; 251 // The bounding box for the simulated world. The origin is 0,0,0 unless we're
253 // The bounding box for the simulated world 252 // a child in a mega-region.
253 // Turns out that Bullet really doesn't care about the extents of the simulated
254 // area. It tracks active objects no matter where they are.
254 Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 8192f); 255 Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 8192f);
255 256
256 // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader); 257 // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader);
257 m_worldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(), 258 WorldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(),
258 m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(), 259 m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(),
259 m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject()); 260 m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject(),
261 m_DebugLogCallbackHandle);
260 262
261 // Initialization to support the transition to a new API which puts most of the logic 263 // Initialization to support the transition to a new API which puts most of the logic
262 // into the C# code so it is easier to modify and add to. 264 // into the C# code so it is easier to modify and add to.
263 m_worldSim = new BulletSim(m_worldID, this, BulletSimAPI.GetSimHandle2(m_worldID)); 265 World = new BulletSim(WorldID, this, BulletSimAPI.GetSimHandle2(WorldID));
264 m_constraintCollection = new BSConstraintCollection(World); 266
267 Constraints = new BSConstraintCollection(World);
268
269 TerrainManager = new BSTerrainManager(this);
270 TerrainManager.CreateInitialGroundPlaneAndTerrain();
265 271
266 m_initialized = true; 272 m_initialized = true;
267 } 273 }
@@ -289,7 +295,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
289 m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-"); 295 m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-");
290 m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5); 296 m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
291 // Very detailed logging for vehicle debugging 297 // Very detailed logging for vehicle debugging
292 m_vehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false); 298 VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
293 299
294 // Do any replacements in the parameters 300 // Do any replacements in the parameters
295 m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName); 301 m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName);
@@ -324,6 +330,38 @@ public class BSScene : PhysicsScene, IPhysicsParameters
324 PhysicsLogging.Write("[BULLETS UNMANAGED]:" + msg); 330 PhysicsLogging.Write("[BULLETS UNMANAGED]:" + msg);
325 } 331 }
326 332
333 public override void Dispose()
334 {
335 // m_log.DebugFormat("{0}: Dispose()", LogHeader);
336
337 // make sure no stepping happens while we're deleting stuff
338 m_initialized = false;
339
340 TerrainManager.ReleaseGroundPlaneAndTerrain();
341
342 foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
343 {
344 kvp.Value.Destroy();
345 }
346 PhysObjects.Clear();
347
348 // Now that the prims are all cleaned up, there should be no constraints left
349 if (Constraints != null)
350 {
351 Constraints.Dispose();
352 Constraints = null;
353 }
354
355 // Anything left in the unmanaged code should be cleaned out
356 BulletSimAPI.Shutdown(WorldID);
357
358 // Not logging any more
359 PhysicsLogging.Close();
360 }
361 #endregion // Construction and Initialization
362
363 #region Prim and Avatar addition and removal
364
327 public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying) 365 public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
328 { 366 {
329 m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader); 367 m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
@@ -337,7 +375,13 @@ public class BSScene : PhysicsScene, IPhysicsParameters
337 if (!m_initialized) return null; 375 if (!m_initialized) return null;
338 376
339 BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying); 377 BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
340 lock (m_avatars) m_avatars.Add(localID, actor); 378 lock (PhysObjects) PhysObjects.Add(localID, actor);
379
380 // TODO: Remove kludge someday.
381 // We must generate a collision for avatars whether they collide or not.
382 // This is required by OpenSim to update avatar animations, etc.
383 lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Add(actor);
384
341 return actor; 385 return actor;
342 } 386 }
343 387
@@ -352,7 +396,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters
352 { 396 {
353 try 397 try
354 { 398 {
355 lock (m_avatars) m_avatars.Remove(actor.LocalID); 399 lock (PhysObjects) PhysObjects.Remove(actor.LocalID);
400 // Remove kludge someday
401 lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Remove(bsactor);
356 } 402 }
357 catch (Exception e) 403 catch (Exception e)
358 { 404 {
@@ -374,7 +420,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
374 // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID); 420 // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
375 try 421 try
376 { 422 {
377 lock (m_prims) m_prims.Remove(bsprim.LocalID); 423 lock (PhysObjects) PhysObjects.Remove(bsprim.LocalID);
378 } 424 }
379 catch (Exception e) 425 catch (Exception e)
380 { 426 {
@@ -399,7 +445,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
399 DetailLog("{0},AddPrimShape,call", localID); 445 DetailLog("{0},AddPrimShape,call", localID);
400 446
401 BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical); 447 BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical);
402 lock (m_prims) m_prims.Add(localID, prim); 448 lock (PhysObjects) PhysObjects.Add(localID, prim);
403 return prim; 449 return prim;
404 } 450 }
405 451
@@ -408,6 +454,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters
408 // information call is not needed. 454 // information call is not needed.
409 public override void AddPhysicsActorTaint(PhysicsActor prim) { } 455 public override void AddPhysicsActorTaint(PhysicsActor prim) { }
410 456
457 #endregion // Prim and Avatar addition and removal
458
459 #region Simulation
411 // Simulate one timestep 460 // Simulate one timestep
412 public override float Simulate(float timeStep) 461 public override float Simulate(float timeStep)
413 { 462 {
@@ -424,6 +473,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
424 int simulateStartTime = Util.EnvironmentTickCount(); 473 int simulateStartTime = Util.EnvironmentTickCount();
425 474
426 // update the prim states while we know the physics engine is not busy 475 // update the prim states while we know the physics engine is not busy
476 int numTaints = _taintedObjects.Count;
427 ProcessTaints(); 477 ProcessTaints();
428 478
429 // Some of the prims operate with special vehicle properties 479 // Some of the prims operate with special vehicle properties
@@ -435,14 +485,17 @@ public class BSScene : PhysicsScene, IPhysicsParameters
435 int numSubSteps = 0; 485 int numSubSteps = 0;
436 try 486 try
437 { 487 {
438 numSubSteps = BulletSimAPI.PhysicsStep(m_worldID, timeStep, m_maxSubSteps, m_fixedTimeStep, 488 numSubSteps = BulletSimAPI.PhysicsStep(WorldID, timeStep, m_maxSubSteps, m_fixedTimeStep,
439 out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); 489 out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr);
440 DetailLog("{0},Simulate,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); 490 DetailLog("{0},Simulate,call, nTaints= {1}, substeps={2}, updates={3}, colliders={4}",
491 DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
441 } 492 }
442 catch (Exception e) 493 catch (Exception e)
443 { 494 {
444 m_log.WarnFormat("{0},PhysicsStep Exception: substeps={1}, updates={2}, colliders={3}, e={4}", LogHeader, numSubSteps, updatedEntityCount, collidersCount, e); 495 m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}",
445 // DetailLog("{0},PhysicsStepException,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); 496 LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e);
497 DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}",
498 DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
446 updatedEntityCount = 0; 499 updatedEntityCount = 0;
447 collidersCount = 0; 500 collidersCount = 0;
448 } 501 }
@@ -451,7 +504,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
451 // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in 504 // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in
452 505
453 // Get a value for 'now' so all the collision and update routines don't have to get their own 506 // Get a value for 'now' so all the collision and update routines don't have to get their own
454 m_simulationNowTime = Util.EnvironmentTickCount(); 507 SimulationNowTime = Util.EnvironmentTickCount();
455 508
456 // If there were collisions, process them by sending the event to the prim. 509 // If there were collisions, process them by sending the event to the prim.
457 // Collisions must be processed before updates. 510 // Collisions must be processed before updates.
@@ -470,19 +523,16 @@ public class BSScene : PhysicsScene, IPhysicsParameters
470 523
471 // The above SendCollision's batch up the collisions on the objects. 524 // The above SendCollision's batch up the collisions on the objects.
472 // Now push the collisions into the simulator. 525 // Now push the collisions into the simulator.
473 foreach (BSPrim bsp in m_primsWithCollisions) 526 foreach (BSPhysObject bsp in m_objectsWithCollisions)
474 bsp.SendCollisions(); 527 bsp.SendCollisions();
475 m_primsWithCollisions.Clear(); 528 m_objectsWithCollisions.Clear();
476 529
477 // This is a kludge to get avatar movement updated. 530 // This is a kludge to get avatar movement updated.
478 // Don't send collisions only if there were collisions -- send everytime.
479 // ODE sends collisions even if there are none and this is used to update 531 // ODE sends collisions even if there are none and this is used to update
480 // avatar animations and stuff. 532 // avatar animations and stuff.
481 // foreach (BSCharacter bsc in m_avatarsWithCollisions) 533 foreach (BSPhysObject bpo in m_avatarsWithCollisions)
482 // bsc.SendCollisions(); 534 bpo.SendCollisions();
483 foreach (KeyValuePair<uint, BSCharacter> kvp in m_avatars) 535 // m_avatarsWithCollisions.Clear();
484 kvp.Value.SendCollisions();
485 m_avatarsWithCollisions.Clear();
486 536
487 // If any of the objects had updated properties, tell the object it has been changed by the physics engine 537 // If any of the objects had updated properties, tell the object it has been changed by the physics engine
488 if (updatedEntityCount > 0) 538 if (updatedEntityCount > 0)
@@ -490,16 +540,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters
490 for (int ii = 0; ii < updatedEntityCount; ii++) 540 for (int ii = 0; ii < updatedEntityCount; ii++)
491 { 541 {
492 EntityProperties entprop = m_updateArray[ii]; 542 EntityProperties entprop = m_updateArray[ii];
493 BSPrim prim; 543 BSPhysObject pobj;
494 if (m_prims.TryGetValue(entprop.ID, out prim)) 544 if (PhysObjects.TryGetValue(entprop.ID, out pobj))
495 {
496 prim.UpdateProperties(entprop);
497 continue;
498 }
499 BSCharacter actor;
500 if (m_avatars.TryGetValue(entprop.ID, out actor))
501 { 545 {
502 actor.UpdateProperties(entprop); 546 pobj.UpdateProperties(entprop);
503 continue; 547 continue;
504 } 548 }
505 } 549 }
@@ -529,58 +573,47 @@ public class BSScene : PhysicsScene, IPhysicsParameters
529 } 573 }
530 574
531 // Something has collided 575 // Something has collided
532 private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penitration) 576 private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
533 { 577 {
534 if (localID == TERRAIN_ID || localID == GROUNDPLANE_ID) 578 if (localID <= TerrainManager.HighestTerrainID)
535 { 579 {
536 return; // don't send collisions to the terrain 580 return; // don't send collisions to the terrain
537 } 581 }
538 582
583 BSPhysObject collider = PhysObjects[localID];
584 // TODO: as of this code, terrain was not in the physical object list.
585 // When BSTerrain is created and it will be in the list, we can remove
586 // the possibility that it's not there and just fetch the collidee.
587 BSPhysObject collidee = null;
588
539 ActorTypes type = ActorTypes.Prim; 589 ActorTypes type = ActorTypes.Prim;
540 if (collidingWith == TERRAIN_ID || collidingWith == GROUNDPLANE_ID) 590 if (collidingWith <= TerrainManager.HighestTerrainID)
591 {
541 type = ActorTypes.Ground; 592 type = ActorTypes.Ground;
542 else if (m_avatars.ContainsKey(collidingWith)) 593 }
543 type = ActorTypes.Agent; 594 else
595 {
596 collidee = PhysObjects[collidingWith];
597 if (collidee is BSCharacter)
598 type = ActorTypes.Agent;
599 }
544 600
545 // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); 601 // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
546 602
547 BSPrim prim; 603 collider.Collide(collidingWith, collidee, type, collidePoint, collideNormal, penetration);
548 if (m_prims.TryGetValue(localID, out prim)) { 604 m_objectsWithCollisions.Add(collider);
549 prim.Collide(collidingWith, type, collidePoint, collideNormal, penitration); 605
550 m_primsWithCollisions.Add(prim);
551 return;
552 }
553 BSCharacter actor;
554 if (m_avatars.TryGetValue(localID, out actor)) {
555 actor.Collide(collidingWith, type, collidePoint, collideNormal, penitration);
556 m_avatarsWithCollisions.Add(actor);
557 return;
558 }
559 return; 606 return;
560 } 607 }
561 608
562 public override void GetResults() { } 609 #endregion // Simulation
563 610
564 public override void SetTerrain(float[] heightMap) { 611 public override void GetResults() { }
565 m_heightMap = heightMap;
566 this.TaintedObject("BSScene.SetTerrain", delegate()
567 {
568 BulletSimAPI.SetHeightmap(m_worldID, m_heightMap);
569 });
570 }
571 612
572 // Someday we will have complex terrain with caves and tunnels 613 #region Terrain
573 // For the moment, it's flat and convex
574 public float GetTerrainHeightAtXYZ(Vector3 loc)
575 {
576 return GetTerrainHeightAtXY(loc.X, loc.Y);
577 }
578 614
579 public float GetTerrainHeightAtXY(float tX, float tY) 615 public override void SetTerrain(float[] heightMap) {
580 { 616 TerrainManager.SetTerrain(heightMap);
581 if (tX < 0 || tX >= Constants.RegionSize || tY < 0 || tY >= Constants.RegionSize)
582 return 30;
583 return m_heightMap[((int)tX) * Constants.RegionSize + ((int)tY)];
584 } 617 }
585 618
586 public override void SetWaterLevel(float baseheight) 619 public override void SetWaterLevel(float baseheight)
@@ -598,39 +631,27 @@ public class BSScene : PhysicsScene, IPhysicsParameters
598 // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader); 631 // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
599 } 632 }
600 633
601 public override void Dispose() 634 // Although no one seems to check this, I do support combining.
635 public override bool SupportsCombining()
602 { 636 {
603 // m_log.DebugFormat("{0}: Dispose()", LogHeader); 637 return TerrainManager.SupportsCombining();
604 638 }
605 // make sure no stepping happens while we're deleting stuff 639 // This call says I am a child to region zero in a mega-region. 'pScene' is that
606 m_initialized = false; 640 // of region zero, 'offset' is my offset from regions zero's origin, and
607 641 // 'extents' is the largest XY that is handled in my region.
608 foreach (KeyValuePair<uint, BSCharacter> kvp in m_avatars) 642 public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
609 { 643 {
610 kvp.Value.Destroy(); 644 TerrainManager.Combine(pScene, offset, extents);
611 } 645 }
612 m_avatars.Clear();
613
614 foreach (KeyValuePair<uint, BSPrim> kvp in m_prims)
615 {
616 kvp.Value.Destroy();
617 }
618 m_prims.Clear();
619
620 // Now that the prims are all cleaned up, there should be no constraints left
621 if (m_constraintCollection != null)
622 {
623 m_constraintCollection.Dispose();
624 m_constraintCollection = null;
625 }
626
627 // Anything left in the unmanaged code should be cleaned out
628 BulletSimAPI.Shutdown(WorldID);
629 646
630 // Not logging any more 647 // Unhook all the combining that I know about.
631 PhysicsLogging.Close(); 648 public override void UnCombine(PhysicsScene pScene)
649 {
650 TerrainManager.UnCombine(pScene);
632 } 651 }
633 652
653 #endregion // Terrain
654
634 public override Dictionary<uint, float> GetTopColliders() 655 public override Dictionary<uint, float> GetTopColliders()
635 { 656 {
636 return new Dictionary<uint, float>(); 657 return new Dictionary<uint, float>();
@@ -840,14 +861,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters
840 // no locking because only called when physics engine is not busy 861 // no locking because only called when physics engine is not busy
841 private void ProcessVehicles(float timeStep) 862 private void ProcessVehicles(float timeStep)
842 { 863 {
843 foreach (BSPrim prim in m_vehicles) 864 foreach (BSPhysObject pobj in m_vehicles)
844 { 865 {
845 prim.StepVehicle(timeStep); 866 pobj.StepVehicle(timeStep);
846 } 867 }
847 } 868 }
848 #endregion Vehicles 869 #endregion Vehicles
849 870
850 #region Parameters 871 #region INI and command line parameter processing
851 872
852 delegate void ParamUser(BSScene scene, IConfig conf, string paramName, float val); 873 delegate void ParamUser(BSScene scene, IConfig conf, string paramName, float val);
853 delegate float ParamGet(BSScene scene); 874 delegate float ParamGet(BSScene scene);
@@ -950,9 +971,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters
950 (s,p,l,v) => { s.m_maxUpdatesPerFrame = (int)v; } ), 971 (s,p,l,v) => { s.m_maxUpdatesPerFrame = (int)v; } ),
951 new ParameterDefn("MaxObjectMass", "Maximum object mass (10000.01)", 972 new ParameterDefn("MaxObjectMass", "Maximum object mass (10000.01)",
952 10000.01f, 973 10000.01f,
953 (s,cf,p,v) => { s.m_maximumObjectMass = cf.GetFloat(p, v); }, 974 (s,cf,p,v) => { s.MaximumObjectMass = cf.GetFloat(p, v); },
954 (s) => { return (float)s.m_maximumObjectMass; }, 975 (s) => { return (float)s.MaximumObjectMass; },
955 (s,p,l,v) => { s.m_maximumObjectMass = v; } ), 976 (s,p,l,v) => { s.MaximumObjectMass = v; } ),
956 977
957 new ParameterDefn("PID_D", "Derivitive factor for motion smoothing", 978 new ParameterDefn("PID_D", "Derivitive factor for motion smoothing",
958 2200f, 979 2200f,
@@ -996,42 +1017,42 @@ public class BSScene : PhysicsScene, IPhysicsParameters
996 0f, 1017 0f,
997 (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); }, 1018 (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); },
998 (s) => { return s.m_params[0].linearDamping; }, 1019 (s) => { return s.m_params[0].linearDamping; },
999 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].linearDamping, p, l, v); } ), 1020 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); } ),
1000 new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)", 1021 new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)",
1001 0f, 1022 0f,
1002 (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); }, 1023 (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); },
1003 (s) => { return s.m_params[0].angularDamping; }, 1024 (s) => { return s.m_params[0].angularDamping; },
1004 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].angularDamping, p, l, v); } ), 1025 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); } ),
1005 new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static", 1026 new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static",
1006 0.2f, 1027 0.2f,
1007 (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); }, 1028 (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); },
1008 (s) => { return s.m_params[0].deactivationTime; }, 1029 (s) => { return s.m_params[0].deactivationTime; },
1009 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].deactivationTime, p, l, v); } ), 1030 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].deactivationTime, p, l, v); } ),
1010 new ParameterDefn("LinearSleepingThreshold", "Seconds to measure linear movement before considering static", 1031 new ParameterDefn("LinearSleepingThreshold", "Seconds to measure linear movement before considering static",
1011 0.8f, 1032 0.8f,
1012 (s,cf,p,v) => { s.m_params[0].linearSleepingThreshold = cf.GetFloat(p, v); }, 1033 (s,cf,p,v) => { s.m_params[0].linearSleepingThreshold = cf.GetFloat(p, v); },
1013 (s) => { return s.m_params[0].linearSleepingThreshold; }, 1034 (s) => { return s.m_params[0].linearSleepingThreshold; },
1014 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].linearSleepingThreshold, p, l, v); } ), 1035 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearSleepingThreshold, p, l, v); } ),
1015 new ParameterDefn("AngularSleepingThreshold", "Seconds to measure angular movement before considering static", 1036 new ParameterDefn("AngularSleepingThreshold", "Seconds to measure angular movement before considering static",
1016 1.0f, 1037 1.0f,
1017 (s,cf,p,v) => { s.m_params[0].angularSleepingThreshold = cf.GetFloat(p, v); }, 1038 (s,cf,p,v) => { s.m_params[0].angularSleepingThreshold = cf.GetFloat(p, v); },
1018 (s) => { return s.m_params[0].angularSleepingThreshold; }, 1039 (s) => { return s.m_params[0].angularSleepingThreshold; },
1019 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].angularSleepingThreshold, p, l, v); } ), 1040 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularSleepingThreshold, p, l, v); } ),
1020 new ParameterDefn("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" , 1041 new ParameterDefn("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" ,
1021 0f, // set to zero to disable 1042 0f, // set to zero to disable
1022 (s,cf,p,v) => { s.m_params[0].ccdMotionThreshold = cf.GetFloat(p, v); }, 1043 (s,cf,p,v) => { s.m_params[0].ccdMotionThreshold = cf.GetFloat(p, v); },
1023 (s) => { return s.m_params[0].ccdMotionThreshold; }, 1044 (s) => { return s.m_params[0].ccdMotionThreshold; },
1024 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].ccdMotionThreshold, p, l, v); } ), 1045 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdMotionThreshold, p, l, v); } ),
1025 new ParameterDefn("CcdSweptSphereRadius", "Continuious collision detection test radius" , 1046 new ParameterDefn("CcdSweptSphereRadius", "Continuious collision detection test radius" ,
1026 0f, 1047 0f,
1027 (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); }, 1048 (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); },
1028 (s) => { return s.m_params[0].ccdSweptSphereRadius; }, 1049 (s) => { return s.m_params[0].ccdSweptSphereRadius; },
1029 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); } ), 1050 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); } ),
1030 new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" , 1051 new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" ,
1031 0.1f, 1052 0.1f,
1032 (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); }, 1053 (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); },
1033 (s) => { return s.m_params[0].contactProcessingThreshold; }, 1054 (s) => { return s.m_params[0].contactProcessingThreshold; },
1034 (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].contactProcessingThreshold, p, l, v); } ), 1055 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); } ),
1035 1056
1036 new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" , 1057 new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" ,
1037 0.5f, 1058 0.5f,
@@ -1049,35 +1070,35 @@ public class BSScene : PhysicsScene, IPhysicsParameters
1049 (s) => { return s.m_params[0].terrainRestitution; }, 1070 (s) => { return s.m_params[0].terrainRestitution; },
1050 (s,p,l,v) => { s.m_params[0].terrainRestitution = v; s.TaintedUpdateParameter(p,l,v); } ), 1071 (s,p,l,v) => { s.m_params[0].terrainRestitution = v; s.TaintedUpdateParameter(p,l,v); } ),
1051 new ParameterDefn("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.", 1072 new ParameterDefn("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.",
1052 0.5f, 1073 0.2f,
1053 (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); }, 1074 (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); },
1054 (s) => { return s.m_params[0].avatarFriction; }, 1075 (s) => { return s.m_params[0].avatarFriction; },
1055 (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarFriction, p, l, v); } ), 1076 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarFriction, p, l, v); } ),
1056 new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.", 1077 new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.",
1057 60f, 1078 60f,
1058 (s,cf,p,v) => { s.m_params[0].avatarDensity = cf.GetFloat(p, v); }, 1079 (s,cf,p,v) => { s.m_params[0].avatarDensity = cf.GetFloat(p, v); },
1059 (s) => { return s.m_params[0].avatarDensity; }, 1080 (s) => { return s.m_params[0].avatarDensity; },
1060 (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarDensity, p, l, v); } ), 1081 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarDensity, p, l, v); } ),
1061 new ParameterDefn("AvatarRestitution", "Bouncyness. Changed on avatar recreation.", 1082 new ParameterDefn("AvatarRestitution", "Bouncyness. Changed on avatar recreation.",
1062 0f, 1083 0f,
1063 (s,cf,p,v) => { s.m_params[0].avatarRestitution = cf.GetFloat(p, v); }, 1084 (s,cf,p,v) => { s.m_params[0].avatarRestitution = cf.GetFloat(p, v); },
1064 (s) => { return s.m_params[0].avatarRestitution; }, 1085 (s) => { return s.m_params[0].avatarRestitution; },
1065 (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarRestitution, p, l, v); } ), 1086 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarRestitution, p, l, v); } ),
1066 new ParameterDefn("AvatarCapsuleRadius", "Radius of space around an avatar", 1087 new ParameterDefn("AvatarCapsuleRadius", "Radius of space around an avatar",
1067 0.37f, 1088 0.37f,
1068 (s,cf,p,v) => { s.m_params[0].avatarCapsuleRadius = cf.GetFloat(p, v); }, 1089 (s,cf,p,v) => { s.m_params[0].avatarCapsuleRadius = cf.GetFloat(p, v); },
1069 (s) => { return s.m_params[0].avatarCapsuleRadius; }, 1090 (s) => { return s.m_params[0].avatarCapsuleRadius; },
1070 (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarCapsuleRadius, p, l, v); } ), 1091 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleRadius, p, l, v); } ),
1071 new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar", 1092 new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar",
1072 1.5f, 1093 1.5f,
1073 (s,cf,p,v) => { s.m_params[0].avatarCapsuleHeight = cf.GetFloat(p, v); }, 1094 (s,cf,p,v) => { s.m_params[0].avatarCapsuleHeight = cf.GetFloat(p, v); },
1074 (s) => { return s.m_params[0].avatarCapsuleHeight; }, 1095 (s) => { return s.m_params[0].avatarCapsuleHeight; },
1075 (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ), 1096 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ),
1076 new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", 1097 new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions",
1077 0.1f, 1098 0.1f,
1078 (s,cf,p,v) => { s.m_params[0].avatarContactProcessingThreshold = cf.GetFloat(p, v); }, 1099 (s,cf,p,v) => { s.m_params[0].avatarContactProcessingThreshold = cf.GetFloat(p, v); },
1079 (s) => { return s.m_params[0].avatarContactProcessingThreshold; }, 1100 (s) => { return s.m_params[0].avatarContactProcessingThreshold; },
1080 (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarContactProcessingThreshold, p, l, v); } ), 1101 (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarContactProcessingThreshold, p, l, v); } ),
1081 1102
1082 1103
1083 new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)", 1104 new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)",
@@ -1214,6 +1235,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters
1214 1235
1215 private PhysParameterEntry[] SettableParameters = new PhysParameterEntry[1]; 1236 private PhysParameterEntry[] SettableParameters = new PhysParameterEntry[1];
1216 1237
1238 // This creates an array in the correct format for returning the list of
1239 // parameters. This is used by the 'list' option of the 'physics' command.
1217 private void BuildParameterTable() 1240 private void BuildParameterTable()
1218 { 1241 {
1219 if (SettableParameters.Length < ParameterDefinitions.Length) 1242 if (SettableParameters.Length < ParameterDefinitions.Length)
@@ -1264,18 +1287,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters
1264 } 1287 }
1265 1288
1266 // check to see if we are updating a parameter for a particular or all of the prims 1289 // check to see if we are updating a parameter for a particular or all of the prims
1267 protected void UpdateParameterPrims(ref float loc, string parm, uint localID, float val) 1290 protected void UpdateParameterObject(ref float loc, string parm, uint localID, float val)
1268 {
1269 List<uint> operateOn;
1270 lock (m_prims) operateOn = new List<uint>(m_prims.Keys);
1271 UpdateParameterSet(operateOn, ref loc, parm, localID, val);
1272 }
1273
1274 // check to see if we are updating a parameter for a particular or all of the avatars
1275 protected void UpdateParameterAvatars(ref float loc, string parm, uint localID, float val)
1276 { 1291 {
1277 List<uint> operateOn; 1292 List<uint> operateOn;
1278 lock (m_avatars) operateOn = new List<uint>(m_avatars.Keys); 1293 lock (PhysObjects) operateOn = new List<uint>(PhysObjects.Keys);
1279 UpdateParameterSet(operateOn, ref loc, parm, localID, val); 1294 UpdateParameterSet(operateOn, ref loc, parm, localID, val);
1280 } 1295 }
1281 1296
@@ -1298,7 +1313,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
1298 TaintedObject("BSScene.UpdateParameterSet", delegate() { 1313 TaintedObject("BSScene.UpdateParameterSet", delegate() {
1299 foreach (uint lID in objectIDs) 1314 foreach (uint lID in objectIDs)
1300 { 1315 {
1301 BulletSimAPI.UpdateParameter(m_worldID, lID, xparm, xval); 1316 BulletSimAPI.UpdateParameter(WorldID, lID, xparm, xval);
1302 } 1317 }
1303 }); 1318 });
1304 break; 1319 break;
@@ -1316,7 +1331,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters
1316 string xparm = parm.ToLower(); 1331 string xparm = parm.ToLower();
1317 float xval = val; 1332 float xval = val;
1318 TaintedObject("BSScene.TaintedUpdateParameter", delegate() { 1333 TaintedObject("BSScene.TaintedUpdateParameter", delegate() {
1319 BulletSimAPI.UpdateParameter(m_worldID, xlocalID, xparm, xval); 1334 BulletSimAPI.UpdateParameter(WorldID, xlocalID, xparm, xval);
1320 }); 1335 });
1321 } 1336 }
1322 1337
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs
new file mode 100755
index 0000000..ab45f8f
--- /dev/null
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs
@@ -0,0 +1,464 @@
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.Text;
30
31using OpenSim.Framework;
32using OpenSim.Region.Framework;
33using OpenSim.Region.CoreModules;
34using OpenSim.Region.Physics.Manager;
35
36using Nini.Config;
37using log4net;
38
39using OpenMetaverse;
40
41namespace OpenSim.Region.Physics.BulletSPlugin
42{
43public class BSTerrainManager
44{
45 static string LogHeader = "[BULLETSIM TERRAIN MANAGER]";
46
47 // These height values are fractional so the odd values will be
48 // noticable when debugging.
49 public const float HEIGHT_INITIALIZATION = 24.987f;
50 public const float HEIGHT_INITIAL_LASTHEIGHT = 24.876f;
51 public const float HEIGHT_GETHEIGHT_RET = 24.765f;
52
53 // If the min and max height are equal, we reduce the min by this
54 // amount to make sure that a bounding box is built for the terrain.
55 public const float HEIGHT_EQUAL_FUDGE = 0.2f;
56
57 public const float TERRAIN_COLLISION_MARGIN = 0.0f;
58
59 // Until the whole simulator is changed to pass us the region size, we rely on constants.
60 public Vector3 DefaultRegionSize = new Vector3(Constants.RegionSize, Constants.RegionSize, 0f);
61
62 // The scene that I am part of
63 private BSScene m_physicsScene;
64
65 // The ground plane created to keep thing from falling to infinity.
66 private BulletBody m_groundPlane;
67
68 // If doing mega-regions, if we're region zero we will be managing multiple
69 // region terrains since region zero does the physics for the whole mega-region.
70 private Dictionary<Vector2, BulletHeightMapInfo> m_heightMaps;
71
72 // True of the terrain has been modified.
73 // Used to force recalculation of terrain height after terrain has been modified
74 private bool m_terrainModified;
75
76 // If we are doing mega-regions, terrains are added from TERRAIN_ID to m_terrainCount.
77 // This is incremented before assigning to new region so it is the last ID allocated.
78 private uint m_terrainCount = BSScene.CHILDTERRAIN_ID - 1;
79 public uint HighestTerrainID { get {return m_terrainCount; } }
80
81 // If doing mega-regions, this holds our offset from region zero of
82 // the mega-regions. "parentScene" points to the PhysicsScene of region zero.
83 private Vector3 m_worldOffset;
84 // If the parent region (region 0), this is the extent of the combined regions
85 // relative to the origin of region zero
86 private Vector3 m_worldMax;
87 private PhysicsScene m_parentScene;
88
89 public BSTerrainManager(BSScene physicsScene)
90 {
91 m_physicsScene = physicsScene;
92 m_heightMaps = new Dictionary<Vector2,BulletHeightMapInfo>();
93 m_terrainModified = false;
94
95 // Assume one region of default size
96 m_worldOffset = Vector3.Zero;
97 m_worldMax = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, 4096f);
98 m_parentScene = null;
99 }
100
101 // Create the initial instance of terrain and the underlying ground plane.
102 // The objects are allocated in the unmanaged space and the pointers are tracked
103 // by the managed code.
104 // The terrains and the groundPlane are not added to the list of PhysObjects.
105 // This is called from the initialization routine so we presume it is
106 // safe to call Bullet in real time. We hope no one is moving prims around yet.
107 public void CreateInitialGroundPlaneAndTerrain()
108 {
109 // The ground plane is here to catch things that are trying to drop to negative infinity
110 BulletShape groundPlaneShape = new BulletShape(BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN));
111 m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID,
112 BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.Ptr, Vector3.Zero, Quaternion.Identity));
113 BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr);
114
115 Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE);
116 Vector3 maxTerrainCoords = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, HEIGHT_INITIALIZATION);
117 int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y;
118 float[] initialMap = new float[totalHeights];
119 for (int ii = 0; ii < totalHeights; ii++)
120 {
121 initialMap[ii] = HEIGHT_INITIALIZATION;
122 }
123 UpdateOrCreateTerrain(BSScene.TERRAIN_ID, initialMap, minTerrainCoords, maxTerrainCoords, true);
124 }
125
126 // Release all the terrain structures we might have allocated
127 public void ReleaseGroundPlaneAndTerrain()
128 {
129 if (m_groundPlane.Ptr != IntPtr.Zero)
130 {
131 if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr))
132 {
133 BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, m_groundPlane.Ptr);
134 }
135 m_groundPlane.Ptr = IntPtr.Zero;
136 }
137
138 ReleaseTerrain();
139 }
140
141 // Release all the terrain we have allocated
142 public void ReleaseTerrain()
143 {
144 foreach (KeyValuePair<Vector2, BulletHeightMapInfo> kvp in m_heightMaps)
145 {
146 if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, kvp.Value.terrainBody.Ptr))
147 {
148 BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, kvp.Value.terrainBody.Ptr);
149 BulletSimAPI.ReleaseHeightMapInfo2(kvp.Value.Ptr);
150 }
151 }
152 m_heightMaps.Clear();
153 }
154
155 // The simulator wants to set a new heightmap for the terrain.
156 public void SetTerrain(float[] heightMap) {
157 if (m_worldOffset != Vector3.Zero && m_parentScene != null)
158 {
159 // If a child of a mega-region, we shouldn't have any terrain allocated for us
160 ReleaseGroundPlaneAndTerrain();
161 // If doing the mega-prim stuff and we are the child of the zero region,
162 // the terrain is added to our parent
163 if (m_parentScene is BSScene)
164 {
165 DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}",
166 BSScene.DetailLogZero, m_worldOffset, m_worldMax);
167 ((BSScene)m_parentScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID,
168 heightMap, m_worldOffset, m_worldOffset+DefaultRegionSize, false);
169 }
170 }
171 else
172 {
173 // If not doing the mega-prim thing, just change the terrain
174 DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero);
175
176 UpdateOrCreateTerrain(BSScene.TERRAIN_ID, heightMap, m_worldOffset, m_worldOffset+DefaultRegionSize, false);
177 }
178 }
179
180 // If called with no mapInfo for the terrain, this will create a new mapInfo and terrain
181 // based on the passed information. The 'id' should be either the terrain id or
182 // BSScene.CHILDTERRAIN_ID. If the latter, a new child terrain ID will be allocated and used.
183 // The latter feature is for creating child terrains for mega-regions.
184 // If called with a mapInfo in m_heightMaps but the terrain has no body yet (mapInfo.terrainBody.Ptr == 0)
185 // then a new body and shape is created and the mapInfo is filled.
186 // This call is used for doing the initial terrain creation.
187 // If called with a mapInfo in m_heightMaps and there is an existing terrain body, a new
188 // terrain shape is created and added to the body.
189 // This call is most often used to update the heightMap and parameters of the terrain.
190 // The 'doNow' boolean says whether to do all the unmanaged activities right now (like when
191 // calling this routine from initialization or taint-time routines) or whether to delay
192 // all the unmanaged activities to taint-time.
193 private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool doNow)
194 {
195 DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},doNow={3}",
196 BSScene.DetailLogZero, minCoords, maxCoords, doNow);
197
198 float minZ = float.MaxValue;
199 float maxZ = float.MinValue;
200 Vector2 terrainRegionBase = new Vector2(minCoords.X, minCoords.Y);
201
202 int heightMapSize = heightMap.Length;
203 for (int ii = 0; ii < heightMapSize; ii++)
204 {
205 float height = heightMap[ii];
206 if (height < minZ) minZ = height;
207 if (height > maxZ) maxZ = height;
208 }
209
210 // The shape of the terrain is from its base to its extents.
211 minCoords.Z = minZ;
212 maxCoords.Z = maxZ;
213
214 BulletHeightMapInfo mapInfo;
215 if (m_heightMaps.TryGetValue(terrainRegionBase, out mapInfo))
216 {
217 // If this is terrain we know about, it's easy to update
218
219 mapInfo.heightMap = heightMap;
220 mapInfo.minCoords = minCoords;
221 mapInfo.maxCoords = maxCoords;
222 mapInfo.minZ = minZ;
223 mapInfo.maxZ = maxZ;
224 mapInfo.sizeX = maxCoords.X - minCoords.X;
225 mapInfo.sizeY = maxCoords.Y - minCoords.Y;
226 DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,call,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}",
227 BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY);
228
229 BSScene.TaintCallback rebuildOperation = delegate()
230 {
231 if (m_parentScene != null)
232 {
233 // It's possible that Combine() was called after this code was queued.
234 // If we are a child of combined regions, we don't create any terrain for us.
235 DetailLog("{0},UpdateOrCreateTerrain:AmACombineChild,taint", BSScene.DetailLogZero);
236
237 // Get rid of any terrain that may have been allocated for us.
238 ReleaseGroundPlaneAndTerrain();
239
240 // I hate doing this, but just bail
241 return;
242 }
243
244 if (mapInfo.terrainBody.Ptr != IntPtr.Zero)
245 {
246 // Updating an existing terrain.
247 DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,taint,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}",
248 BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY);
249
250 // Remove from the dynamics world because we're going to mangle this object
251 BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr);
252
253 // Get rid of the old terrain
254 BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr);
255 BulletSimAPI.ReleaseHeightMapInfo2(mapInfo.Ptr);
256 mapInfo.Ptr = IntPtr.Zero;
257
258 /*
259 // NOTE: This routine is half here because I can't get the terrain shape replacement
260 // to work. In the short term, the above three lines completely delete the old
261 // terrain and the code below recreates one from scratch.
262 // Hopefully the Bullet community will help me out on this one.
263
264 // First, release the old collision shape (there is only one terrain)
265 BulletSimAPI.DeleteCollisionShape2(m_physicsScene.World.Ptr, mapInfo.terrainShape.Ptr);
266
267 // Fill the existing height map info with the new location and size information
268 BulletSimAPI.FillHeightMapInfo2(m_physicsScene.World.Ptr, mapInfo.Ptr, mapInfo.ID,
269 mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN);
270
271 // Create a terrain shape based on the new info
272 mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr));
273
274 // Stuff the shape into the existing terrain body
275 BulletSimAPI.SetBodyShape2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr, mapInfo.terrainShape.Ptr);
276 */
277 }
278 // else
279 {
280 // Creating a new terrain.
281 DetailLog("{0},UpdateOrCreateTerrain:CreateNewTerrain,taint,baseX={1},baseY={2},minZ={3},maxZ={4}",
282 BSScene.DetailLogZero, mapInfo.minCoords.X, mapInfo.minCoords.Y, minZ, maxZ);
283
284 mapInfo.ID = id;
285 mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(m_physicsScene.World.Ptr, mapInfo.ID,
286 mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN);
287
288 // The terrain object initial position is at the center of the object
289 Vector3 centerPos;
290 centerPos.X = minCoords.X + (mapInfo.sizeX / 2f);
291 centerPos.Y = minCoords.Y + (mapInfo.sizeY / 2f);
292 centerPos.Z = minZ + ((maxZ - minZ) / 2f);
293
294 // Create the terrain shape from the mapInfo
295 mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr));
296
297 mapInfo.terrainBody = new BulletBody(mapInfo.ID,
298 BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.Ptr,
299 centerPos, Quaternion.Identity));
300 }
301
302 // Make sure the entry is in the heightmap table
303 m_heightMaps[terrainRegionBase] = mapInfo;
304
305 // Set current terrain attributes
306 BulletSimAPI.SetFriction2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainFriction);
307 BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainHitFraction);
308 BulletSimAPI.SetRestitution2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainRestitution);
309 BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.Ptr, CollisionFlags.CF_STATIC_OBJECT);
310
311 BulletSimAPI.SetMassProps2(mapInfo.terrainBody.Ptr, 0f, Vector3.Zero);
312 BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.Ptr);
313
314 // Return the new terrain to the world of physical objects
315 BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr);
316
317 // redo its bounding box now that it is in the world
318 BulletSimAPI.UpdateSingleAabb2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr);
319
320 // Make sure the new shape is processed.
321 BulletSimAPI.Activate2(mapInfo.terrainBody.Ptr, true);
322 };
323
324 // There is the option to do the changes now (we're already in 'taint time'), or
325 // to do the Bullet operations later.
326 if (doNow)
327 rebuildOperation();
328 else
329 m_physicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation);
330 }
331 else
332 {
333 // We don't know about this terrain so either we are creating a new terrain or
334 // our mega-prim child is giving us a new terrain to add to the phys world
335
336 // if this is a child terrain, calculate a unique terrain id
337 uint newTerrainID = id;
338 if (newTerrainID >= BSScene.CHILDTERRAIN_ID)
339 newTerrainID = ++m_terrainCount;
340
341 float[] heightMapX = heightMap;
342 Vector3 minCoordsX = minCoords;
343 Vector3 maxCoordsX = maxCoords;
344
345 DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,call,id={1}, minC={2}, maxC={3}",
346 BSScene.DetailLogZero, newTerrainID, minCoords, minCoords);
347
348 // Code that must happen at taint-time
349 BSScene.TaintCallback createOperation = delegate()
350 {
351 DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y);
352 // Create a new mapInfo that will be filled with the new info
353 mapInfo = new BulletHeightMapInfo(id, heightMapX,
354 BulletSimAPI.CreateHeightMapInfo2(m_physicsScene.World.Ptr, newTerrainID,
355 minCoordsX, maxCoordsX, heightMapX, TERRAIN_COLLISION_MARGIN));
356 // Put the unfilled heightmap info into the collection of same
357 m_heightMaps.Add(terrainRegionBase, mapInfo);
358 // Build the terrain
359 UpdateOrCreateTerrain(newTerrainID, heightMap, minCoords, maxCoords, true);
360 };
361
362 // If already in taint-time, just call Bullet. Otherwise queue the operations for the safe time.
363 if (doNow)
364 createOperation();
365 else
366 m_physicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation);
367 }
368 }
369
370 // Someday we will have complex terrain with caves and tunnels
371 public float GetTerrainHeightAtXYZ(Vector3 loc)
372 {
373 // For the moment, it's flat and convex
374 return GetTerrainHeightAtXY(loc.X, loc.Y);
375 }
376
377 // Given an X and Y, find the height of the terrain.
378 // Since we could be handling multiple terrains for a mega-region,
379 // the base of the region is calcuated assuming all regions are
380 // the same size and that is the default.
381 // Once the heightMapInfo is found, we have all the information to
382 // compute the offset into the array.
383 private float lastHeightTX = 999999f;
384 private float lastHeightTY = 999999f;
385 private float lastHeight = HEIGHT_INITIAL_LASTHEIGHT;
386 public float GetTerrainHeightAtXY(float tX, float tY)
387 {
388 // You'd be surprized at the number of times this routine is called
389 // with the same parameters as last time.
390 if (!m_terrainModified && lastHeightTX == tX && lastHeightTY == tY)
391 return lastHeight;
392
393 lastHeightTX = tX;
394 lastHeightTY = tY;
395 float ret = HEIGHT_GETHEIGHT_RET;
396
397 int offsetX = ((int)(tX / (int)DefaultRegionSize.X)) * (int)DefaultRegionSize.X;
398 int offsetY = ((int)(tY / (int)DefaultRegionSize.Y)) * (int)DefaultRegionSize.Y;
399 Vector2 terrainBaseXY = new Vector2(offsetX, offsetY);
400
401 BulletHeightMapInfo mapInfo;
402 if (m_heightMaps.TryGetValue(terrainBaseXY, out mapInfo))
403 {
404 float regionX = tX - offsetX;
405 float regionY = tY - offsetY;
406 if (regionX > mapInfo.sizeX) regionX = 0;
407 if (regionY > mapInfo.sizeY) regionY = 0;
408 int mapIndex = (int)regionY * (int)mapInfo.sizeY + (int)regionX;
409 ret = mapInfo.heightMap[mapIndex];
410 m_terrainModified = false;
411 DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXY,bX={1},baseY={2},szX={3},szY={4},regX={5},regY={6},index={7},ht={8}",
412 BSScene.DetailLogZero, offsetX, offsetY, mapInfo.sizeX, mapInfo.sizeY, regionX, regionY, mapIndex, ret);
413 }
414 else
415 {
416 m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}",
417 LogHeader, m_physicsScene.RegionName, tX, tY);
418 }
419 lastHeight = ret;
420 return ret;
421 }
422
423 // Although no one seems to check this, I do support combining.
424 public bool SupportsCombining()
425 {
426 return true;
427 }
428
429 // This routine is called two ways:
430 // One with 'offset' and 'pScene' zero and null but 'extents' giving the maximum
431 // extent of the combined regions. This is to inform the parent of the size
432 // of the combined regions.
433 // and one with 'offset' as the offset of the child region to the base region,
434 // 'pScene' pointing to the parent and 'extents' of zero. This informs the
435 // child of its relative base and new parent.
436 public void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
437 {
438 m_worldOffset = offset;
439 m_worldMax = extents;
440 m_parentScene = pScene;
441 if (pScene != null)
442 {
443 // We are a child.
444 // We want m_worldMax to be the highest coordinate of our piece of terrain.
445 m_worldMax = offset + DefaultRegionSize;
446 }
447 DetailLog("{0},BSTerrainManager.Combine,offset={1},extents={2},wOffset={3},wMax={4}",
448 BSScene.DetailLogZero, offset, extents, m_worldOffset, m_worldMax);
449 }
450
451 // Unhook all the combining that I know about.
452 public void UnCombine(PhysicsScene pScene)
453 {
454 // Just like ODE, for the moment a NOP
455 DetailLog("{0},BSTerrainManager.UnCombine", BSScene.DetailLogZero);
456 }
457
458
459 private void DetailLog(string msg, params Object[] args)
460 {
461 m_physicsScene.PhysicsLogging.Write(msg, args);
462 }
463}
464}
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs
index 504bd3c..a0bad3a 100644
--- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs
@@ -33,15 +33,25 @@ using OpenMetaverse;
33namespace OpenSim.Region.Physics.BulletSPlugin { 33namespace OpenSim.Region.Physics.BulletSPlugin {
34 34
35// Classes to allow some type checking for the API 35// Classes to allow some type checking for the API
36// These hold pointers to allocated objects in the unmanaged space.
37
38// The physics engine controller class created at initialization
36public struct BulletSim 39public struct BulletSim
37{ 40{
38 public BulletSim(uint id, BSScene bss, IntPtr xx) { ID = id; scene = bss; Ptr = xx; } 41 public BulletSim(uint worldId, BSScene bss, IntPtr xx) { worldID = worldId; scene = bss; Ptr = xx; }
39 public uint ID; 42 public uint worldID;
40 // The scene is only in here so very low level routines have a handle to print debug/error messages 43 // The scene is only in here so very low level routines have a handle to print debug/error messages
41 public BSScene scene; 44 public BSScene scene;
42 public IntPtr Ptr; 45 public IntPtr Ptr;
43} 46}
44 47
48public struct BulletShape
49{
50 public BulletShape(IntPtr xx) { Ptr = xx; }
51 public IntPtr Ptr;
52}
53
54// An allocated Bullet btRigidBody
45public struct BulletBody 55public struct BulletBody
46{ 56{
47 public BulletBody(uint id, IntPtr xx) { ID = id; Ptr = xx; } 57 public BulletBody(uint id, IntPtr xx) { ID = id; Ptr = xx; }
@@ -49,12 +59,41 @@ public struct BulletBody
49 public uint ID; 59 public uint ID;
50} 60}
51 61
62// An allocated Bullet btConstraint
52public struct BulletConstraint 63public struct BulletConstraint
53{ 64{
54 public BulletConstraint(IntPtr xx) { Ptr = xx; } 65 public BulletConstraint(IntPtr xx) { Ptr = xx; }
55 public IntPtr Ptr; 66 public IntPtr Ptr;
56} 67}
57 68
69// An allocated HeightMapThing which hold various heightmap info
70// Made a class rather than a struct so there would be only one
71// instance of this and C# will pass around pointers rather
72// than making copies.
73public class BulletHeightMapInfo
74{
75 public BulletHeightMapInfo(uint id, float[] hm, IntPtr xx) {
76 ID = id;
77 Ptr = xx;
78 heightMap = hm;
79 terrainRegionBase = new Vector2(0f, 0f);
80 minCoords = new Vector3(100f, 100f, 25f);
81 maxCoords = new Vector3(101f, 101f, 26f);
82 minZ = maxZ = 0f;
83 sizeX = sizeY = 256f;
84 }
85 public uint ID;
86 public IntPtr Ptr;
87 public float[] heightMap;
88 public Vector2 terrainRegionBase;
89 public Vector3 minCoords;
90 public Vector3 maxCoords;
91 public float sizeX, sizeY;
92 public float minZ, maxZ;
93 public BulletShape terrainShape;
94 public BulletBody terrainBody;
95}
96
58// =============================================================================== 97// ===============================================================================
59[StructLayout(LayoutKind.Sequential)] 98[StructLayout(LayoutKind.Sequential)]
60public struct ConvexHull 99public struct ConvexHull
@@ -221,6 +260,10 @@ public enum ConstraintParamAxis : int
221// =============================================================================== 260// ===============================================================================
222static class BulletSimAPI { 261static class BulletSimAPI {
223 262
263// Link back to the managed code for outputting log messages
264[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
265public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg);
266
224[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 267[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
225[return: MarshalAs(UnmanagedType.LPStr)] 268[return: MarshalAs(UnmanagedType.LPStr)]
226public static extern string GetVersion(); 269public static extern string GetVersion();
@@ -228,7 +271,11 @@ public static extern string GetVersion();
228[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 271[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
229public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, 272public static extern uint Initialize(Vector3 maxPosition, IntPtr parms,
230 int maxCollisions, IntPtr collisionArray, 273 int maxCollisions, IntPtr collisionArray,
231 int maxUpdates, IntPtr updateArray); 274 int maxUpdates, IntPtr updateArray,
275 DebugLogCallback logRoutine);
276
277[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
278public static extern void CreateInitialGroundPlaneAndTerrain(uint worldID);
232 279
233[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 280[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
234public static extern void SetHeightmap(uint worldID, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); 281public static extern void SetHeightmap(uint worldID, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap);
@@ -342,8 +389,6 @@ public static extern Vector3 RecoverFromPenetration(uint worldID, uint id);
342public static extern void DumpBulletStatistics(); 389public static extern void DumpBulletStatistics();
343 390
344// Log a debug message 391// Log a debug message
345[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
346public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg);
347[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 392[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
348public static extern void SetDebugLogCallback(DebugLogCallback callback); 393public static extern void SetDebugLogCallback(DebugLogCallback callback);
349 394
@@ -377,7 +422,7 @@ public static extern IntPtr Initialize2(Vector3 maxPosition, IntPtr parms,
377public static extern bool UpdateParameter2(IntPtr world, uint localID, String parm, float value); 422public static extern bool UpdateParameter2(IntPtr world, uint localID, String parm, float value);
378 423
379[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 424[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
380public static extern void SetHeightmap2(IntPtr world, float[] heightmap); 425public static extern void SetHeightMap2(IntPtr world, float[] heightmap);
381 426
382[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 427[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
383public static extern void Shutdown2(IntPtr sim); 428public static extern void Shutdown2(IntPtr sim);
@@ -392,24 +437,54 @@ public static extern int PhysicsStep2(IntPtr world, float timeStep, int maxSubSt
392[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 437[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
393public static extern bool PushUpdate2(IntPtr obj); 438public static extern bool PushUpdate2(IntPtr obj);
394 439
395/* 440// =====================================================================================
396[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 441[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
397public static extern IntPtr CreateMesh2(IntPtr world, int indicesCount, int* indices, int verticesCount, float* vertices ); 442public static extern IntPtr CreateMeshShape2(IntPtr world,
443 int indicesCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices,
444 int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices );
398 445
399[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 446[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
400public static extern bool BuildHull2(IntPtr world, IntPtr mesh); 447public static extern IntPtr CreateHullShape2(IntPtr world,
448 int hullCount, [MarshalAs(UnmanagedType.LPArray)] float[] hulls);
401 449
402[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 450[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
403public static extern bool ReleaseHull2(IntPtr world, IntPtr mesh); 451public static extern IntPtr BuildHullShape2(IntPtr world, IntPtr meshShape);
404 452
405[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 453[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
406public static extern bool DestroyMesh2(IntPtr world, IntPtr mesh); 454public static extern IntPtr BuildNativeShape2(IntPtr world,
455 float shapeType, float collisionMargin, Vector3 scale);
407 456
408[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 457[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
409public static extern IntPtr CreateObject2(IntPtr world, ShapeData shapeData); 458public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape);
410*/
411 459
412[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 460[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
461public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot);
462
463[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
464public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot);
465
466[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
467public static extern bool SetBodyShape2(IntPtr sim, IntPtr obj, IntPtr shape);
468// =====================================================================================
469[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
470public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords,
471 [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin);
472
473[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
474public static extern IntPtr FillHeightMapInfo2(IntPtr sim, IntPtr mapInfo, uint id, Vector3 minCoords, Vector3 maxCoords,
475 [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin);
476
477[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
478public static extern bool ReleaseHeightMapInfo2(IntPtr heightMapInfo);
479
480[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
481public static extern IntPtr CreateGroundPlaneShape2(uint id, float height, float collisionMargin);
482
483[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
484public static extern IntPtr CreateTerrainShape2(IntPtr mapInfo);
485
486// =====================================================================================
487[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
413public static extern IntPtr Create6DofConstraint2(IntPtr world, IntPtr obj1, IntPtr obj2, 488public static extern IntPtr Create6DofConstraint2(IntPtr world, IntPtr obj1, IntPtr obj2,
414 Vector3 frame1loc, Quaternion frame1rot, 489 Vector3 frame1loc, Quaternion frame1rot,
415 Vector3 frame2loc, Quaternion frame2rot, 490 Vector3 frame2loc, Quaternion frame2rot,
@@ -460,11 +535,16 @@ public static extern bool SetConstraintParam2(IntPtr constrain, ConstraintParams
460[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 535[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
461public static extern bool DestroyConstraint2(IntPtr world, IntPtr constrain); 536public static extern bool DestroyConstraint2(IntPtr world, IntPtr constrain);
462 537
538// =====================================================================================
463[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 539[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
464public static extern Vector3 AddObjectToWorld2(IntPtr world, IntPtr obj); 540public static extern bool AddObjectToWorld2(IntPtr world, IntPtr obj);
465 541
466[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 542[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
467public static extern Vector3 RemoveObjectFromWorld2(IntPtr world, IntPtr obj); 543public static extern bool RemoveObjectFromWorld2(IntPtr world, IntPtr obj);
544
545// =====================================================================================
546[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
547public static extern void Activate2(IntPtr obj, bool forceActivation);
468 548
469[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 549[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
470public static extern Vector3 GetPosition2(IntPtr obj); 550public static extern Vector3 GetPosition2(IntPtr obj);
@@ -509,6 +589,9 @@ public static extern bool SetContactProcessingThreshold2(IntPtr obj, float val);
509public static extern bool SetFriction2(IntPtr obj, float val); 589public static extern bool SetFriction2(IntPtr obj, float val);
510 590
511[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 591[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
592public static extern bool SetHitFraction2(IntPtr obj, float val);
593
594[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
512public static extern bool SetRestitution2(IntPtr obj, float val); 595public static extern bool SetRestitution2(IntPtr obj, float val);
513 596
514[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 597[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
@@ -551,7 +634,7 @@ public static extern bool SetMargin2(IntPtr obj, float val);
551public static extern bool UpdateSingleAabb2(IntPtr world, IntPtr obj); 634public static extern bool UpdateSingleAabb2(IntPtr world, IntPtr obj);
552 635
553[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 636[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
554public static extern bool DestroyObject2(IntPtr world, uint id); 637public static extern bool DestroyObject2(IntPtr world, IntPtr obj);
555 638
556[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] 639[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
557public static extern void DumpPhysicsStatistics2(IntPtr sim); 640public static extern void DumpPhysicsStatistics2(IntPtr sim);