aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Physics/ChOdePlugin/ODECharacter.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Physics/ChOdePlugin/ODECharacter.cs')
-rw-r--r--OpenSim/Region/Physics/ChOdePlugin/ODECharacter.cs1367
1 files changed, 1367 insertions, 0 deletions
diff --git a/OpenSim/Region/Physics/ChOdePlugin/ODECharacter.cs b/OpenSim/Region/Physics/ChOdePlugin/ODECharacter.cs
new file mode 100644
index 0000000..6dadbe5
--- /dev/null
+++ b/OpenSim/Region/Physics/ChOdePlugin/ODECharacter.cs
@@ -0,0 +1,1367 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the 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 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using OpenMetaverse;
32using Ode.NET;
33using OpenSim.Framework;
34using OpenSim.Region.Physics.Manager;
35using log4net;
36
37namespace OpenSim.Region.Physics.OdePlugin
38{
39 /// <summary>
40 /// Various properties that ODE uses for AMotors but isn't exposed in ODE.NET so we must define them ourselves.
41 /// </summary>
42
43 public enum dParam : int
44 {
45 LowStop = 0,
46 HiStop = 1,
47 Vel = 2,
48 FMax = 3,
49 FudgeFactor = 4,
50 Bounce = 5,
51 CFM = 6,
52 StopERP = 7,
53 StopCFM = 8,
54 LoStop2 = 256,
55 HiStop2 = 257,
56 Vel2 = 258,
57 FMax2 = 259,
58 StopERP2 = 7 + 256,
59 StopCFM2 = 8 + 256,
60 LoStop3 = 512,
61 HiStop3 = 513,
62 Vel3 = 514,
63 FMax3 = 515,
64 StopERP3 = 7 + 512,
65 StopCFM3 = 8 + 512
66 }
67 public class OdeCharacter : PhysicsActor
68 {
69 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
70
71 private Vector3 _position;
72 private d.Vector3 _zeroPosition;
73 // private d.Matrix3 m_StandUpRotation;
74 private bool _zeroFlag = false;
75 private bool m_lastUpdateSent = false;
76 private Vector3 _velocity;
77 private Vector3 _target_velocity;
78 private Vector3 _acceleration;
79 private Vector3 m_rotationalVelocity;
80 private float m_mass = 80f;
81 public float m_density = 60f;
82 private bool m_pidControllerActive = true;
83 public float PID_D = 800.0f;
84 public float PID_P = 900.0f;
85 //private static float POSTURE_SERVO = 10000.0f;
86 public float CAPSULE_RADIUS = 0.37f;
87 public float CAPSULE_LENGTH = 2.140599f;
88 public float m_tensor = 3800000f;
89 public float heightFudgeFactor = 0.52f;
90 public float walkDivisor = 1.3f;
91 public float runDivisor = 0.8f;
92 private bool flying = false;
93 private bool m_iscolliding = false;
94 private bool m_iscollidingGround = false;
95 private bool m_wascolliding = false;
96 private bool m_wascollidingGround = false;
97 private bool m_iscollidingObj = false;
98 private bool m_alwaysRun = false;
99 private bool m_hackSentFall = false;
100 private bool m_hackSentFly = false;
101 private int m_requestedUpdateFrequency = 0;
102 private Vector3 m_taintPosition = Vector3.Zero;
103 public uint m_localID = 0;
104 public bool m_returnCollisions = false;
105 // taints and their non-tainted counterparts
106 public bool m_isPhysical = false; // the current physical status
107 public bool m_tainted_isPhysical = false; // set when the physical status is tainted (false=not existing in physics engine, true=existing)
108 public float MinimumGroundFlightOffset = 3f;
109
110 private float m_tainted_CAPSULE_LENGTH; // set when the capsule length changes.
111 private float m_tiltMagnitudeWhenProjectedOnXYPlane = 0.1131371f; // used to introduce a fixed tilt because a straight-up capsule falls through terrain, probably a bug in terrain collider
112
113
114 private float m_buoyancy = 0f;
115
116 // private CollisionLocker ode;
117
118 private string m_name = String.Empty;
119
120 private bool[] m_colliderarr = new bool[11];
121 private bool[] m_colliderGroundarr = new bool[11];
122
123 // Default we're a Character
124 private CollisionCategories m_collisionCategories = (CollisionCategories.Character);
125
126 // Default, Collide with Other Geometries, spaces, bodies and characters.
127 private CollisionCategories m_collisionFlags = (CollisionCategories.Geom
128 | CollisionCategories.Space
129 | CollisionCategories.Body
130 | CollisionCategories.Character
131 | CollisionCategories.Land);
132 public IntPtr Body = IntPtr.Zero;
133 private OdeScene _parent_scene;
134 public IntPtr Shell = IntPtr.Zero;
135 public IntPtr Amotor = IntPtr.Zero;
136 public d.Mass ShellMass;
137 public bool collidelock = false;
138
139 public int m_eventsubscription = 0;
140 private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
141
142 // unique UUID of this character object
143 public UUID m_uuid;
144 public bool bad = false;
145
146 public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, CollisionLocker dode, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor)
147 {
148 m_uuid = UUID.Random();
149
150 if (pos.IsFinite())
151 {
152 if (pos.Z > 9999999f)
153 {
154 pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
155 }
156 if (pos.Z < -90000f)
157 {
158 pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
159 }
160 _position = pos;
161 m_taintPosition.X = pos.X;
162 m_taintPosition.Y = pos.Y;
163 m_taintPosition.Z = pos.Z;
164 }
165 else
166 {
167 _position = new Vector3(((float)_parent_scene.WorldExtents.X * 0.5f), ((float)_parent_scene.WorldExtents.Y * 0.5f), parent_scene.GetTerrainHeightAtXY(128f, 128f) + 10f);
168 m_taintPosition.X = _position.X;
169 m_taintPosition.Y = _position.Y;
170 m_taintPosition.Z = _position.Z;
171 m_log.Warn("[PHYSICS]: Got NaN Position on Character Create");
172 }
173
174 _parent_scene = parent_scene;
175
176 PID_D = pid_d;
177 PID_P = pid_p;
178 CAPSULE_RADIUS = capsule_radius;
179 m_tensor = tensor;
180 m_density = density;
181 heightFudgeFactor = height_fudge_factor;
182 walkDivisor = walk_divisor;
183 runDivisor = rundivisor;
184
185 // m_StandUpRotation =
186 // new d.Matrix3(0.5f, 0.7071068f, 0.5f, -0.7071068f, 0f, 0.7071068f, 0.5f, -0.7071068f,
187 // 0.5f);
188
189 for (int i = 0; i < 11; i++)
190 {
191 m_colliderarr[i] = false;
192 }
193 CAPSULE_LENGTH = (size.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
194 //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
195 m_tainted_CAPSULE_LENGTH = CAPSULE_LENGTH;
196
197 m_isPhysical = false; // current status: no ODE information exists
198 m_tainted_isPhysical = true; // new tainted status: need to create ODE information
199
200 _parent_scene.AddPhysicsActorTaint(this);
201
202 m_name = avName;
203 }
204
205 public override int PhysicsActorType
206 {
207 get { return (int) ActorTypes.Agent; }
208 set { return; }
209 }
210
211 /// <summary>
212 /// If this is set, the avatar will move faster
213 /// </summary>
214 public override bool SetAlwaysRun
215 {
216 get { return m_alwaysRun; }
217 set { m_alwaysRun = value; }
218 }
219
220 public override uint LocalID
221 {
222 set { m_localID = value; }
223 }
224
225 public override bool Grabbed
226 {
227 set { return; }
228 }
229
230 public override bool Selected
231 {
232 set { return; }
233 }
234
235 public override float Buoyancy
236 {
237 get { return m_buoyancy; }
238 set { m_buoyancy = value; }
239 }
240
241 public override bool FloatOnWater
242 {
243 set { return; }
244 }
245
246 public override bool IsPhysical
247 {
248 get { return false; }
249 set { return; }
250 }
251
252 public override bool ThrottleUpdates
253 {
254 get { return false; }
255 set { return; }
256 }
257
258 public override bool Flying
259 {
260 get { return flying; }
261 set { flying = value; }
262 }
263
264 /// <summary>
265 /// Returns if the avatar is colliding in general.
266 /// This includes the ground and objects and avatar.
267 /// </summary>
268 public override bool IsColliding
269 {
270 get { return m_iscolliding; }
271 set
272 {
273 int i;
274 int truecount = 0;
275 int falsecount = 0;
276
277 if (m_colliderarr.Length >= 10)
278 {
279 for (i = 0; i < 10; i++)
280 {
281 m_colliderarr[i] = m_colliderarr[i + 1];
282 }
283 }
284 m_colliderarr[10] = value;
285
286 for (i = 0; i < 11; i++)
287 {
288 if (m_colliderarr[i])
289 {
290 truecount++;
291 }
292 else
293 {
294 falsecount++;
295 }
296 }
297
298 // Equal truecounts and false counts means we're colliding with something.
299
300 if (falsecount > 1.2*truecount)
301 {
302 m_iscolliding = false;
303 }
304 else
305 {
306 m_iscolliding = true;
307 }
308 if (m_wascolliding != m_iscolliding)
309 {
310 //base.SendCollisionUpdate(new CollisionEventUpdate());
311 }
312 m_wascolliding = m_iscolliding;
313 }
314 }
315
316 /// <summary>
317 /// Returns if an avatar is colliding with the ground
318 /// </summary>
319 public override bool CollidingGround
320 {
321 get { return m_iscollidingGround; }
322 set
323 {
324 // Collisions against the ground are not really reliable
325 // So, to get a consistant value we have to average the current result over time
326 // Currently we use 1 second = 10 calls to this.
327 int i;
328 int truecount = 0;
329 int falsecount = 0;
330
331 if (m_colliderGroundarr.Length >= 10)
332 {
333 for (i = 0; i < 10; i++)
334 {
335 m_colliderGroundarr[i] = m_colliderGroundarr[i + 1];
336 }
337 }
338 m_colliderGroundarr[10] = value;
339
340 for (i = 0; i < 11; i++)
341 {
342 if (m_colliderGroundarr[i])
343 {
344 truecount++;
345 }
346 else
347 {
348 falsecount++;
349 }
350 }
351
352 // Equal truecounts and false counts means we're colliding with something.
353
354 if (falsecount > 1.2*truecount)
355 {
356 m_iscollidingGround = false;
357 }
358 else
359 {
360 m_iscollidingGround = true;
361 }
362 if (m_wascollidingGround != m_iscollidingGround)
363 {
364 //base.SendCollisionUpdate(new CollisionEventUpdate());
365 }
366 m_wascollidingGround = m_iscollidingGround;
367 }
368 }
369
370 /// <summary>
371 /// Returns if the avatar is colliding with an object
372 /// </summary>
373 public override bool CollidingObj
374 {
375 get { return m_iscollidingObj; }
376 set
377 {
378 m_iscollidingObj = value;
379 if (value)
380 m_pidControllerActive = false;
381 else
382 m_pidControllerActive = true;
383 }
384 }
385
386 /// <summary>
387 /// turn the PID controller on or off.
388 /// The PID Controller will turn on all by itself in many situations
389 /// </summary>
390 /// <param name="status"></param>
391 public void SetPidStatus(bool status)
392 {
393 m_pidControllerActive = status;
394 }
395
396 public override bool Stopped
397 {
398 get { return _zeroFlag; }
399 }
400
401 /// <summary>
402 /// This 'puts' an avatar somewhere in the physics space.
403 /// Not really a good choice unless you 'know' it's a good
404 /// spot otherwise you're likely to orbit the avatar.
405 /// </summary>
406 public override Vector3 Position
407 {
408 get { return _position; }
409 set
410 {
411 if (Body == IntPtr.Zero || Shell == IntPtr.Zero)
412 {
413 if (value.IsFinite())
414 {
415 if (value.Z > 9999999f)
416 {
417 value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
418 }
419 if (value.Z < -90000f)
420 {
421 value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
422 }
423
424 _position.X = value.X;
425 _position.Y = value.Y;
426 _position.Z = value.Z;
427
428 m_taintPosition.X = value.X;
429 m_taintPosition.Y = value.Y;
430 m_taintPosition.Z = value.Z;
431 _parent_scene.AddPhysicsActorTaint(this);
432 }
433 else
434 {
435 m_log.Warn("[PHYSICS]: Got a NaN Position from Scene on a Character");
436 }
437 }
438 }
439 }
440
441 public override Vector3 RotationalVelocity
442 {
443 get { return m_rotationalVelocity; }
444 set { m_rotationalVelocity = value; }
445 }
446
447 /// <summary>
448 /// This property sets the height of the avatar only. We use the height to make sure the avatar stands up straight
449 /// and use it to offset landings properly
450 /// </summary>
451 public override Vector3 Size
452 {
453 get { return new Vector3(CAPSULE_RADIUS * 2, CAPSULE_RADIUS * 2, CAPSULE_LENGTH); }
454 set
455 {
456 if (value.IsFinite())
457 {
458 m_pidControllerActive = true;
459
460 Vector3 SetSize = value;
461 m_tainted_CAPSULE_LENGTH = (SetSize.Z*1.15f) - CAPSULE_RADIUS*2.0f;
462 //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
463
464 Velocity = Vector3.Zero;
465
466 _parent_scene.AddPhysicsActorTaint(this);
467 }
468 else
469 {
470 m_log.Warn("[PHYSICS]: Got a NaN Size from Scene on a Character");
471 }
472 }
473 }
474
475 private void AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3 movementVector)
476 {
477 movementVector.Z = 0f;
478 float magnitude = (float)Math.Sqrt((double)(movementVector.X * movementVector.X + movementVector.Y * movementVector.Y));
479 if (magnitude < 0.1f) return;
480
481 // normalize the velocity vector
482 float invMagnitude = 1.0f / magnitude;
483 movementVector.X *= invMagnitude;
484 movementVector.Y *= invMagnitude;
485
486 // if we change the capsule heading too often, the capsule can fall down
487 // therefore we snap movement vector to just 1 of 4 predefined directions (ne, nw, se, sw),
488 // meaning only 4 possible capsule tilt orientations
489 if (movementVector.X > 0)
490 {
491 // east
492 if (movementVector.Y > 0)
493 {
494 // northeast
495 movementVector.X = (float)Math.Sqrt(2.0);
496 movementVector.Y = (float)Math.Sqrt(2.0);
497 }
498 else
499 {
500 // southeast
501 movementVector.X = (float)Math.Sqrt(2.0);
502 movementVector.Y = -(float)Math.Sqrt(2.0);
503 }
504 }
505 else
506 {
507 // west
508 if (movementVector.Y > 0)
509 {
510 // northwest
511 movementVector.X = -(float)Math.Sqrt(2.0);
512 movementVector.Y = (float)Math.Sqrt(2.0);
513 }
514 else
515 {
516 // southwest
517 movementVector.X = -(float)Math.Sqrt(2.0);
518 movementVector.Y = -(float)Math.Sqrt(2.0);
519 }
520 }
521
522
523 // movementVector.Z is zero
524
525 // calculate tilt components based on desired amount of tilt and current (snapped) heading.
526 // the "-" sign is to force the tilt to be OPPOSITE the direction of movement.
527 float xTiltComponent = -movementVector.X * m_tiltMagnitudeWhenProjectedOnXYPlane;
528 float yTiltComponent = -movementVector.Y * m_tiltMagnitudeWhenProjectedOnXYPlane;
529
530 //m_log.Debug("[PHYSICS] changing avatar tilt");
531 d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, xTiltComponent);
532 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, xTiltComponent); // must be same as lowstop, else a different, spurious tilt is introduced
533 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, yTiltComponent);
534 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, yTiltComponent); // same as lowstop
535 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, 0f);
536 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f); // same as lowstop
537 }
538
539 /// <summary>
540 /// This creates the Avatar's physical Surrogate at the position supplied
541 /// </summary>
542 /// <param name="npositionX"></param>
543 /// <param name="npositionY"></param>
544 /// <param name="npositionZ"></param>
545
546 // WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access
547 // to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only
548 // place that is safe to call this routine AvatarGeomAndBodyCreation.
549 private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ, float tensor)
550 {
551 //CAPSULE_LENGTH = -5;
552 //CAPSULE_RADIUS = -5;
553 int dAMotorEuler = 1;
554 _parent_scene.waitForSpaceUnlock(_parent_scene.space);
555 if (CAPSULE_LENGTH <= 0)
556 {
557 m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
558 CAPSULE_LENGTH = 0.01f;
559
560 }
561
562 if (CAPSULE_RADIUS <= 0)
563 {
564 m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
565 CAPSULE_RADIUS = 0.01f;
566
567 }
568 Shell = d.CreateCapsule(_parent_scene.space, CAPSULE_RADIUS, CAPSULE_LENGTH);
569
570 d.GeomSetCategoryBits(Shell, (int)m_collisionCategories);
571 d.GeomSetCollideBits(Shell, (int)m_collisionFlags);
572
573 d.MassSetCapsuleTotal(out ShellMass, m_mass, 2, CAPSULE_RADIUS, CAPSULE_LENGTH);
574 Body = d.BodyCreate(_parent_scene.world);
575 d.BodySetPosition(Body, npositionX, npositionY, npositionZ);
576
577 _position.X = npositionX;
578 _position.Y = npositionY;
579 _position.Z = npositionZ;
580
581
582 m_taintPosition.X = npositionX;
583 m_taintPosition.Y = npositionY;
584 m_taintPosition.Z = npositionZ;
585
586 d.BodySetMass(Body, ref ShellMass);
587 d.Matrix3 m_caprot;
588 // 90 Stand up on the cap of the capped cyllinder
589 if (_parent_scene.IsAvCapsuleTilted)
590 {
591 d.RFromAxisAndAngle(out m_caprot, 1, 0, 1, (float)(Math.PI / 2));
592 }
593 else
594 {
595 d.RFromAxisAndAngle(out m_caprot, 0, 0, 1, (float)(Math.PI / 2));
596 }
597
598
599 d.GeomSetRotation(Shell, ref m_caprot);
600 d.BodySetRotation(Body, ref m_caprot);
601
602 d.GeomSetBody(Shell, Body);
603
604
605 // The purpose of the AMotor here is to keep the avatar's physical
606 // surrogate from rotating while moving
607 Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
608 d.JointAttach(Amotor, Body, IntPtr.Zero);
609 d.JointSetAMotorMode(Amotor, dAMotorEuler);
610 d.JointSetAMotorNumAxes(Amotor, 3);
611 d.JointSetAMotorAxis(Amotor, 0, 0, 1, 0, 0);
612 d.JointSetAMotorAxis(Amotor, 1, 0, 0, 1, 0);
613 d.JointSetAMotorAxis(Amotor, 2, 0, 0, 0, 1);
614 d.JointSetAMotorAngle(Amotor, 0, 0);
615 d.JointSetAMotorAngle(Amotor, 1, 0);
616 d.JointSetAMotorAngle(Amotor, 2, 0);
617
618 // These lowstops and high stops are effectively (no wiggle room)
619 if (_parent_scene.IsAvCapsuleTilted)
620 {
621 d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -0.000000000001f);
622 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0.000000000001f);
623 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -0.000000000001f);
624 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.000000000001f);
625 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0.000000000001f);
626 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.000000000001f);
627 }
628 else
629 {
630 #region Documentation of capsule motor LowStop and HighStop parameters
631 // Intentionally introduce some tilt into the capsule by setting
632 // the motor stops to small epsilon values. This small tilt prevents
633 // the capsule from falling into the terrain; a straight-up capsule
634 // (with -0..0 motor stops) falls into the terrain for reasons yet
635 // to be comprehended in their entirety.
636 #endregion
637 AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3.Zero);
638 d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, 0.08f);
639 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0f);
640 d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, 0.08f);
641 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.08f); // must be same as lowstop, else a different, spurious tilt is introduced
642 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f); // same as lowstop
643 d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.08f); // same as lowstop
644 }
645
646 // Fudge factor is 1f by default, we're setting it to 0. We don't want it to Fudge or the
647 // capped cyllinder will fall over
648 d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f);
649 d.JointSetAMotorParam(Amotor, (int)dParam.FMax, tensor);
650
651 //d.Matrix3 bodyrotation = d.BodyGetRotation(Body);
652 //d.QfromR(
653 //d.Matrix3 checkrotation = new d.Matrix3(0.7071068,0.5, -0.7071068,
654 //
655 //m_log.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22);
656 //standupStraight();
657 }
658
659 //
660 /// <summary>
661 /// Uses the capped cyllinder volume formula to calculate the avatar's mass.
662 /// This may be used in calculations in the scene/scenepresence
663 /// </summary>
664 public override float Mass
665 {
666 get
667 {
668 float AVvolume = (float) (Math.PI*Math.Pow(CAPSULE_RADIUS, 2)*CAPSULE_LENGTH);
669 return m_density*AVvolume;
670 }
671 }
672 public override void link(PhysicsActor obj)
673 {
674
675 }
676
677 public override void delink()
678 {
679
680 }
681
682 public override void LockAngularMotion(Vector3 axis)
683 {
684
685 }
686
687// This code is very useful. Written by DanX0r. We're just not using it right now.
688// Commented out to prevent a warning.
689//
690// private void standupStraight()
691// {
692// // The purpose of this routine here is to quickly stabilize the Body while it's popped up in the air.
693// // The amotor needs a few seconds to stabilize so without it, the avatar shoots up sky high when you
694// // change appearance and when you enter the simulator
695// // After this routine is done, the amotor stabilizes much quicker
696// d.Vector3 feet;
697// d.Vector3 head;
698// d.BodyGetRelPointPos(Body, 0.0f, 0.0f, -1.0f, out feet);
699// d.BodyGetRelPointPos(Body, 0.0f, 0.0f, 1.0f, out head);
700// float posture = head.Z - feet.Z;
701
702// // restoring force proportional to lack of posture:
703// float servo = (2.5f - posture) * POSTURE_SERVO;
704// d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, servo, 0.0f, 0.0f, 1.0f);
705// d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, -servo, 0.0f, 0.0f, -1.0f);
706// //d.Matrix3 bodyrotation = d.BodyGetRotation(Body);
707// //m_log.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22);
708// }
709
710 public override Vector3 Force
711 {
712 get { return _target_velocity; }
713 set { return; }
714 }
715
716 public override int VehicleType
717 {
718 get { return 0; }
719 set { return; }
720 }
721
722 public override void VehicleFloatParam(int param, float value)
723 {
724
725 }
726
727 public override void VehicleVectorParam(int param, Vector3 value)
728 {
729
730 }
731
732 public override void VehicleRotationParam(int param, Quaternion rotation)
733 {
734
735 }
736
737 public override void VehicleFlags(int flags, bool remove)
738 {
739 }
740
741 public override void VehicleFlagsSet(int flags)
742 {
743
744 }
745
746 public override void VehicleFlagsRemove(int flags)
747 {
748
749 }
750
751 public override void SetVolumeDetect(int param)
752 {
753
754 }
755
756 public override Vector3 CenterOfMass
757 {
758 get { return Vector3.Zero; }
759 }
760
761 public override Vector3 GeometricCenter
762 {
763 get { return Vector3.Zero; }
764 }
765
766 public override PrimitiveBaseShape Shape
767 {
768 set { return; }
769 }
770
771 public override Vector3 Velocity
772 {
773 get {
774 // There's a problem with Vector3.Zero! Don't Use it Here!
775 if (_zeroFlag)
776 return Vector3.Zero;
777 m_lastUpdateSent = false;
778 return _velocity;
779 }
780 set
781 {
782 if (value.IsFinite())
783 {
784 m_pidControllerActive = true;
785 _target_velocity = value;
786 }
787 else
788 {
789 m_log.Warn("[PHYSICS]: Got a NaN velocity from Scene in a Character");
790 }
791 }
792 }
793
794 public override Vector3 Torque
795 {
796 get { return Vector3.Zero; }
797 set { return; }
798 }
799
800 public override float CollisionScore
801 {
802 get { return 0f; }
803 set { }
804 }
805
806 public override bool Kinematic
807 {
808 get { return false; }
809 set { }
810 }
811
812 public override Quaternion Orientation
813 {
814 get { return Quaternion.Identity; }
815 set {
816 //Matrix3 or = Orientation.ToRotationMatrix();
817 //d.Matrix3 ord = new d.Matrix3(or.m00, or.m10, or.m20, or.m01, or.m11, or.m21, or.m02, or.m12, or.m22);
818 //d.BodySetRotation(Body, ref ord);
819 }
820 }
821
822 public override Vector3 Acceleration
823 {
824 get { return _acceleration; }
825 }
826
827 public void SetAcceleration(Vector3 accel)
828 {
829 m_pidControllerActive = true;
830 _acceleration = accel;
831 }
832
833 /// <summary>
834 /// Adds the force supplied to the Target Velocity
835 /// The PID controller takes this target velocity and tries to make it a reality
836 /// </summary>
837 /// <param name="force"></param>
838 public override void AddForce(Vector3 force, bool pushforce)
839 {
840 if (force.IsFinite())
841 {
842 if (pushforce)
843 {
844 m_pidControllerActive = false;
845 force *= 100f;
846 doForce(force);
847 // If uncommented, things get pushed off world
848 //
849 // m_log.Debug("Push!");
850 // _target_velocity.X += force.X;
851 // _target_velocity.Y += force.Y;
852 // _target_velocity.Z += force.Z;
853 }
854 else
855 {
856 m_pidControllerActive = true;
857 _target_velocity.X += force.X;
858 _target_velocity.Y += force.Y;
859 _target_velocity.Z += force.Z;
860 }
861 }
862 else
863 {
864 m_log.Warn("[PHYSICS]: Got a NaN force applied to a Character");
865 }
866 //m_lastUpdateSent = false;
867 }
868
869 public override void AddAngularForce(Vector3 force, bool pushforce)
870 {
871
872 }
873
874 /// <summary>
875 /// After all of the forces add up with 'add force' we apply them with doForce
876 /// </summary>
877 /// <param name="force"></param>
878 public void doForce(Vector3 force)
879 {
880 if (!collidelock)
881 {
882 d.BodyAddForce(Body, force.X, force.Y, force.Z);
883 //d.BodySetRotation(Body, ref m_StandUpRotation);
884 //standupStraight();
885
886 }
887 }
888
889 public override void SetMomentum(Vector3 momentum)
890 {
891 }
892
893
894 /// <summary>
895 /// Called from Simulate
896 /// This is the avatar's movement control + PID Controller
897 /// </summary>
898 /// <param name="timeStep"></param>
899 public void Move(float timeStep, List<OdeCharacter> defects)
900 {
901 // no lock; for now it's only called from within Simulate()
902
903 // If the PID Controller isn't active then we set our force
904 // calculating base velocity to the current position
905
906 if (Body == IntPtr.Zero)
907 return;
908
909 if (m_pidControllerActive == false)
910 {
911 _zeroPosition = d.BodyGetPosition(Body);
912 }
913 //PidStatus = true;
914
915 d.Vector3 localpos = d.BodyGetPosition(Body);
916 Vector3 localPos = new Vector3(localpos.X, localpos.Y, localpos.Z);
917
918 if (!localPos.IsFinite())
919 {
920
921 m_log.Warn("[PHYSICS]: Avatar Position is non-finite!");
922 defects.Add(this);
923 // _parent_scene.RemoveCharacter(this);
924
925 // destroy avatar capsule and related ODE data
926 if (Amotor != IntPtr.Zero)
927 {
928 // Kill the Amotor
929 d.JointDestroy(Amotor);
930 Amotor = IntPtr.Zero;
931 }
932
933 //kill the Geometry
934 _parent_scene.waitForSpaceUnlock(_parent_scene.space);
935
936 if (Body != IntPtr.Zero)
937 {
938 //kill the body
939 d.BodyDestroy(Body);
940
941 Body = IntPtr.Zero;
942 }
943
944 if (Shell != IntPtr.Zero)
945 {
946 d.GeomDestroy(Shell);
947 _parent_scene.geom_name_map.Remove(Shell);
948 Shell = IntPtr.Zero;
949 }
950
951 return;
952 }
953
954 Vector3 vec = Vector3.Zero;
955 d.Vector3 vel = d.BodyGetLinearVel(Body);
956
957 float movementdivisor = 1f;
958
959 if (!m_alwaysRun)
960 {
961 movementdivisor = walkDivisor;
962 }
963 else
964 {
965 movementdivisor = runDivisor;
966 }
967
968 // if velocity is zero, use position control; otherwise, velocity control
969 if (_target_velocity.X == 0.0f && _target_velocity.Y == 0.0f && _target_velocity.Z == 0.0f && m_iscolliding)
970 {
971 // keep track of where we stopped. No more slippin' & slidin'
972 if (!_zeroFlag)
973 {
974 _zeroFlag = true;
975 _zeroPosition = d.BodyGetPosition(Body);
976 }
977 if (m_pidControllerActive)
978 {
979 // We only want to deactivate the PID Controller if we think we want to have our surrogate
980 // react to the physics scene by moving it's position.
981 // Avatar to Avatar collisions
982 // Prim to avatar collisions
983
984 d.Vector3 pos = d.BodyGetPosition(Body);
985 vec.X = (_target_velocity.X - vel.X) * (PID_D) + (_zeroPosition.X - pos.X) * (PID_P * 2);
986 vec.Y = (_target_velocity.Y - vel.Y)*(PID_D) + (_zeroPosition.Y - pos.Y)* (PID_P * 2);
987 if (flying)
988 {
989 vec.Z = (_target_velocity.Z - vel.Z) * (PID_D) + (_zeroPosition.Z - pos.Z) * PID_P;
990 }
991 }
992 //PidStatus = true;
993 }
994 else
995 {
996 m_pidControllerActive = true;
997 _zeroFlag = false;
998 if (m_iscolliding && !flying)
999 {
1000 // We're standing on something
1001 vec.X = ((_target_velocity.X / movementdivisor) - vel.X) * (PID_D);
1002 vec.Y = ((_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D);
1003 }
1004 else if (m_iscolliding && flying)
1005 {
1006 // We're flying and colliding with something
1007 vec.X = ((_target_velocity.X/movementdivisor) - vel.X)*(PID_D / 16);
1008 vec.Y = ((_target_velocity.Y/movementdivisor) - vel.Y)*(PID_D / 16);
1009 }
1010 else if (!m_iscolliding && flying)
1011 {
1012 // we're in mid air suspended
1013 vec.X = ((_target_velocity.X / movementdivisor) - vel.X) * (PID_D/6);
1014 vec.Y = ((_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D/6);
1015 }
1016
1017 if (m_iscolliding && !flying && _target_velocity.Z > 0.0f)
1018 {
1019 // We're colliding with something and we're not flying but we're moving
1020 // This means we're walking or running.
1021 d.Vector3 pos = d.BodyGetPosition(Body);
1022 vec.Z = (_target_velocity.Z - vel.Z)*PID_D + (_zeroPosition.Z - pos.Z)*PID_P;
1023 if (_target_velocity.X > 0)
1024 {
1025 vec.X = ((_target_velocity.X - vel.X)/1.2f)*PID_D;
1026 }
1027 if (_target_velocity.Y > 0)
1028 {
1029 vec.Y = ((_target_velocity.Y - vel.Y)/1.2f)*PID_D;
1030 }
1031 }
1032 else if (!m_iscolliding && !flying)
1033 {
1034 // we're not colliding and we're not flying so that means we're falling!
1035 // m_iscolliding includes collisions with the ground.
1036
1037 // d.Vector3 pos = d.BodyGetPosition(Body);
1038 if (_target_velocity.X > 0)
1039 {
1040 vec.X = ((_target_velocity.X - vel.X)/1.2f)*PID_D;
1041 }
1042 if (_target_velocity.Y > 0)
1043 {
1044 vec.Y = ((_target_velocity.Y - vel.Y)/1.2f)*PID_D;
1045 }
1046 }
1047
1048 if (flying)
1049 {
1050 vec.Z = (_target_velocity.Z - vel.Z) * (PID_D);
1051 }
1052 }
1053 if (flying)
1054 {
1055 vec.Z += ((-1 * _parent_scene.gravityz)*m_mass);
1056
1057 //Added for auto fly height. Kitto Flora
1058 //d.Vector3 pos = d.BodyGetPosition(Body);
1059 float target_altitude = _parent_scene.GetTerrainHeightAtXY(_position.X, _position.Y) + MinimumGroundFlightOffset;
1060
1061 if (_position.Z < target_altitude)
1062 {
1063 vec.Z += (target_altitude - _position.Z) * PID_P * 5.0f;
1064 }
1065 // end add Kitto Flora
1066 }
1067 if (vec.IsFinite())
1068 {
1069 doForce(vec);
1070 if (!_zeroFlag)
1071 {
1072 AlignAvatarTiltWithCurrentDirectionOfMovement(vec);
1073 }
1074 }
1075 else
1076 {
1077 m_log.Warn("[PHYSICS]: Got a NaN force vector in Move()");
1078 m_log.Warn("[PHYSICS]: Avatar Position is non-finite!");
1079 defects.Add(this);
1080 // _parent_scene.RemoveCharacter(this);
1081 // destroy avatar capsule and related ODE data
1082 if (Amotor != IntPtr.Zero)
1083 {
1084 // Kill the Amotor
1085 d.JointDestroy(Amotor);
1086 Amotor = IntPtr.Zero;
1087 }
1088 //kill the Geometry
1089 _parent_scene.waitForSpaceUnlock(_parent_scene.space);
1090
1091 if (Body != IntPtr.Zero)
1092 {
1093 //kill the body
1094 d.BodyDestroy(Body);
1095
1096 Body = IntPtr.Zero;
1097 }
1098
1099 if (Shell != IntPtr.Zero)
1100 {
1101 d.GeomDestroy(Shell);
1102 _parent_scene.geom_name_map.Remove(Shell);
1103 Shell = IntPtr.Zero;
1104 }
1105 }
1106 }
1107
1108 /// <summary>
1109 /// Updates the reported position and velocity. This essentially sends the data up to ScenePresence.
1110 /// </summary>
1111 public void UpdatePositionAndVelocity()
1112 {
1113 // no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
1114 d.Vector3 vec;
1115 try
1116 {
1117 vec = d.BodyGetPosition(Body);
1118 }
1119 catch (NullReferenceException)
1120 {
1121 bad = true;
1122 _parent_scene.BadCharacter(this);
1123 vec = new d.Vector3(_position.X, _position.Y, _position.Z);
1124 base.RaiseOutOfBounds(_position); // Tells ScenePresence that there's a problem!
1125 m_log.WarnFormat("[ODEPLUGIN]: Avatar Null reference for Avatar {0}, physical actor {1}", m_name, m_uuid);
1126 }
1127
1128
1129 // kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
1130 if (vec.X < 0.0f) vec.X = 0.0f;
1131 if (vec.Y < 0.0f) vec.Y = 0.0f;
1132 if (vec.X > (int)_parent_scene.WorldExtents.X - 0.05f) vec.X = (int)_parent_scene.WorldExtents.X - 0.05f;
1133 if (vec.Y > (int)_parent_scene.WorldExtents.Y - 0.05f) vec.Y = (int)_parent_scene.WorldExtents.Y - 0.05f;
1134
1135 _position.X = vec.X;
1136 _position.Y = vec.Y;
1137 _position.Z = vec.Z;
1138
1139 // Did we move last? = zeroflag
1140 // This helps keep us from sliding all over
1141
1142 if (_zeroFlag)
1143 {
1144 _velocity.X = 0.0f;
1145 _velocity.Y = 0.0f;
1146 _velocity.Z = 0.0f;
1147
1148 // Did we send out the 'stopped' message?
1149 if (!m_lastUpdateSent)
1150 {
1151 m_lastUpdateSent = true;
1152 //base.RequestPhysicsterseUpdate();
1153
1154 }
1155 }
1156 else
1157 {
1158 m_lastUpdateSent = false;
1159 try
1160 {
1161 vec = d.BodyGetLinearVel(Body);
1162 }
1163 catch (NullReferenceException)
1164 {
1165 vec.X = _velocity.X;
1166 vec.Y = _velocity.Y;
1167 vec.Z = _velocity.Z;
1168 }
1169 _velocity.X = (vec.X);
1170 _velocity.Y = (vec.Y);
1171
1172 _velocity.Z = (vec.Z);
1173
1174 if (_velocity.Z < -6 && !m_hackSentFall)
1175 {
1176 m_hackSentFall = true;
1177 m_pidControllerActive = false;
1178 }
1179 else if (flying && !m_hackSentFly)
1180 {
1181 //m_hackSentFly = true;
1182 //base.SendCollisionUpdate(new CollisionEventUpdate());
1183 }
1184 else
1185 {
1186 m_hackSentFly = false;
1187 m_hackSentFall = false;
1188 }
1189 }
1190 }
1191
1192 /// <summary>
1193 /// Cleanup the things we use in the scene.
1194 /// </summary>
1195 public void Destroy()
1196 {
1197 m_tainted_isPhysical = false;
1198 _parent_scene.AddPhysicsActorTaint(this);
1199 }
1200
1201 public override void CrossingFailure()
1202 {
1203 }
1204
1205 public override Vector3 PIDTarget { set { return; } }
1206 public override bool PIDActive { set { return; } }
1207 public override float PIDTau { set { return; } }
1208
1209 public override float PIDHoverHeight { set { return; } }
1210 public override bool PIDHoverActive { set { return; } }
1211 public override PIDHoverType PIDHoverType { set { return; } }
1212 public override float PIDHoverTau { set { return; } }
1213
1214 public override Quaternion APIDTarget{ set { return; } }
1215
1216 public override bool APIDActive{ set { return; } }
1217
1218 public override float APIDStrength{ set { return; } }
1219
1220 public override float APIDDamping{ set { return; } }
1221
1222
1223 public override void SubscribeEvents(int ms)
1224 {
1225 m_requestedUpdateFrequency = ms;
1226 m_eventsubscription = ms;
1227 _parent_scene.addCollisionEventReporting(this);
1228 }
1229 public override void UnSubscribeEvents()
1230 {
1231 _parent_scene.remCollisionEventReporting(this);
1232 m_requestedUpdateFrequency = 0;
1233 m_eventsubscription = 0;
1234 }
1235 public void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
1236 {
1237 if (m_eventsubscription > 0)
1238 {
1239 CollisionEventsThisFrame.addCollider(CollidedWith, contact);
1240 }
1241 }
1242
1243 public void SendCollisions()
1244 {
1245 if (m_eventsubscription > m_requestedUpdateFrequency)
1246 {
1247 if (CollisionEventsThisFrame != null)
1248 {
1249 base.SendCollisionUpdate(CollisionEventsThisFrame);
1250 }
1251 CollisionEventsThisFrame = new CollisionEventUpdate();
1252 m_eventsubscription = 0;
1253 }
1254 }
1255 public override bool SubscribedEvents()
1256 {
1257 if (m_eventsubscription > 0)
1258 return true;
1259 return false;
1260 }
1261
1262 public void ProcessTaints(float timestep)
1263 {
1264
1265 if (m_tainted_isPhysical != m_isPhysical)
1266 {
1267 if (m_tainted_isPhysical)
1268 {
1269 // Create avatar capsule and related ODE data
1270 if (!(Shell == IntPtr.Zero && Body == IntPtr.Zero && Amotor == IntPtr.Zero))
1271 {
1272 m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
1273 + (Shell!=IntPtr.Zero ? "Shell ":"")
1274 + (Body!=IntPtr.Zero ? "Body ":"")
1275 + (Amotor!=IntPtr.Zero ? "Amotor ":""));
1276 }
1277 AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z, m_tensor);
1278
1279 _parent_scene.geom_name_map[Shell] = m_name;
1280 _parent_scene.actor_name_map[Shell] = (PhysicsActor)this;
1281 _parent_scene.AddCharacter(this);
1282 }
1283 else
1284 {
1285 _parent_scene.RemoveCharacter(this);
1286 // destroy avatar capsule and related ODE data
1287 if (Amotor != IntPtr.Zero)
1288 {
1289 // Kill the Amotor
1290 d.JointDestroy(Amotor);
1291 Amotor = IntPtr.Zero;
1292 }
1293 //kill the Geometry
1294 _parent_scene.waitForSpaceUnlock(_parent_scene.space);
1295
1296 if (Body != IntPtr.Zero)
1297 {
1298 //kill the body
1299 d.BodyDestroy(Body);
1300
1301 Body = IntPtr.Zero;
1302 }
1303
1304 if (Shell != IntPtr.Zero)
1305 {
1306 d.GeomDestroy(Shell);
1307 _parent_scene.geom_name_map.Remove(Shell);
1308 Shell = IntPtr.Zero;
1309 }
1310
1311 }
1312
1313 m_isPhysical = m_tainted_isPhysical;
1314 }
1315
1316 if (m_tainted_CAPSULE_LENGTH != CAPSULE_LENGTH)
1317 {
1318 if (Shell != IntPtr.Zero && Body != IntPtr.Zero && Amotor != IntPtr.Zero)
1319 {
1320
1321 m_pidControllerActive = true;
1322 // no lock needed on _parent_scene.OdeLock because we are called from within the thread lock in OdePlugin's simulate()
1323 d.JointDestroy(Amotor);
1324 float prevCapsule = CAPSULE_LENGTH;
1325 CAPSULE_LENGTH = m_tainted_CAPSULE_LENGTH;
1326 //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
1327 d.BodyDestroy(Body);
1328 d.GeomDestroy(Shell);
1329 AvatarGeomAndBodyCreation(_position.X, _position.Y,
1330 _position.Z + (Math.Abs(CAPSULE_LENGTH - prevCapsule) * 2), m_tensor);
1331 Velocity = Vector3.Zero;
1332
1333 _parent_scene.geom_name_map[Shell] = m_name;
1334 _parent_scene.actor_name_map[Shell] = (PhysicsActor)this;
1335 }
1336 else
1337 {
1338 m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - "
1339 + (Shell==IntPtr.Zero ? "Shell ":"")
1340 + (Body==IntPtr.Zero ? "Body ":"")
1341 + (Amotor==IntPtr.Zero ? "Amotor ":""));
1342 }
1343 }
1344
1345 if (!m_taintPosition.ApproxEquals(_position, 0.05f))
1346 {
1347 if (Body != IntPtr.Zero)
1348 {
1349 d.BodySetPosition(Body, m_taintPosition.X, m_taintPosition.Y, m_taintPosition.Z);
1350
1351 _position.X = m_taintPosition.X;
1352 _position.Y = m_taintPosition.Y;
1353 _position.Z = m_taintPosition.Z;
1354 }
1355 }
1356
1357 }
1358
1359 internal void AddCollisionFrameTime(int p)
1360 {
1361 // protect it from overflow crashing
1362 if (m_eventsubscription + p >= int.MaxValue)
1363 m_eventsubscription = 0;
1364 m_eventsubscription += p;
1365 }
1366 }
1367}