1
0

BSCharacter.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using log4net;
  31. using OMV = OpenMetaverse;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.PhysicsModules.SharedBase;
  34. namespace OpenSim.Region.PhysicsModule.BulletS
  35. {
  36. public sealed class BSCharacter : BSPhysObject
  37. {
  38. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. private static readonly string LogHeader = "[BULLETS CHAR]";
  40. // private bool _stopped;
  41. private OMV.Vector3 _size;
  42. private bool _grabbed;
  43. private bool _selected;
  44. private float _mass;
  45. private float _avatarVolume;
  46. private float _collisionScore;
  47. private OMV.Vector3 _acceleration;
  48. private int _physicsActorType;
  49. private bool _isPhysical;
  50. private bool _flying;
  51. private bool _setAlwaysRun;
  52. private bool _throttleUpdates;
  53. private bool _floatOnWater;
  54. private OMV.Vector3 _rotationalVelocity;
  55. private bool _kinematic;
  56. private float _buoyancy;
  57. private BSActorAvatarMove m_moveActor;
  58. private const string AvatarMoveActorName = "BSCharacter.AvatarMove";
  59. private OMV.Vector3 _PIDTarget;
  60. private float _PIDTau;
  61. // public override OMV.Vector3 RawVelocity
  62. // { get { return base.RawVelocity; }
  63. // set {
  64. // if (value != base.RawVelocity)
  65. // Util.PrintCallStack();
  66. // Console.WriteLine("Set rawvel to {0}", value);
  67. // base.RawVelocity = value; }
  68. // }
  69. // Avatars are always complete (in the physics engine sense)
  70. public override bool IsIncomplete { get { return false; } }
  71. public BSCharacter(
  72. uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, bool isFlying)
  73. : base(parent_scene, localID, avName, "BSCharacter")
  74. {
  75. _physicsActorType = (int)ActorTypes.Agent;
  76. RawPosition = pos;
  77. _flying = isFlying;
  78. RawOrientation = OMV.Quaternion.Identity;
  79. RawVelocity = vel;
  80. _buoyancy = ComputeBuoyancyFromFlying(isFlying);
  81. Friction = BSParam.AvatarStandingFriction;
  82. Density = BSParam.AvatarDensity;
  83. // Old versions of ScenePresence passed only the height. If width and/or depth are zero,
  84. // replace with the default values.
  85. _size = size;
  86. if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
  87. if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
  88. // The dimensions of the physical capsule are kept in the scale.
  89. // Physics creates a unit capsule which is scaled by the physics engine.
  90. Scale = ComputeAvatarScale(_size);
  91. // set _avatarVolume and _mass based on capsule size, _density and Scale
  92. ComputeAvatarVolumeAndMass();
  93. DetailLog(
  94. "{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}",
  95. LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos, vel);
  96. // do actual creation in taint time
  97. PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate()
  98. {
  99. DetailLog("{0},BSCharacter.create,taint", LocalID);
  100. // New body and shape into PhysBody and PhysShape
  101. PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this);
  102. // The avatar's movement is controlled by this motor that speeds up and slows down
  103. // the avatar seeking to reach the motor's target speed.
  104. // This motor runs as a prestep action for the avatar so it will keep the avatar
  105. // standing as well as moving. Destruction of the avatar will destroy the pre-step action.
  106. m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName);
  107. PhysicalActors.Add(AvatarMoveActorName, m_moveActor);
  108. SetPhysicalProperties();
  109. IsInitialized = true;
  110. });
  111. return;
  112. }
  113. // called when this character is being destroyed and the resources should be released
  114. public override void Destroy()
  115. {
  116. IsInitialized = false;
  117. base.Destroy();
  118. DetailLog("{0},BSCharacter.Destroy", LocalID);
  119. PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate()
  120. {
  121. PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */);
  122. PhysBody.Clear();
  123. PhysShape.Dereference(PhysScene);
  124. PhysShape = new BSShapeNull();
  125. });
  126. }
  127. private void SetPhysicalProperties()
  128. {
  129. PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
  130. ForcePosition = RawPosition;
  131. // Set the velocity
  132. if (m_moveActor != null)
  133. m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false);
  134. ForceVelocity = RawVelocity;
  135. TargetVelocity = RawVelocity;
  136. // This will enable or disable the flying buoyancy of the avatar.
  137. // Needs to be reset especially when an avatar is recreated after crossing a region boundry.
  138. Flying = _flying;
  139. PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
  140. PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin);
  141. PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
  142. PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
  143. if (BSParam.CcdMotionThreshold > 0f)
  144. {
  145. PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
  146. PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
  147. }
  148. UpdatePhysicalMassProperties(RawMass, false);
  149. // Make so capsule does not fall over
  150. PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
  151. // The avatar mover sets some parameters.
  152. PhysicalActors.Refresh();
  153. PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
  154. PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
  155. // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
  156. PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
  157. PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
  158. // Do this after the object has been added to the world
  159. if (BSParam.AvatarToAvatarCollisionsByDefault)
  160. PhysBody.collisionType = CollisionType.Avatar;
  161. else
  162. PhysBody.collisionType = CollisionType.PhantomToOthersAvatar;
  163. PhysBody.ApplyCollisionMask(PhysScene);
  164. }
  165. public override void RequestPhysicsterseUpdate()
  166. {
  167. base.RequestPhysicsterseUpdate();
  168. }
  169. // No one calls this method so I don't know what it could possibly mean
  170. public override bool Stopped { get { return false; } }
  171. public override OMV.Vector3 Size {
  172. get
  173. {
  174. // Avatar capsule size is kept in the scale parameter.
  175. return _size;
  176. }
  177. set {
  178. // This is how much the avatar size is changing. Positive means getting bigger.
  179. // The avatar altitude must be adjusted for this change.
  180. float heightChange = value.Z - _size.Z;
  181. _size = value;
  182. // Old versions of ScenePresence passed only the height. If width and/or depth are zero,
  183. // replace with the default values.
  184. if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
  185. if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
  186. Scale = ComputeAvatarScale(_size);
  187. ComputeAvatarVolumeAndMass();
  188. DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
  189. LocalID, _size, Scale, Density, _avatarVolume, RawMass);
  190. PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate()
  191. {
  192. if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape)
  193. {
  194. PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
  195. UpdatePhysicalMassProperties(RawMass, true);
  196. // Adjust the avatar's position to account for the increase/decrease in size
  197. ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f);
  198. // Make sure this change appears as a property update event
  199. PhysScene.PE.PushUpdate(PhysBody);
  200. }
  201. });
  202. }
  203. }
  204. public override PrimitiveBaseShape Shape
  205. {
  206. set { BaseShape = value; }
  207. }
  208. public override bool Grabbed {
  209. set { _grabbed = value; }
  210. }
  211. public override bool Selected {
  212. set { _selected = value; }
  213. }
  214. public override bool IsSelected
  215. {
  216. get { return _selected; }
  217. }
  218. public override void CrossingFailure() { return; }
  219. public override void link(PhysicsActor obj) { return; }
  220. public override void delink() { return; }
  221. // Set motion values to zero.
  222. // Do it to the properties so the values get set in the physics engine.
  223. // Push the setting of the values to the viewer.
  224. // Called at taint time!
  225. public override void ZeroMotion(bool inTaintTime)
  226. {
  227. RawVelocity = OMV.Vector3.Zero;
  228. _acceleration = OMV.Vector3.Zero;
  229. _rotationalVelocity = OMV.Vector3.Zero;
  230. // Zero some other properties directly into the physics engine
  231. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
  232. {
  233. if (PhysBody.HasPhysicalBody)
  234. PhysScene.PE.ClearAllForces(PhysBody);
  235. });
  236. }
  237. public override void ZeroAngularMotion(bool inTaintTime)
  238. {
  239. _rotationalVelocity = OMV.Vector3.Zero;
  240. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
  241. {
  242. if (PhysBody.HasPhysicalBody)
  243. {
  244. PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
  245. PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
  246. // The next also get rid of applied linear force but the linear velocity is untouched.
  247. PhysScene.PE.ClearForces(PhysBody);
  248. }
  249. });
  250. }
  251. public override void LockAngularMotion(OMV.Vector3 axis) { return; }
  252. public override OMV.Vector3 Position {
  253. get {
  254. // Don't refetch the position because this function is called a zillion times
  255. // RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
  256. return RawPosition;
  257. }
  258. set {
  259. RawPosition = value;
  260. PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate()
  261. {
  262. DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  263. PositionSanityCheck();
  264. ForcePosition = RawPosition;
  265. });
  266. }
  267. }
  268. public override OMV.Vector3 ForcePosition {
  269. get {
  270. RawPosition = PhysScene.PE.GetPosition(PhysBody);
  271. return RawPosition;
  272. }
  273. set {
  274. RawPosition = value;
  275. if (PhysBody.HasPhysicalBody)
  276. {
  277. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  278. }
  279. }
  280. }
  281. // Check that the current position is sane and, if not, modify the position to make it so.
  282. // Check for being below terrain or on water.
  283. // Returns 'true' of the position was made sane by some action.
  284. private bool PositionSanityCheck()
  285. {
  286. bool ret = false;
  287. // TODO: check for out of bounds
  288. if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
  289. {
  290. // The character is out of the known/simulated area.
  291. // Force the avatar position to be within known. ScenePresence will use the position
  292. // plus the velocity to decide if the avatar is moving out of the region.
  293. RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition);
  294. DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition);
  295. return true;
  296. }
  297. // If below the ground, move the avatar up
  298. float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
  299. if (Position.Z < terrainHeight)
  300. {
  301. DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
  302. RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
  303. ret = true;
  304. }
  305. if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
  306. {
  307. float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
  308. if (Position.Z < waterHeight)
  309. {
  310. RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
  311. ret = true;
  312. }
  313. }
  314. return ret;
  315. }
  316. // A version of the sanity check that also makes sure a new position value is
  317. // pushed back to the physics engine. This routine would be used by anyone
  318. // who is not already pushing the value.
  319. private bool PositionSanityCheck(bool inTaintTime)
  320. {
  321. bool ret = false;
  322. if (PositionSanityCheck())
  323. {
  324. // The new position value must be pushed into the physics engine but we can't
  325. // just assign to "Position" because of potential call loops.
  326. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate()
  327. {
  328. DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  329. ForcePosition = RawPosition;
  330. });
  331. ret = true;
  332. }
  333. return ret;
  334. }
  335. public override float Mass { get { return _mass; } }
  336. // used when we only want this prim's mass and not the linkset thing
  337. public override float RawMass {
  338. get {return _mass; }
  339. }
  340. public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
  341. {
  342. OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
  343. PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia);
  344. }
  345. public override OMV.Vector3 Force {
  346. get { return RawForce; }
  347. set {
  348. RawForce = value;
  349. // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force);
  350. PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate()
  351. {
  352. DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce);
  353. if (PhysBody.HasPhysicalBody)
  354. PhysScene.PE.SetObjectForce(PhysBody, RawForce);
  355. });
  356. }
  357. }
  358. // Avatars don't do vehicles
  359. public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } }
  360. public override void VehicleFloatParam(int param, float value) { }
  361. public override void VehicleVectorParam(int param, OMV.Vector3 value) {}
  362. public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { }
  363. public override void VehicleFlags(int param, bool remove) { }
  364. // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
  365. public override void SetVolumeDetect(int param) { return; }
  366. public override bool IsVolumeDetect { get { return false; } }
  367. public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
  368. public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
  369. // Sets the target in the motor. This starts the changing of the avatar's velocity.
  370. public override OMV.Vector3 TargetVelocity
  371. {
  372. get
  373. {
  374. return base.m_targetVelocity;
  375. }
  376. set
  377. {
  378. DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
  379. m_targetVelocity = value;
  380. OMV.Vector3 targetVel = value;
  381. if (_setAlwaysRun && !_flying)
  382. targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f);
  383. if (m_moveActor != null)
  384. m_moveActor.SetVelocityAndTarget(RawVelocity, targetVel, false /* inTaintTime */);
  385. }
  386. }
  387. // Directly setting velocity means this is what the user really wants now.
  388. public override OMV.Vector3 Velocity {
  389. get { return RawVelocity; }
  390. set {
  391. RawVelocity = value;
  392. OMV.Vector3 vel = RawVelocity;
  393. DetailLog("{0}: set Velocity = {1}", LocalID, value);
  394. PhysScene.TaintedObject(LocalID, "BSCharacter.setVelocity", delegate()
  395. {
  396. if (m_moveActor != null)
  397. m_moveActor.SetVelocityAndTarget(vel, vel, true /* inTaintTime */);
  398. DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, vel);
  399. ForceVelocity = vel;
  400. });
  401. }
  402. }
  403. public override OMV.Vector3 ForceVelocity {
  404. get { return RawVelocity; }
  405. set {
  406. PhysScene.AssertInTaintTime("BSCharacter.ForceVelocity");
  407. // Util.PrintCallStack();
  408. DetailLog("{0}: set ForceVelocity = {1}", LocalID, value);
  409. RawVelocity = value;
  410. PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
  411. PhysScene.PE.Activate(PhysBody, true);
  412. }
  413. }
  414. public override OMV.Vector3 Torque {
  415. get { return RawTorque; }
  416. set { RawTorque = value;
  417. }
  418. }
  419. public override float CollisionScore {
  420. get { return _collisionScore; }
  421. set { _collisionScore = value;
  422. }
  423. }
  424. public override OMV.Vector3 Acceleration {
  425. get { return _acceleration; }
  426. set { _acceleration = value; }
  427. }
  428. public override OMV.Quaternion Orientation {
  429. get { return RawOrientation; }
  430. set {
  431. // Orientation is set zillions of times when an avatar is walking. It's like
  432. // the viewer doesn't trust us.
  433. if (RawOrientation != value)
  434. {
  435. RawOrientation = value;
  436. PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate()
  437. {
  438. // Bullet assumes we know what we are doing when forcing orientation
  439. // so it lets us go against all the rules and just compensates for them later.
  440. // This forces rotation to be only around the Z axis and doesn't change any of the other axis.
  441. // This keeps us from flipping the capsule over which the veiwer does not understand.
  442. float oRoll, oPitch, oYaw;
  443. RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
  444. OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
  445. // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
  446. // LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
  447. // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
  448. ForceOrientation = trimmedOrientation;
  449. });
  450. }
  451. }
  452. }
  453. // Go directly to Bullet to get/set the value.
  454. public override OMV.Quaternion ForceOrientation
  455. {
  456. get
  457. {
  458. RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
  459. return RawOrientation;
  460. }
  461. set
  462. {
  463. RawOrientation = value;
  464. if (PhysBody.HasPhysicalBody)
  465. {
  466. // RawPosition = PhysicsScene.PE.GetPosition(BSBody);
  467. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  468. }
  469. }
  470. }
  471. public override int PhysicsActorType {
  472. get { return _physicsActorType; }
  473. set { _physicsActorType = value;
  474. }
  475. }
  476. public override bool IsPhysical {
  477. get { return _isPhysical; }
  478. set { _isPhysical = value;
  479. }
  480. }
  481. public override bool IsSolid {
  482. get { return true; }
  483. }
  484. public override bool IsStatic {
  485. get { return false; }
  486. }
  487. public override bool IsPhysicallyActive {
  488. get { return true; }
  489. }
  490. public override bool Flying {
  491. get { return _flying; }
  492. set {
  493. _flying = value;
  494. // simulate flying by changing the effect of gravity
  495. Buoyancy = ComputeBuoyancyFromFlying(_flying);
  496. }
  497. }
  498. // Flying is implimented by changing the avatar's buoyancy.
  499. // Would this be done better with a vehicle type?
  500. private float ComputeBuoyancyFromFlying(bool ifFlying) {
  501. return ifFlying ? 1f : 0f;
  502. }
  503. public override bool
  504. SetAlwaysRun {
  505. get { return _setAlwaysRun; }
  506. set { _setAlwaysRun = value; }
  507. }
  508. public override bool ThrottleUpdates {
  509. get { return _throttleUpdates; }
  510. set { _throttleUpdates = value; }
  511. }
  512. public override bool FloatOnWater {
  513. set {
  514. _floatOnWater = value;
  515. PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate()
  516. {
  517. if (PhysBody.HasPhysicalBody)
  518. {
  519. if (_floatOnWater)
  520. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  521. else
  522. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  523. }
  524. });
  525. }
  526. }
  527. public override OMV.Vector3 RotationalVelocity {
  528. get { return _rotationalVelocity; }
  529. set { _rotationalVelocity = value; }
  530. }
  531. public override OMV.Vector3 ForceRotationalVelocity {
  532. get { return _rotationalVelocity; }
  533. set { _rotationalVelocity = value; }
  534. }
  535. public override bool Kinematic {
  536. get { return _kinematic; }
  537. set { _kinematic = value; }
  538. }
  539. // neg=fall quickly, 0=1g, 1=0g, pos=float up
  540. public override float Buoyancy {
  541. get { return _buoyancy; }
  542. set { _buoyancy = value;
  543. PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate()
  544. {
  545. DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
  546. ForceBuoyancy = _buoyancy;
  547. });
  548. }
  549. }
  550. public override float ForceBuoyancy {
  551. get { return _buoyancy; }
  552. set {
  553. PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy");
  554. _buoyancy = value;
  555. DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
  556. // Buoyancy is faked by changing the gravity applied to the object
  557. float grav = BSParam.Gravity * (1f - _buoyancy);
  558. Gravity = new OMV.Vector3(0f, 0f, grav);
  559. if (PhysBody.HasPhysicalBody)
  560. PhysScene.PE.SetGravity(PhysBody, Gravity);
  561. }
  562. }
  563. // Used for MoveTo
  564. public override OMV.Vector3 PIDTarget {
  565. set { _PIDTarget = value; }
  566. }
  567. public override bool PIDActive { get; set; }
  568. public override float PIDTau {
  569. set { _PIDTau = value; }
  570. }
  571. public override void AddForce(OMV.Vector3 force, bool pushforce)
  572. {
  573. // Since this force is being applied in only one step, make this a force per second.
  574. OMV.Vector3 addForce = force / PhysScene.LastTimeStep;
  575. AddForce(addForce, pushforce, false);
  576. }
  577. public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
  578. if (force.IsFinite())
  579. {
  580. OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
  581. // DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce);
  582. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate()
  583. {
  584. // Bullet adds this central force to the total force for this tick
  585. // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
  586. if (PhysBody.HasPhysicalBody)
  587. {
  588. PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
  589. }
  590. });
  591. }
  592. else
  593. {
  594. m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
  595. return;
  596. }
  597. }
  598. public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
  599. }
  600. public override void SetMomentum(OMV.Vector3 momentum) {
  601. }
  602. private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
  603. {
  604. OMV.Vector3 newScale = size;
  605. // Bullet's capsule total height is the "passed height + radius * 2";
  606. // The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1)
  607. // The number we pass in for 'scaling' is the multiplier to get that base
  608. // shape to be the size desired.
  609. // So, when creating the scale for the avatar height, we take the passed height
  610. // (size.Z) and remove the caps.
  611. // An oddity of the Bullet capsule implementation is that it presumes the Y
  612. // dimension is the radius of the capsule. Even though some of the code allows
  613. // for a asymmetrical capsule, other parts of the code presume it is cylindrical.
  614. // Scale is multiplier of radius with one of "0.5"
  615. float heightAdjust = BSParam.AvatarHeightMidFudge;
  616. if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f)
  617. {
  618. const float AVATAR_LOW = 1.1f;
  619. const float AVATAR_MID = 1.775f; // 1.87f
  620. const float AVATAR_HI = 2.45f;
  621. // An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m.
  622. float midHeightOffset = size.Z - AVATAR_MID;
  623. if (midHeightOffset < 0f)
  624. {
  625. // Small avatar. Add the adjustment based on the distance from midheight
  626. heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge;
  627. }
  628. else
  629. {
  630. // Large avatar. Add the adjustment based on the distance from midheight
  631. heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge;
  632. }
  633. }
  634. if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
  635. {
  636. newScale.X = size.X / 2f;
  637. newScale.Y = size.Y / 2f;
  638. // The total scale height is the central cylindar plus the caps on the two ends.
  639. newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f;
  640. }
  641. else
  642. {
  643. newScale.Z = size.Z + heightAdjust;
  644. }
  645. // m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale);
  646. // If smaller than the endcaps, just fake like we're almost that small
  647. if (newScale.Z < 0)
  648. newScale.Z = 0.1f;
  649. DetailLog("{0},BSCharacter.ComputerAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}",
  650. LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale);
  651. return newScale;
  652. }
  653. // set _avatarVolume and _mass based on capsule size, _density and Scale
  654. private void ComputeAvatarVolumeAndMass()
  655. {
  656. _avatarVolume = (float)(
  657. Math.PI
  658. * Size.X / 2f
  659. * Size.Y / 2f // the area of capsule cylinder
  660. * Size.Z // times height of capsule cylinder
  661. + 1.33333333f
  662. * Math.PI
  663. * Size.X / 2f
  664. * Math.Min(Size.X, Size.Y) / 2
  665. * Size.Y / 2f // plus the volume of the capsule end caps
  666. );
  667. _mass = Density * BSParam.DensityScaleFactor * _avatarVolume;
  668. }
  669. // The physics engine says that properties have updated. Update same and inform
  670. // the world that things have changed.
  671. public override void UpdateProperties(EntityProperties entprop)
  672. {
  673. // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
  674. TriggerPreUpdatePropertyAction(ref entprop);
  675. RawPosition = entprop.Position;
  676. RawOrientation = entprop.Rotation;
  677. // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
  678. // and will send agent updates to the clients if velocity changes by more than
  679. // 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
  680. // extra updates.
  681. //
  682. // XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to
  683. // avatar movement rather than removes it. The larger the threshold, the bigger the jitter.
  684. // This is most noticeable in level flight and can be seen with
  685. // the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower
  686. // bound and an upper bound, where the difference between the two is enough to trigger a large delta v update
  687. // and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?)
  688. // has not yet been identified.
  689. //
  690. // If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra
  691. // updates are not triggered in ScenePresence.SendTerseUpdateToAllClients().
  692. // if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
  693. RawVelocity = entprop.Velocity;
  694. _acceleration = entprop.Acceleration;
  695. _rotationalVelocity = entprop.RotationalVelocity;
  696. // Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
  697. if (PositionSanityCheck(true))
  698. {
  699. DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
  700. entprop.Position = RawPosition;
  701. }
  702. // remember the current and last set values
  703. LastEntityProperties = CurrentEntityProperties;
  704. CurrentEntityProperties = entprop;
  705. // Tell the linkset about value changes
  706. // Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
  707. // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
  708. // PhysScene.PostUpdate(this);
  709. DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
  710. LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity);
  711. }
  712. }
  713. }