BSCharacter.cs 35 KB

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