1
0

BSPhysObject.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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.Text;
  30. using OMV = OpenMetaverse;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.PhysicsModules.SharedBase;
  33. namespace OpenSim.Region.PhysicsModule.BulletS
  34. {
  35. /*
  36. * Class to wrap all objects.
  37. * The rest of BulletSim doesn't need to keep checking for avatars or prims
  38. * unless the difference is significant.
  39. *
  40. * Variables in the physicsl objects are in three forms:
  41. * VariableName: used by the simulator and performs taint operations, etc
  42. * RawVariableName: direct reference to the BulletSim storage for the variable value
  43. * ForceVariableName: direct reference (store and fetch) to the value in the physics engine.
  44. * The last one should only be referenced in taint-time.
  45. */
  46. /*
  47. * As of 20121221, the following are the call sequences (going down) for different script physical functions:
  48. * llApplyImpulse llApplyRotImpulse llSetTorque llSetForce
  49. * SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce
  50. * SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse
  51. * PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v
  52. * BS.ApplyCentralForce BS.ApplyTorque
  53. */
  54. // Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc.
  55. public enum UpdatedProperties : uint
  56. {
  57. Position = 1 << 0,
  58. Orientation = 1 << 1,
  59. Velocity = 1 << 2,
  60. Acceleration = 1 << 3,
  61. RotationalVelocity = 1 << 4,
  62. EntPropUpdates = Position | Orientation | Velocity | Acceleration | RotationalVelocity,
  63. }
  64. public abstract class BSPhysObject : PhysicsActor
  65. {
  66. protected BSPhysObject()
  67. {
  68. }
  69. protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName)
  70. {
  71. IsInitialized = false;
  72. PhysScene = parentScene;
  73. LocalID = localID;
  74. PhysObjectName = name;
  75. Name = name; // PhysicsActor also has the name of the object. Someday consolidate.
  76. TypeName = typeName;
  77. // Oddity if object is destroyed and recreated very quickly it could still have the old body.
  78. if (!PhysBody.HasPhysicalBody)
  79. PhysBody = new BulletBody(localID);
  80. // Clean out anything that might be in the physical actor list.
  81. // Again, a workaround for destroying and recreating an object very quickly.
  82. PhysicalActors.Dispose();
  83. UserSetCenterOfMassDisplacement = null;
  84. PrimAssetState = PrimAssetCondition.Unknown;
  85. // Initialize variables kept in base.
  86. // Beware that these cause taints to be queued whch can cause race conditions on startup.
  87. GravModifier = 1.0f;
  88. Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity);
  89. HoverActive = false;
  90. // Default material type. Also sets Friction, Restitution and Density.
  91. SetMaterial((int)MaterialAttributes.Material.Wood);
  92. CollisionsLastTickStep = -1;
  93. SubscribedEventsMs = 0;
  94. // Crazy values that will never be true
  95. CollidingStep = BSScene.NotASimulationStep;
  96. CollidingGroundStep = BSScene.NotASimulationStep;
  97. CollisionAccumulation = BSScene.NotASimulationStep;
  98. ColliderIsMoving = false;
  99. CollisionScore = 0;
  100. // All axis free.
  101. LockedLinearAxis = LockedAxisFree;
  102. LockedAngularAxis = LockedAxisFree;
  103. DisableDeactivation = false; // by default, objects can be deactivated (ie, not checked for collisions)
  104. }
  105. // Tell the object to clean up.
  106. public virtual void Destroy()
  107. {
  108. PhysicalActors.Enable(false);
  109. PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate()
  110. {
  111. PhysicalActors.Dispose();
  112. });
  113. }
  114. public BSScene PhysScene { get; protected set; }
  115. // public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor
  116. public string PhysObjectName { get; protected set; }
  117. public string TypeName { get; protected set; }
  118. // Set to 'true' when the object is completely initialized.
  119. // This mostly prevents property updates and collisions until the object is completely here.
  120. public bool IsInitialized { get; protected set; }
  121. // Set to 'true' if an object (mesh/linkset/sculpty) is not completely constructed.
  122. // This test is used to prevent some updates to the object when it only partially exists.
  123. // There are several reasons and object might be incomplete:
  124. // Its underlying mesh/sculpty is an asset which must be fetched from the asset store
  125. // It is a linkset who is being added to or removed from
  126. // It is changing state (static to physical, for instance) which requires rebuilding
  127. // This is a computed value based on the underlying physical object construction
  128. abstract public bool IsIncomplete { get; }
  129. // Return the object mass without calculating it or having side effects
  130. public abstract float RawMass { get; }
  131. // Set the raw mass but also update physical mass properties (inertia, ...)
  132. // 'inWorld' true if the object has already been added to the dynamic world.
  133. public abstract void UpdatePhysicalMassProperties(float mass, bool inWorld);
  134. // The gravity being applied to the object. A function of default grav, GravityModifier and Buoyancy.
  135. public virtual OMV.Vector3 Gravity { get; set; }
  136. // The last value calculated for the prim's inertia
  137. public OMV.Vector3 Inertia { get; set; }
  138. // Reference to the physical body (btCollisionObject) of this object
  139. public BulletBody PhysBody = new BulletBody(0);
  140. // Reference to the physical shape (btCollisionShape) of this object
  141. public BSShape PhysShape = new BSShapeNull();
  142. // The physical representation of the prim might require an asset fetch.
  143. // The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'.
  144. public enum PrimAssetCondition
  145. {
  146. Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched
  147. }
  148. public PrimAssetCondition PrimAssetState { get; set; }
  149. public virtual bool AssetFailed()
  150. {
  151. return ( (this.PrimAssetState == PrimAssetCondition.FailedAssetFetch)
  152. || (this.PrimAssetState == PrimAssetCondition.FailedMeshing) );
  153. }
  154. // The objects base shape information. Null if not a prim type shape.
  155. public PrimitiveBaseShape BaseShape { get; protected set; }
  156. // When the physical properties are updated, an EntityProperty holds the update values.
  157. // Keep the current and last EntityProperties to enable computation of differences
  158. // between the current update and the previous values.
  159. public EntityProperties CurrentEntityProperties { get; set; }
  160. public EntityProperties LastEntityProperties { get; set; }
  161. public virtual OMV.Vector3 Scale { get; set; }
  162. // It can be confusing for an actor to know if it should move or update an object
  163. // depeneding on the setting of 'selected', 'physical, ...
  164. // This flag is the true test -- if true, the object is being acted on in the physical world
  165. public abstract bool IsPhysicallyActive { get; }
  166. // Detailed state of the object.
  167. public abstract bool IsSolid { get; }
  168. public abstract bool IsStatic { get; }
  169. public abstract bool IsSelected { get; }
  170. public abstract bool IsVolumeDetect { get; }
  171. // Materialness
  172. public MaterialAttributes.Material Material { get; private set; }
  173. public override void SetMaterial(int material)
  174. {
  175. Material = (MaterialAttributes.Material)material;
  176. // Setting the material sets the material attributes also.
  177. // TODO: decide if this is necessary -- the simulator does this.
  178. MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false);
  179. Friction = matAttrib.friction;
  180. Restitution = matAttrib.restitution;
  181. Density = matAttrib.density;
  182. // DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density);
  183. }
  184. public override float Density
  185. {
  186. get
  187. {
  188. return base.Density;
  189. }
  190. set
  191. {
  192. DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value);
  193. base.Density = value;
  194. }
  195. }
  196. // Stop all physical motion.
  197. public abstract void ZeroMotion(bool inTaintTime);
  198. public abstract void ZeroAngularMotion(bool inTaintTime);
  199. // Update the physical location and motion of the object. Called with data from Bullet.
  200. public abstract void UpdateProperties(EntityProperties entprop);
  201. // The position value as known by BulletSim. Does not effect the physics engine.
  202. public virtual OMV.Vector3 RawPosition { get; set; }
  203. // Set position in BulletSim and the physics engined to a value immediately. Must be called at taint time.
  204. public abstract OMV.Vector3 ForcePosition { get; set; }
  205. // The orientation value as known by BulletSim. Does not effect the physics engine.
  206. public virtual OMV.Quaternion RawOrientation { get; set; }
  207. // Set orientation in BulletSim and the physics engine to a value immediately. Must be called at taint time.
  208. public abstract OMV.Quaternion ForceOrientation { get; set; }
  209. // The velocity value as known by BulletSim. Does not effect the physics engine.
  210. public virtual OMV.Vector3 RawVelocity { get; set; }
  211. // Set velocity in BulletSim and the physics engined to a value immediately. Must be called at taint time.
  212. public abstract OMV.Vector3 ForceVelocity { get; set; }
  213. // The rotational velocity value as known by BulletSim. Does not effect the physics engine.
  214. public OMV.Vector3 RawRotationalVelocity { get; set; }
  215. // RawForce is a constant force applied to object (see Force { set; } )
  216. public OMV.Vector3 RawForce { get; set; }
  217. public OMV.Vector3 RawTorque { get; set; }
  218. public override void AddAngularForce(OMV.Vector3 force, bool pushforce)
  219. {
  220. AddAngularForce(false, force);
  221. }
  222. public abstract void AddAngularForce(bool inTaintTime, OMV.Vector3 force);
  223. public abstract void AddForce(bool inTaintTime, OMV.Vector3 force);
  224. // PhysicsActor.Velocity
  225. public override OMV.Vector3 Velocity
  226. {
  227. get { return RawVelocity; }
  228. set
  229. {
  230. // This sets the velocity now. BSCharacter will override to clear target velocity
  231. // before calling this.
  232. RawVelocity = value;
  233. PhysScene.TaintedObject(LocalID, TypeName + ".SetVelocity", delegate () {
  234. // DetailLog("{0},BSPhysObject.Velocity.set,vel={1}", LocalID, RawVelocity);
  235. ForceVelocity = RawVelocity;
  236. });
  237. }
  238. }
  239. // PhysicsActor.SetMomentum
  240. // All the physics engines use this as a way of forcing the velocity to something.
  241. // BSCharacter overrides this so it can set the target velocity to zero before calling this.
  242. public override void SetMomentum(OMV.Vector3 momentum)
  243. {
  244. this.Velocity = momentum;
  245. }
  246. public override OMV.Vector3 RotationalVelocity {
  247. get {
  248. return RawRotationalVelocity;
  249. }
  250. set {
  251. RawRotationalVelocity = value;
  252. Util.ClampV(RawRotationalVelocity, BSParam.MaxAngularVelocity);
  253. // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity);
  254. PhysScene.TaintedObject(LocalID, TypeName + ".setRotationalVelocity", delegate()
  255. {
  256. ForceRotationalVelocity = RawRotationalVelocity;
  257. });
  258. }
  259. }
  260. public OMV.Vector3 ForceRotationalVelocity {
  261. get {
  262. return RawRotationalVelocity;
  263. }
  264. set {
  265. RawRotationalVelocity = Util.ClampV(value, BSParam.MaxAngularVelocity);
  266. if (PhysBody.HasPhysicalBody)
  267. {
  268. DetailLog("{0},{1}.ForceRotationalVel,taint,rotvel={2}", LocalID, TypeName, RawRotationalVelocity);
  269. PhysScene.PE.SetAngularVelocity(PhysBody, RawRotationalVelocity);
  270. // PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity);
  271. ActivateIfPhysical(false);
  272. }
  273. }
  274. }
  275. public abstract float ForceBuoyancy { get; set; }
  276. public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; }
  277. public override bool PIDActive
  278. {
  279. get { return MoveToTargetActive; }
  280. set { MoveToTargetActive = value; }
  281. }
  282. public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } }
  283. public override float PIDTau { set { MoveToTargetTau = value; } }
  284. public bool MoveToTargetActive { get; set; }
  285. public OMV.Vector3 MoveToTargetTarget { get; set; }
  286. public float MoveToTargetTau { get; set; }
  287. // Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z
  288. public override bool PIDHoverActive {get {return HoverActive;} set { HoverActive = value; } }
  289. public override float PIDHoverHeight { set { HoverHeight = value; } }
  290. public override PIDHoverType PIDHoverType { set { HoverType = value; } }
  291. public override float PIDHoverTau { set { HoverTau = value; } }
  292. public bool HoverActive { get; set; }
  293. public float HoverHeight { get; set; }
  294. public PIDHoverType HoverType { get; set; }
  295. public float HoverTau { get; set; }
  296. // For RotLookAt
  297. public override OMV.Quaternion APIDTarget { set { return; } }
  298. public override bool APIDActive { set { return; } }
  299. public override float APIDStrength { set { return; } }
  300. public override float APIDDamping { set { return; } }
  301. // The current velocity forward
  302. public virtual float ForwardSpeed
  303. {
  304. get
  305. {
  306. OMV.Vector3 characterOrientedVelocity = RawVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
  307. return characterOrientedVelocity.X;
  308. }
  309. }
  310. // The forward speed we are trying to achieve (TargetVelocity)
  311. public virtual float TargetVelocitySpeed
  312. {
  313. get
  314. {
  315. OMV.Vector3 characterOrientedVelocity = TargetVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
  316. return characterOrientedVelocity.X;
  317. }
  318. }
  319. // The user can optionally set the center of mass. The user's setting will override any
  320. // computed center-of-mass (like in linksets).
  321. // Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass.
  322. public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; }
  323. // Set 'true' if physical object should never be deactivated
  324. public bool DisableDeactivation;
  325. public OMV.Vector3 LockedLinearAxis; // zero means locked. one means free.
  326. public OMV.Vector3 LockedAngularAxis; // zero means locked. one means free.
  327. public const float FreeAxis = 1f;
  328. public const float LockedAxis = 0f;
  329. public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // All axis are free
  330. // If an axis is locked (flagged above) then the limits of that axis are specified here.
  331. // Linear axis limits are relative to the object's starting coordinates.
  332. // Angular limits are limited to -PI to +PI
  333. public OMV.Vector3 LockedLinearAxisLow;
  334. public OMV.Vector3 LockedLinearAxisHigh;
  335. public OMV.Vector3 LockedAngularAxisLow;
  336. public OMV.Vector3 LockedAngularAxisHigh;
  337. // Enable physical actions. Bullet will keep sleeping non-moving physical objects so
  338. // they need waking up when parameters are changed.
  339. // Called in taint-time!!
  340. public void ActivateIfPhysical(bool forceIt)
  341. {
  342. if (PhysBody.HasPhysicalBody)
  343. {
  344. if (IsPhysical)
  345. {
  346. // Physical objects might need activating
  347. PhysScene.PE.Activate(PhysBody, forceIt);
  348. }
  349. else
  350. {
  351. // Clear the collision cache since we've changed some properties.
  352. PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody);
  353. }
  354. }
  355. }
  356. // 'actors' act on the physical object to change or constrain its motion. These can range from
  357. // hovering to complex vehicle motion.
  358. // May be called at non-taint time as this just adds the actor to the action list and the real
  359. // work is done during the simulation step.
  360. // Note that, if the actor is already in the list and we are disabling same, the actor is just left
  361. // in the list disabled.
  362. public delegate BSActor CreateActor();
  363. public void EnableActor(bool enableActor, string actorName, CreateActor creator)
  364. {
  365. lock (PhysicalActors)
  366. {
  367. BSActor theActor;
  368. if (PhysicalActors.TryGetActor(actorName, out theActor))
  369. {
  370. // The actor already exists so just turn it on or off
  371. DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor);
  372. theActor.Enabled = enableActor;
  373. }
  374. else
  375. {
  376. // The actor does not exist. If it should, create it.
  377. if (enableActor)
  378. {
  379. DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName);
  380. theActor = creator();
  381. PhysicalActors.Add(actorName, theActor);
  382. theActor.Enabled = true;
  383. }
  384. else
  385. {
  386. DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName);
  387. }
  388. }
  389. }
  390. }
  391. #region Collisions
  392. // Requested number of milliseconds between collision events. Zero means disabled.
  393. protected int SubscribedEventsMs { get; set; }
  394. // Given subscription, the time that a collision may be passed up
  395. protected int NextCollisionOkTime { get; set; }
  396. // The simulation step that last had a collision
  397. protected long CollidingStep { get; set; }
  398. // The simulation step that last had a collision with the ground
  399. protected long CollidingGroundStep { get; set; }
  400. // The simulation step that last collided with an object
  401. protected long CollidingObjectStep { get; set; }
  402. // The collision flags we think are set in Bullet
  403. protected CollisionFlags CurrentCollisionFlags { get; set; }
  404. // On a collision, check the collider and remember if the last collider was moving
  405. // Used to modify the standing of avatars (avatars on stationary things stand still)
  406. public bool ColliderIsMoving;
  407. // 'true' if the last collider was a volume detect object
  408. public bool ColliderIsVolumeDetect;
  409. // Used by BSCharacter to manage standing (and not slipping)
  410. public bool IsStationary;
  411. // Count of collisions for this object
  412. protected long CollisionAccumulation { get; set; }
  413. public override bool IsColliding {
  414. get { return (CollidingStep == PhysScene.SimulationStep); }
  415. set {
  416. if (value)
  417. CollidingStep = PhysScene.SimulationStep;
  418. else
  419. CollidingStep = BSScene.NotASimulationStep;
  420. }
  421. }
  422. // Complex objects (like linksets) need to know if there is a collision on any part of
  423. // their shape. 'IsColliding' has an existing definition of reporting a collision on
  424. // only this specific prim or component of linksets.
  425. // 'HasSomeCollision' is defined as reporting if there is a collision on any part of
  426. // the complex body that this prim is the root of.
  427. public virtual bool HasSomeCollision
  428. {
  429. get { return IsColliding; }
  430. set { IsColliding = value; }
  431. }
  432. public override bool CollidingGround {
  433. get { return (CollidingGroundStep == PhysScene.SimulationStep); }
  434. set
  435. {
  436. if (value)
  437. CollidingGroundStep = PhysScene.SimulationStep;
  438. else
  439. CollidingGroundStep = BSScene.NotASimulationStep;
  440. }
  441. }
  442. public override bool CollidingObj {
  443. get { return (CollidingObjectStep == PhysScene.SimulationStep); }
  444. set {
  445. if (value)
  446. CollidingObjectStep = PhysScene.SimulationStep;
  447. else
  448. CollidingObjectStep = BSScene.NotASimulationStep;
  449. }
  450. }
  451. // The collisions that have been collected for the next collision reporting (throttled by subscription)
  452. protected CollisionEventUpdate CollisionCollection = new CollisionEventUpdate();
  453. // This is the collision collection last reported to the Simulator.
  454. public CollisionEventUpdate CollisionsLastReported = new CollisionEventUpdate();
  455. // Remember the collisions recorded in the last tick for fancy collision checking
  456. // (like a BSCharacter walking up stairs).
  457. public CollisionEventUpdate CollisionsLastTick = new CollisionEventUpdate();
  458. private long CollisionsLastTickStep = -1;
  459. // The simulation step is telling this object about a collision.
  460. // I'm the 'collider', the thing I'm colliding with is the 'collidee'.
  461. // Return 'true' if a collision was processed and should be sent up.
  462. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision.
  463. // Called at taint time from within the Step() function
  464. public virtual bool Collide(BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
  465. {
  466. bool ret = false;
  467. // if 'collidee' is null, that means it is terrain
  468. uint collideeLocalID = (collidee == null) ? BSScene.TERRAIN_ID : collidee.LocalID;
  469. // All terrain goes by the TERRAIN_ID id when passed up as a collision
  470. if (collideeLocalID <= PhysScene.TerrainManager.HighestTerrainID) {
  471. collideeLocalID = BSScene.TERRAIN_ID;
  472. }
  473. // The following lines make IsColliding(), CollidingGround() and CollidingObj work
  474. CollidingStep = PhysScene.SimulationStep;
  475. if (collideeLocalID == BSScene.TERRAIN_ID)
  476. {
  477. CollidingGroundStep = PhysScene.SimulationStep;
  478. }
  479. else
  480. {
  481. CollidingObjectStep = PhysScene.SimulationStep;
  482. }
  483. CollisionAccumulation++;
  484. // For movement tests, if the collider is me, remember if we are colliding with an object that is moving.
  485. // Here the 'collider'/'collidee' thing gets messed up. In the larger context, when something is checking
  486. // if the thing it is colliding with is moving, for instance, it asks if the its collider is moving.
  487. ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero || collidee.RotationalVelocity != OMV.Vector3.Zero) : false;
  488. ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false;
  489. // Make a collection of the collisions that happened the last simulation tick.
  490. // This is different than the collection created for sending up to the simulator as it is cleared every tick.
  491. if (CollisionsLastTickStep != PhysScene.SimulationStep)
  492. {
  493. CollisionsLastTick = new CollisionEventUpdate();
  494. CollisionsLastTickStep = PhysScene.SimulationStep;
  495. }
  496. CollisionsLastTick.AddCollider(collideeLocalID, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
  497. // If someone has subscribed for collision events log the collision so it will be reported up
  498. if (SubscribedEvents()) {
  499. ContactPoint newContact = new ContactPoint(contactPoint, contactNormal, pentrationDepth);
  500. // Collision sound requires a velocity to know it should happen. This is a lot of computation for a little used feature.
  501. OMV.Vector3 relvel = OMV.Vector3.Zero;
  502. if (IsPhysical)
  503. relvel = RawVelocity;
  504. if (collidee != null && collidee.IsPhysical)
  505. relvel -= collidee.RawVelocity;
  506. newContact.RelativeSpeed = -OMV.Vector3.Dot(relvel, contactNormal);
  507. // DetailLog("{0},{1}.Collision.AddCollider,vel={2},contee.vel={3},relvel={4},relspeed={5}",
  508. // LocalID, TypeName, RawVelocity, (collidee == null ? OMV.Vector3.Zero : collidee.RawVelocity), relvel, newContact.RelativeSpeed);
  509. lock (PhysScene.CollisionLock)
  510. {
  511. CollisionCollection.AddCollider(collideeLocalID, newContact);
  512. }
  513. DetailLog("{0},{1}.Collision.AddCollider,call,with={2},point={3},normal={4},depth={5},speed={6},colliderMoving={7}",
  514. LocalID, TypeName, collideeLocalID, contactPoint, contactNormal, pentrationDepth,
  515. newContact.RelativeSpeed, ColliderIsMoving);
  516. ret = true;
  517. }
  518. return ret;
  519. }
  520. // Send the collected collisions into the simulator.
  521. // Called at taint time from within the Step() function thus no locking problems
  522. // with CollisionCollection and ObjectsWithNoMoreCollisions.
  523. // Called with BSScene.CollisionLock locked to protect the collision lists.
  524. // Return 'true' if there were some actual collisions passed up
  525. public virtual bool SendCollisions()
  526. {
  527. bool ret = true;
  528. // If no collisions this call but there were collisions last call, force the collision
  529. // event to be happen right now so quick collision_end.
  530. bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0);
  531. // throttle the collisions to the number of milliseconds specified in the subscription
  532. if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime))
  533. {
  534. NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs;
  535. // We are called if we previously had collisions. If there are no collisions
  536. // this time, send up one last empty event so OpenSim can sense collision end.
  537. if (CollisionCollection.Count == 0)
  538. {
  539. // If I have no collisions this time, remove me from the list of objects with collisions.
  540. ret = false;
  541. }
  542. DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count);
  543. base.SendCollisionUpdate(CollisionCollection);
  544. // Remember the collisions from this tick for some collision specific processing.
  545. CollisionsLastReported = CollisionCollection;
  546. // The CollisionCollection instance is passed around in the simulator.
  547. // Make sure we don't have a handle to that one and that a new one is used for next time.
  548. // This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here,
  549. // a race condition is created for the other users of this instance.
  550. CollisionCollection = new CollisionEventUpdate();
  551. }
  552. return ret;
  553. }
  554. // Subscribe for collision events.
  555. // Parameter is the millisecond rate the caller wishes collision events to occur.
  556. public override void SubscribeEvents(int ms) {
  557. // DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms);
  558. SubscribedEventsMs = ms;
  559. if (ms > 0)
  560. {
  561. // make sure first collision happens
  562. NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs);
  563. PhysScene.TaintedObject(LocalID, TypeName+".SubscribeEvents", delegate()
  564. {
  565. if (PhysBody.HasPhysicalBody)
  566. {
  567. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  568. DetailLog("{0},{1}.SubscribeEvents,setting collision. ms={2}, collisionFlags={3:x}",
  569. LocalID, TypeName, SubscribedEventsMs, CurrentCollisionFlags);
  570. }
  571. });
  572. }
  573. else
  574. {
  575. // Subscribing for zero or less is the same as unsubscribing
  576. UnSubscribeEvents();
  577. }
  578. }
  579. public override void UnSubscribeEvents() {
  580. // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName);
  581. SubscribedEventsMs = 0;
  582. PhysScene.TaintedObject(LocalID, TypeName+".UnSubscribeEvents", delegate()
  583. {
  584. // Make sure there is a body there because sometimes destruction happens in an un-ideal order.
  585. if (PhysBody.HasPhysicalBody)
  586. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  587. });
  588. }
  589. // Return 'true' if the simulator wants collision events
  590. public override bool SubscribedEvents() {
  591. return (SubscribedEventsMs > 0);
  592. }
  593. // Because 'CollisionScore' is called many times while sorting, it should not be recomputed
  594. // each time called. So this is built to be light weight for each collision and to do
  595. // all the processing when the user asks for the info.
  596. public void ComputeCollisionScore()
  597. {
  598. // Scale the collision count by the time since the last collision.
  599. // The "+1" prevents dividing by zero.
  600. long timeAgo = PhysScene.SimulationStep - CollidingStep + 1;
  601. CollisionScore = CollisionAccumulation / timeAgo;
  602. }
  603. public override float CollisionScore { get; set; }
  604. #endregion // Collisions
  605. #region Per Simulation Step actions
  606. public BSActorCollection PhysicalActors = new BSActorCollection();
  607. // When an update to the physical properties happens, this event is fired to let
  608. // different actors to modify the update before it is passed around
  609. public delegate void PreUpdatePropertyAction(ref EntityProperties entprop);
  610. public event PreUpdatePropertyAction OnPreUpdateProperty;
  611. protected void TriggerPreUpdatePropertyAction(ref EntityProperties entprop)
  612. {
  613. PreUpdatePropertyAction actions = OnPreUpdateProperty;
  614. if (actions != null)
  615. actions(ref entprop);
  616. }
  617. #endregion // Per Simulation Step actions
  618. // High performance detailed logging routine used by the physical objects.
  619. protected void DetailLog(string msg, params Object[] args)
  620. {
  621. if (PhysScene.PhysicsLogging.Enabled)
  622. PhysScene.DetailLog(msg, args);
  623. }
  624. }
  625. }