BSPrim.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  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.Reflection;
  29. using System.Collections.Generic;
  30. using System.Xml;
  31. using log4net;
  32. using OMV = OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Physics.Manager;
  35. using OpenSim.Region.Physics.ConvexDecompositionDotNet;
  36. namespace OpenSim.Region.Physics.BulletSPlugin
  37. {
  38. [Serializable]
  39. public class BSPrim : BSPhysObject
  40. {
  41. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. private static readonly string LogHeader = "[BULLETS PRIM]";
  43. // _size is what the user passed. Scale is what we pass to the physics engine with the mesh.
  44. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user
  45. private bool _grabbed;
  46. private bool _isSelected;
  47. private bool _isVolumeDetect;
  48. private float _mass; // the mass of this object
  49. private OMV.Vector3 _acceleration;
  50. private int _physicsActorType;
  51. private bool _isPhysical;
  52. private bool _flying;
  53. private bool _setAlwaysRun;
  54. private bool _throttleUpdates;
  55. private bool _floatOnWater;
  56. private OMV.Vector3 _rotationalVelocity;
  57. private bool _kinematic;
  58. private float _buoyancy;
  59. private int CrossingFailures { get; set; }
  60. // Keep a handle to the vehicle actor so it is easy to set parameters on same.
  61. public const string VehicleActorName = "BasicVehicle";
  62. // Parameters for the hover actor
  63. public const string HoverActorName = "BSPrim.HoverActor";
  64. // Parameters for the axis lock actor
  65. public const String LockedAxisActorName = "BSPrim.LockedAxis";
  66. // Parameters for the move to target actor
  67. public const string MoveToTargetActorName = "BSPrim.MoveToTargetActor";
  68. // Parameters for the setForce and setTorque actors
  69. public const string SetForceActorName = "BSPrim.SetForceActor";
  70. public const string SetTorqueActorName = "BSPrim.SetTorqueActor";
  71. public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size,
  72. OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
  73. : base(parent_scene, localID, primName, "BSPrim")
  74. {
  75. // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID);
  76. _physicsActorType = (int)ActorTypes.Prim;
  77. RawPosition = pos;
  78. _size = size;
  79. Scale = size; // prims are the size the user wants them to be (different for BSCharactes).
  80. RawOrientation = rotation;
  81. _buoyancy = 0f;
  82. RawVelocity = OMV.Vector3.Zero;
  83. _rotationalVelocity = OMV.Vector3.Zero;
  84. BaseShape = pbs;
  85. _isPhysical = pisPhysical;
  86. _isVolumeDetect = false;
  87. // Add a dynamic vehicle to our set of actors that can move this prim.
  88. // PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName));
  89. _mass = CalculateMass();
  90. // DetailLog("{0},BSPrim.constructor,call", LocalID);
  91. // do the actual object creation at taint time
  92. PhysScene.TaintedObject("BSPrim.create", delegate()
  93. {
  94. // Make sure the object is being created with some sanity.
  95. ExtremeSanityCheck(true /* inTaintTime */);
  96. CreateGeomAndObject(true);
  97. CurrentCollisionFlags = PhysScene.PE.GetCollisionFlags(PhysBody);
  98. });
  99. }
  100. // called when this prim is being destroyed and we should free all the resources
  101. public override void Destroy()
  102. {
  103. // m_log.DebugFormat("{0}: Destroy, id={1}", LogHeader, LocalID);
  104. base.Destroy();
  105. // Undo any vehicle properties
  106. this.VehicleType = (int)Vehicle.TYPE_NONE;
  107. PhysScene.TaintedObject("BSPrim.Destroy", delegate()
  108. {
  109. DetailLog("{0},BSPrim.Destroy,taint,", LocalID);
  110. // If there are physical body and shape, release my use of same.
  111. PhysScene.Shapes.DereferenceBody(PhysBody, null);
  112. PhysBody.Clear();
  113. PhysShape.Dereference(PhysScene);
  114. PhysShape = new BSShapeNull();
  115. });
  116. }
  117. // No one uses this property.
  118. public override bool Stopped {
  119. get { return false; }
  120. }
  121. public override OMV.Vector3 Size {
  122. get { return _size; }
  123. set {
  124. // We presume the scale and size are the same. If scale must be changed for
  125. // the physical shape, that is done when the geometry is built.
  126. _size = value;
  127. Scale = _size;
  128. ForceBodyShapeRebuild(false);
  129. }
  130. }
  131. public override PrimitiveBaseShape Shape {
  132. set {
  133. BaseShape = value;
  134. PrimAssetState = PrimAssetCondition.Unknown;
  135. ForceBodyShapeRebuild(false);
  136. }
  137. }
  138. public override bool ForceBodyShapeRebuild(bool inTaintTime)
  139. {
  140. PhysScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate()
  141. {
  142. _mass = CalculateMass(); // changing the shape changes the mass
  143. CreateGeomAndObject(true);
  144. });
  145. return true;
  146. }
  147. public override bool Grabbed {
  148. set { _grabbed = value;
  149. }
  150. }
  151. public override bool Selected {
  152. set
  153. {
  154. if (value != _isSelected)
  155. {
  156. _isSelected = value;
  157. PhysScene.TaintedObject("BSPrim.setSelected", delegate()
  158. {
  159. DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected);
  160. SetObjectDynamic(false);
  161. });
  162. }
  163. }
  164. }
  165. public override bool IsSelected
  166. {
  167. get { return _isSelected; }
  168. }
  169. public override void CrossingFailure()
  170. {
  171. CrossingFailures++;
  172. if (CrossingFailures > BSParam.CrossingFailuresBeforeOutOfBounds)
  173. {
  174. base.RaiseOutOfBounds(RawPosition);
  175. }
  176. else if (CrossingFailures == BSParam.CrossingFailuresBeforeOutOfBounds)
  177. {
  178. m_log.WarnFormat("{0} Too many crossing failures for {1}", LogHeader, Name);
  179. }
  180. return;
  181. }
  182. // link me to the specified parent
  183. public override void link(PhysicsActor obj) {
  184. }
  185. // delink me from my linkset
  186. public override void delink() {
  187. }
  188. // Set motion values to zero.
  189. // Do it to the properties so the values get set in the physics engine.
  190. // Push the setting of the values to the viewer.
  191. // Called at taint time!
  192. public override void ZeroMotion(bool inTaintTime)
  193. {
  194. RawVelocity = OMV.Vector3.Zero;
  195. _acceleration = OMV.Vector3.Zero;
  196. _rotationalVelocity = OMV.Vector3.Zero;
  197. // Zero some other properties in the physics engine
  198. PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate()
  199. {
  200. if (PhysBody.HasPhysicalBody)
  201. PhysScene.PE.ClearAllForces(PhysBody);
  202. });
  203. }
  204. public override void ZeroAngularMotion(bool inTaintTime)
  205. {
  206. _rotationalVelocity = OMV.Vector3.Zero;
  207. // Zero some other properties in the physics engine
  208. PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate()
  209. {
  210. // DetailLog("{0},BSPrim.ZeroAngularMotion,call,rotVel={1}", LocalID, _rotationalVelocity);
  211. if (PhysBody.HasPhysicalBody)
  212. {
  213. PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity);
  214. PhysScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity);
  215. }
  216. });
  217. }
  218. public override void LockAngularMotion(OMV.Vector3 axis)
  219. {
  220. DetailLog("{0},BSPrim.LockAngularMotion,call,axis={1}", LocalID, axis);
  221. // "1" means free, "0" means locked
  222. OMV.Vector3 locking = LockedAxisFree;
  223. if (axis.X != 1) locking.X = 0f;
  224. if (axis.Y != 1) locking.Y = 0f;
  225. if (axis.Z != 1) locking.Z = 0f;
  226. LockedAngularAxis = locking;
  227. EnableActor(LockedAngularAxis != LockedAxisFree, LockedAxisActorName, delegate()
  228. {
  229. return new BSActorLockAxis(PhysScene, this, LockedAxisActorName);
  230. });
  231. // Update parameters so the new actor's Refresh() action is called at the right time.
  232. PhysScene.TaintedObject("BSPrim.LockAngularMotion", delegate()
  233. {
  234. UpdatePhysicalParameters();
  235. });
  236. return;
  237. }
  238. public override OMV.Vector3 Position {
  239. get {
  240. // don't do the GetObjectPosition for root elements because this function is called a zillion times.
  241. // RawPosition = ForcePosition;
  242. return RawPosition;
  243. }
  244. set {
  245. // If the position must be forced into the physics engine, use ForcePosition.
  246. // All positions are given in world positions.
  247. if (RawPosition == value)
  248. {
  249. DetailLog("{0},BSPrim.setPosition,call,positionNotChanging,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  250. return;
  251. }
  252. RawPosition = value;
  253. PositionSanityCheck(false);
  254. PhysScene.TaintedObject("BSPrim.setPosition", delegate()
  255. {
  256. DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  257. ForcePosition = RawPosition;
  258. });
  259. }
  260. }
  261. // NOTE: overloaded by BSPrimDisplaced to handle offset for center-of-gravity.
  262. public override OMV.Vector3 ForcePosition {
  263. get {
  264. RawPosition = PhysScene.PE.GetPosition(PhysBody);
  265. return RawPosition;
  266. }
  267. set {
  268. RawPosition = value;
  269. if (PhysBody.HasPhysicalBody)
  270. {
  271. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  272. ActivateIfPhysical(false);
  273. }
  274. }
  275. }
  276. // Check that the current position is sane and, if not, modify the position to make it so.
  277. // Check for being below terrain and being out of bounds.
  278. // Returns 'true' of the position was made sane by some action.
  279. private bool PositionSanityCheck(bool inTaintTime)
  280. {
  281. bool ret = false;
  282. // We don't care where non-physical items are placed
  283. if (!IsPhysicallyActive)
  284. return ret;
  285. if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
  286. {
  287. // The physical object is out of the known/simulated area.
  288. // Upper levels of code will handle the transition to other areas so, for
  289. // the time, we just ignore the position.
  290. return ret;
  291. }
  292. float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
  293. OMV.Vector3 upForce = OMV.Vector3.Zero;
  294. float approxSize = Math.Max(Size.X, Math.Max(Size.Y, Size.Z));
  295. if ((RawPosition.Z + approxSize / 2f) < terrainHeight)
  296. {
  297. DetailLog("{0},BSPrim.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
  298. float targetHeight = terrainHeight + (Size.Z / 2f);
  299. // If the object is below ground it just has to be moved up because pushing will
  300. // not get it through the terrain
  301. RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, targetHeight);
  302. if (inTaintTime)
  303. {
  304. ForcePosition = RawPosition;
  305. }
  306. // If we are throwing the object around, zero its other forces
  307. ZeroMotion(inTaintTime);
  308. ret = true;
  309. }
  310. if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
  311. {
  312. float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
  313. // TODO: a floating motor so object will bob in the water
  314. if (Math.Abs(RawPosition.Z - waterHeight) > 0.1f)
  315. {
  316. // Upforce proportional to the distance away from the water. Correct the error in 1 sec.
  317. upForce.Z = (waterHeight - RawPosition.Z) * 1f;
  318. // Apply upforce and overcome gravity.
  319. OMV.Vector3 correctionForce = upForce - PhysScene.DefaultGravity;
  320. DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, RawPosition, upForce, correctionForce);
  321. AddForce(correctionForce, false, inTaintTime);
  322. ret = true;
  323. }
  324. }
  325. return ret;
  326. }
  327. // Occasionally things will fly off and really get lost.
  328. // Find the wanderers and bring them back.
  329. // Return 'true' if some parameter need some sanity.
  330. private bool ExtremeSanityCheck(bool inTaintTime)
  331. {
  332. bool ret = false;
  333. uint wayOutThere = Constants.RegionSize * Constants.RegionSize;
  334. // There have been instances of objects getting thrown way out of bounds and crashing
  335. // the border crossing code.
  336. if ( RawPosition.X < -Constants.RegionSize || RawPosition.X > wayOutThere
  337. || RawPosition.Y < -Constants.RegionSize || RawPosition.Y > wayOutThere
  338. || RawPosition.Z < -Constants.RegionSize || RawPosition.Z > wayOutThere)
  339. {
  340. RawPosition = new OMV.Vector3(10, 10, 50);
  341. ZeroMotion(inTaintTime);
  342. ret = true;
  343. }
  344. if (RawVelocity.LengthSquared() > BSParam.MaxLinearVelocity)
  345. {
  346. RawVelocity = Util.ClampV(RawVelocity, BSParam.MaxLinearVelocity);
  347. ret = true;
  348. }
  349. if (_rotationalVelocity.LengthSquared() > BSParam.MaxAngularVelocitySquared)
  350. {
  351. _rotationalVelocity = Util.ClampV(_rotationalVelocity, BSParam.MaxAngularVelocity);
  352. ret = true;
  353. }
  354. return ret;
  355. }
  356. // Return the effective mass of the object.
  357. // The definition of this call is to return the mass of the prim.
  358. // If the simulator cares about the mass of the linkset, it will sum it itself.
  359. public override float Mass
  360. {
  361. get { return _mass; }
  362. }
  363. // TotalMass returns the mass of the large object the prim may be in (overridden by linkset code)
  364. public virtual float TotalMass
  365. {
  366. get { return _mass; }
  367. }
  368. // used when we only want this prim's mass and not the linkset thing
  369. public override float RawMass {
  370. get { return _mass; }
  371. }
  372. // Set the physical mass to the passed mass.
  373. // Note that this does not change _mass!
  374. public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
  375. {
  376. if (PhysBody.HasPhysicalBody && PhysShape.HasPhysicalShape)
  377. {
  378. if (IsStatic)
  379. {
  380. PhysScene.PE.SetGravity(PhysBody, PhysScene.DefaultGravity);
  381. Inertia = OMV.Vector3.Zero;
  382. PhysScene.PE.SetMassProps(PhysBody, 0f, Inertia);
  383. PhysScene.PE.UpdateInertiaTensor(PhysBody);
  384. }
  385. else
  386. {
  387. if (inWorld)
  388. {
  389. // Changing interesting properties doesn't change proxy and collision cache
  390. // information. The Bullet solution is to re-add the object to the world
  391. // after parameters are changed.
  392. PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
  393. }
  394. // The computation of mass props requires gravity to be set on the object.
  395. Gravity = ComputeGravity(Buoyancy);
  396. PhysScene.PE.SetGravity(PhysBody, Gravity);
  397. // OMV.Vector3 currentScale = PhysScene.PE.GetLocalScaling(PhysShape.physShapeInfo); // DEBUG DEBUG
  398. // DetailLog("{0},BSPrim.UpdateMassProperties,currentScale{1},shape={2}", LocalID, currentScale, PhysShape.physShapeInfo); // DEBUG DEBUG
  399. Inertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
  400. PhysScene.PE.SetMassProps(PhysBody, physMass, Inertia);
  401. PhysScene.PE.UpdateInertiaTensor(PhysBody);
  402. DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2},grav={3},inWorld={4}",
  403. LocalID, physMass, Inertia, Gravity, inWorld);
  404. if (inWorld)
  405. {
  406. AddObjectToPhysicalWorld();
  407. }
  408. }
  409. }
  410. }
  411. // Return what gravity should be set to this very moment
  412. public OMV.Vector3 ComputeGravity(float buoyancy)
  413. {
  414. OMV.Vector3 ret = PhysScene.DefaultGravity;
  415. if (!IsStatic)
  416. {
  417. ret *= (1f - buoyancy);
  418. ret *= GravModifier;
  419. }
  420. return ret;
  421. }
  422. // Is this used?
  423. public override OMV.Vector3 CenterOfMass
  424. {
  425. get { return RawPosition; }
  426. }
  427. // Is this used?
  428. public override OMV.Vector3 GeometricCenter
  429. {
  430. get { return RawPosition; }
  431. }
  432. public override OMV.Vector3 Force {
  433. get { return RawForce; }
  434. set {
  435. RawForce = value;
  436. EnableActor(RawForce != OMV.Vector3.Zero, SetForceActorName, delegate()
  437. {
  438. return new BSActorSetForce(PhysScene, this, SetForceActorName);
  439. });
  440. }
  441. }
  442. // Find and return a handle to the current vehicle actor.
  443. // Return 'null' if there is no vehicle actor.
  444. public BSDynamics GetVehicleActor(bool createIfNone)
  445. {
  446. BSDynamics ret = null;
  447. BSActor actor;
  448. if (PhysicalActors.TryGetActor(VehicleActorName, out actor))
  449. {
  450. ret = actor as BSDynamics;
  451. }
  452. else
  453. {
  454. if (createIfNone)
  455. {
  456. ret = new BSDynamics(PhysScene, this, VehicleActorName);
  457. PhysicalActors.Add(ret.ActorName, ret);
  458. }
  459. }
  460. return ret;
  461. }
  462. public override int VehicleType {
  463. get {
  464. int ret = (int)Vehicle.TYPE_NONE;
  465. BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */);
  466. if (vehicleActor != null)
  467. ret = (int)vehicleActor.Type;
  468. return ret;
  469. }
  470. set {
  471. Vehicle type = (Vehicle)value;
  472. PhysScene.TaintedObject("setVehicleType", delegate()
  473. {
  474. // Some vehicle scripts change vehicle type on the fly as an easy way to
  475. // change all the parameters. Like a plane changing to CAR when on the
  476. // ground. In this case, don't want to zero motion.
  477. // ZeroMotion(true /* inTaintTime */);
  478. if (type == Vehicle.TYPE_NONE)
  479. {
  480. // Vehicle type is 'none' so get rid of any actor that may have been allocated.
  481. BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */);
  482. if (vehicleActor != null)
  483. {
  484. PhysicalActors.RemoveAndRelease(vehicleActor.ActorName);
  485. }
  486. }
  487. else
  488. {
  489. // Vehicle type is not 'none' so create an actor and set it running.
  490. BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */);
  491. if (vehicleActor != null)
  492. {
  493. vehicleActor.ProcessTypeChange(type);
  494. ActivateIfPhysical(false);
  495. }
  496. }
  497. });
  498. }
  499. }
  500. public override void VehicleFloatParam(int param, float value)
  501. {
  502. PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate()
  503. {
  504. BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */);
  505. if (vehicleActor != null)
  506. {
  507. vehicleActor.ProcessFloatVehicleParam((Vehicle)param, value);
  508. ActivateIfPhysical(false);
  509. }
  510. });
  511. }
  512. public override void VehicleVectorParam(int param, OMV.Vector3 value)
  513. {
  514. PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate()
  515. {
  516. BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */);
  517. if (vehicleActor != null)
  518. {
  519. vehicleActor.ProcessVectorVehicleParam((Vehicle)param, value);
  520. ActivateIfPhysical(false);
  521. }
  522. });
  523. }
  524. public override void VehicleRotationParam(int param, OMV.Quaternion rotation)
  525. {
  526. PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate()
  527. {
  528. BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */);
  529. if (vehicleActor != null)
  530. {
  531. vehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation);
  532. ActivateIfPhysical(false);
  533. }
  534. });
  535. }
  536. public override void VehicleFlags(int param, bool remove)
  537. {
  538. PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate()
  539. {
  540. BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */);
  541. if (vehicleActor != null)
  542. {
  543. vehicleActor.ProcessVehicleFlags(param, remove);
  544. }
  545. });
  546. }
  547. // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
  548. public override void SetVolumeDetect(int param) {
  549. bool newValue = (param != 0);
  550. if (_isVolumeDetect != newValue)
  551. {
  552. _isVolumeDetect = newValue;
  553. PhysScene.TaintedObject("BSPrim.SetVolumeDetect", delegate()
  554. {
  555. // DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect);
  556. SetObjectDynamic(true);
  557. });
  558. }
  559. return;
  560. }
  561. public override void SetMaterial(int material)
  562. {
  563. base.SetMaterial(material);
  564. PhysScene.TaintedObject("BSPrim.SetMaterial", delegate()
  565. {
  566. UpdatePhysicalParameters();
  567. });
  568. }
  569. public override float Friction
  570. {
  571. get { return base.Friction; }
  572. set
  573. {
  574. if (base.Friction != value)
  575. {
  576. base.Friction = value;
  577. PhysScene.TaintedObject("BSPrim.setFriction", delegate()
  578. {
  579. UpdatePhysicalParameters();
  580. });
  581. }
  582. }
  583. }
  584. public override float Restitution
  585. {
  586. get { return base.Restitution; }
  587. set
  588. {
  589. if (base.Restitution != value)
  590. {
  591. base.Restitution = value;
  592. PhysScene.TaintedObject("BSPrim.setRestitution", delegate()
  593. {
  594. UpdatePhysicalParameters();
  595. });
  596. }
  597. }
  598. }
  599. // The simulator/viewer keep density as 100kg/m3.
  600. // Remember to use BSParam.DensityScaleFactor to create the physical density.
  601. public override float Density
  602. {
  603. get { return base.Density; }
  604. set
  605. {
  606. if (base.Density != value)
  607. {
  608. base.Density = value;
  609. PhysScene.TaintedObject("BSPrim.setDensity", delegate()
  610. {
  611. UpdatePhysicalParameters();
  612. });
  613. }
  614. }
  615. }
  616. public override float GravModifier
  617. {
  618. get { return base.GravModifier; }
  619. set
  620. {
  621. if (base.GravModifier != value)
  622. {
  623. base.GravModifier = value;
  624. PhysScene.TaintedObject("BSPrim.setGravityModifier", delegate()
  625. {
  626. UpdatePhysicalParameters();
  627. });
  628. }
  629. }
  630. }
  631. public override OMV.Vector3 Velocity {
  632. get { return RawVelocity; }
  633. set {
  634. RawVelocity = value;
  635. PhysScene.TaintedObject("BSPrim.setVelocity", delegate()
  636. {
  637. // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, RawVelocity);
  638. ForceVelocity = RawVelocity;
  639. });
  640. }
  641. }
  642. public override OMV.Vector3 ForceVelocity {
  643. get { return RawVelocity; }
  644. set {
  645. PhysScene.AssertInTaintTime("BSPrim.ForceVelocity");
  646. RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity);
  647. if (PhysBody.HasPhysicalBody)
  648. {
  649. DetailLog("{0},BSPrim.ForceVelocity,taint,vel={1}", LocalID, RawVelocity);
  650. PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
  651. ActivateIfPhysical(false);
  652. }
  653. }
  654. }
  655. public override OMV.Vector3 Torque {
  656. get { return RawTorque; }
  657. set {
  658. RawTorque = value;
  659. EnableActor(RawTorque != OMV.Vector3.Zero, SetTorqueActorName, delegate()
  660. {
  661. return new BSActorSetTorque(PhysScene, this, SetTorqueActorName);
  662. });
  663. DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, RawTorque);
  664. }
  665. }
  666. public override OMV.Vector3 Acceleration {
  667. get { return _acceleration; }
  668. set { _acceleration = value; }
  669. }
  670. public override OMV.Quaternion Orientation {
  671. get {
  672. return RawOrientation;
  673. }
  674. set {
  675. if (RawOrientation == value)
  676. return;
  677. RawOrientation = value;
  678. PhysScene.TaintedObject("BSPrim.setOrientation", delegate()
  679. {
  680. ForceOrientation = RawOrientation;
  681. });
  682. }
  683. }
  684. // Go directly to Bullet to get/set the value.
  685. public override OMV.Quaternion ForceOrientation
  686. {
  687. get
  688. {
  689. RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
  690. return RawOrientation;
  691. }
  692. set
  693. {
  694. RawOrientation = value;
  695. if (PhysBody.HasPhysicalBody)
  696. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  697. }
  698. }
  699. public override int PhysicsActorType {
  700. get { return _physicsActorType; }
  701. set { _physicsActorType = value; }
  702. }
  703. public override bool IsPhysical {
  704. get { return _isPhysical; }
  705. set {
  706. if (_isPhysical != value)
  707. {
  708. _isPhysical = value;
  709. PhysScene.TaintedObject("BSPrim.setIsPhysical", delegate()
  710. {
  711. DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical);
  712. SetObjectDynamic(true);
  713. // whether phys-to-static or static-to-phys, the object is not moving.
  714. ZeroMotion(true);
  715. });
  716. }
  717. }
  718. }
  719. // An object is static (does not move) if selected or not physical
  720. public override bool IsStatic
  721. {
  722. get { return _isSelected || !IsPhysical; }
  723. }
  724. // An object is solid if it's not phantom and if it's not doing VolumeDetect
  725. public override bool IsSolid
  726. {
  727. get { return !IsPhantom && !_isVolumeDetect; }
  728. }
  729. // The object is moving and is actively being dynamic in the physical world
  730. public override bool IsPhysicallyActive
  731. {
  732. get { return !_isSelected && IsPhysical; }
  733. }
  734. // Make gravity work if the object is physical and not selected
  735. // Called at taint-time!!
  736. private void SetObjectDynamic(bool forceRebuild)
  737. {
  738. // Recreate the physical object if necessary
  739. CreateGeomAndObject(forceRebuild);
  740. }
  741. // Convert the simulator's physical properties into settings on BulletSim objects.
  742. // There are four flags we're interested in:
  743. // IsStatic: Object does not move, otherwise the object has mass and moves
  744. // isSolid: other objects bounce off of this object
  745. // isVolumeDetect: other objects pass through but can generate collisions
  746. // collisionEvents: whether this object returns collision events
  747. // NOTE: overloaded by BSPrimLinkable to also update linkset physical parameters.
  748. public virtual void UpdatePhysicalParameters()
  749. {
  750. if (!PhysBody.HasPhysicalBody)
  751. {
  752. // This would only happen if updates are called for during initialization when the body is not set up yet.
  753. // DetailLog("{0},BSPrim.UpdatePhysicalParameters,taint,calledWithNoPhysBody", LocalID);
  754. return;
  755. }
  756. // Mangling all the physical properties requires the object not be in the physical world.
  757. // This is a NOOP if the object is not in the world (BulletSim and Bullet ignore objects not found).
  758. PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
  759. // Set up the object physicalness (does gravity and collisions move this object)
  760. MakeDynamic(IsStatic);
  761. // Update vehicle specific parameters (after MakeDynamic() so can change physical parameters)
  762. PhysicalActors.Refresh();
  763. // Arrange for collision events if the simulator wants them
  764. EnableCollisions(SubscribedEvents());
  765. // Make solid or not (do things bounce off or pass through this object).
  766. MakeSolid(IsSolid);
  767. AddObjectToPhysicalWorld();
  768. // Rebuild its shape
  769. PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
  770. DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},cType={6},body={7},shape={8}",
  771. LocalID, IsStatic, IsSolid, Mass, SubscribedEvents(),
  772. CurrentCollisionFlags, PhysBody.collisionType, PhysBody, PhysShape);
  773. }
  774. // "Making dynamic" means changing to and from static.
  775. // When static, gravity does not effect the object and it is fixed in space.
  776. // When dynamic, the object can fall and be pushed by others.
  777. // This is independent of its 'solidness' which controls what passes through
  778. // this object and what interacts with it.
  779. protected virtual void MakeDynamic(bool makeStatic)
  780. {
  781. if (makeStatic)
  782. {
  783. // Become a Bullet 'static' object type
  784. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT);
  785. // Stop all movement
  786. ZeroMotion(true);
  787. // Set various physical properties so other object interact properly
  788. PhysScene.PE.SetFriction(PhysBody, Friction);
  789. PhysScene.PE.SetRestitution(PhysBody, Restitution);
  790. PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
  791. // Mass is zero which disables a bunch of physics stuff in Bullet
  792. UpdatePhysicalMassProperties(0f, false);
  793. // Set collision detection parameters
  794. if (BSParam.CcdMotionThreshold > 0f)
  795. {
  796. PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
  797. PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
  798. }
  799. // The activation state is 'disabled' so Bullet will not try to act on it.
  800. // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_SIMULATION);
  801. // Start it out sleeping and physical actions could wake it up.
  802. PhysScene.PE.ForceActivationState(PhysBody, ActivationState.ISLAND_SLEEPING);
  803. // This collides like a static object
  804. PhysBody.collisionType = CollisionType.Static;
  805. }
  806. else
  807. {
  808. // Not a Bullet static object
  809. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT);
  810. // Set various physical properties so other object interact properly
  811. PhysScene.PE.SetFriction(PhysBody, Friction);
  812. PhysScene.PE.SetRestitution(PhysBody, Restitution);
  813. // DetailLog("{0},BSPrim.MakeDynamic,frict={1},rest={2}", LocalID, Friction, Restitution);
  814. // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382
  815. // Since this can be called multiple times, only zero forces when becoming physical
  816. // PhysicsScene.PE.ClearAllForces(BSBody);
  817. // For good measure, make sure the transform is set through to the motion state
  818. ForcePosition = RawPosition;
  819. ForceVelocity = RawVelocity;
  820. ForceRotationalVelocity = _rotationalVelocity;
  821. // A dynamic object has mass
  822. UpdatePhysicalMassProperties(RawMass, false);
  823. // Set collision detection parameters
  824. if (BSParam.CcdMotionThreshold > 0f)
  825. {
  826. PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
  827. PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
  828. }
  829. // Various values for simulation limits
  830. PhysScene.PE.SetDamping(PhysBody, BSParam.LinearDamping, BSParam.AngularDamping);
  831. PhysScene.PE.SetDeactivationTime(PhysBody, BSParam.DeactivationTime);
  832. PhysScene.PE.SetSleepingThresholds(PhysBody, BSParam.LinearSleepingThreshold, BSParam.AngularSleepingThreshold);
  833. PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
  834. // This collides like an object.
  835. PhysBody.collisionType = CollisionType.Dynamic;
  836. // Force activation of the object so Bullet will act on it.
  837. // Must do the ForceActivationState2() to overcome the DISABLE_SIMULATION from static objects.
  838. PhysScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
  839. }
  840. }
  841. // "Making solid" means that other object will not pass through this object.
  842. // To make transparent, we create a Bullet ghost object.
  843. // Note: This expects to be called from the UpdatePhysicalParameters() routine as
  844. // the functions after this one set up the state of a possibly newly created collision body.
  845. private void MakeSolid(bool makeSolid)
  846. {
  847. CollisionObjectTypes bodyType = (CollisionObjectTypes)PhysScene.PE.GetBodyType(PhysBody);
  848. if (makeSolid)
  849. {
  850. // Verify the previous code created the correct shape for this type of thing.
  851. if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0)
  852. {
  853. m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for solidity. id={1}, type={2}", LogHeader, LocalID, bodyType);
  854. }
  855. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
  856. }
  857. else
  858. {
  859. if ((bodyType & CollisionObjectTypes.CO_GHOST_OBJECT) == 0)
  860. {
  861. m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for non-solidness. id={1}, type={2}", LogHeader, LocalID, bodyType);
  862. }
  863. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
  864. // Change collision info from a static object to a ghosty collision object
  865. PhysBody.collisionType = CollisionType.VolumeDetect;
  866. }
  867. }
  868. // Turn on or off the flag controlling whether collision events are returned to the simulator.
  869. private void EnableCollisions(bool wantsCollisionEvents)
  870. {
  871. if (wantsCollisionEvents)
  872. {
  873. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  874. }
  875. else
  876. {
  877. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  878. }
  879. }
  880. // Add me to the physical world.
  881. // Object MUST NOT already be in the world.
  882. // This routine exists because some assorted properties get mangled by adding to the world.
  883. internal void AddObjectToPhysicalWorld()
  884. {
  885. if (PhysBody.HasPhysicalBody)
  886. {
  887. PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
  888. }
  889. else
  890. {
  891. m_log.ErrorFormat("{0} Attempt to add physical object without body. id={1}", LogHeader, LocalID);
  892. DetailLog("{0},BSPrim.AddObjectToPhysicalWorld,addObjectWithoutBody,cType={1}", LocalID, PhysBody.collisionType);
  893. }
  894. }
  895. // prims don't fly
  896. public override bool Flying {
  897. get { return _flying; }
  898. set {
  899. _flying = value;
  900. }
  901. }
  902. public override bool SetAlwaysRun {
  903. get { return _setAlwaysRun; }
  904. set { _setAlwaysRun = value; }
  905. }
  906. public override bool ThrottleUpdates {
  907. get { return _throttleUpdates; }
  908. set { _throttleUpdates = value; }
  909. }
  910. public bool IsPhantom {
  911. get {
  912. // SceneObjectPart removes phantom objects from the physics scene
  913. // so, although we could implement touching and such, we never
  914. // are invoked as a phantom object
  915. return false;
  916. }
  917. }
  918. public override bool FloatOnWater {
  919. set {
  920. _floatOnWater = value;
  921. PhysScene.TaintedObject("BSPrim.setFloatOnWater", delegate()
  922. {
  923. if (_floatOnWater)
  924. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  925. else
  926. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  927. });
  928. }
  929. }
  930. public override OMV.Vector3 RotationalVelocity {
  931. get {
  932. return _rotationalVelocity;
  933. }
  934. set {
  935. _rotationalVelocity = value;
  936. Util.ClampV(_rotationalVelocity, BSParam.MaxAngularVelocity);
  937. // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity);
  938. PhysScene.TaintedObject("BSPrim.setRotationalVelocity", delegate()
  939. {
  940. ForceRotationalVelocity = _rotationalVelocity;
  941. });
  942. }
  943. }
  944. public override OMV.Vector3 ForceRotationalVelocity {
  945. get {
  946. return _rotationalVelocity;
  947. }
  948. set {
  949. _rotationalVelocity = Util.ClampV(value, BSParam.MaxAngularVelocity);
  950. if (PhysBody.HasPhysicalBody)
  951. {
  952. DetailLog("{0},BSPrim.ForceRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity);
  953. PhysScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity);
  954. // PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity);
  955. ActivateIfPhysical(false);
  956. }
  957. }
  958. }
  959. public override bool Kinematic {
  960. get { return _kinematic; }
  961. set { _kinematic = value;
  962. // m_log.DebugFormat("{0}: Kinematic={1}", LogHeader, _kinematic);
  963. }
  964. }
  965. public override float Buoyancy {
  966. get { return _buoyancy; }
  967. set {
  968. _buoyancy = value;
  969. PhysScene.TaintedObject("BSPrim.setBuoyancy", delegate()
  970. {
  971. ForceBuoyancy = _buoyancy;
  972. });
  973. }
  974. }
  975. public override float ForceBuoyancy {
  976. get { return _buoyancy; }
  977. set {
  978. _buoyancy = value;
  979. // DetailLog("{0},BSPrim.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
  980. // Force the recalculation of the various inertia,etc variables in the object
  981. UpdatePhysicalMassProperties(RawMass, true);
  982. DetailLog("{0},BSPrim.ForceBuoyancy,buoy={1},mass={2},grav={3}", LocalID, _buoyancy, RawMass, Gravity);
  983. ActivateIfPhysical(false);
  984. }
  985. }
  986. public override bool PIDActive {
  987. set {
  988. base.MoveToTargetActive = value;
  989. EnableActor(MoveToTargetActive, MoveToTargetActorName, delegate()
  990. {
  991. return new BSActorMoveToTarget(PhysScene, this, MoveToTargetActorName);
  992. });
  993. }
  994. }
  995. public override OMV.Vector3 PIDTarget
  996. {
  997. set
  998. {
  999. base.PIDTarget = value;
  1000. BSActor actor;
  1001. if (PhysicalActors.TryGetActor(MoveToTargetActorName, out actor))
  1002. {
  1003. // if the actor exists, tell it to refresh its values.
  1004. actor.Refresh();
  1005. }
  1006. }
  1007. }
  1008. // Used for llSetHoverHeight and maybe vehicle height
  1009. // Hover Height will override MoveTo target's Z
  1010. public override bool PIDHoverActive {
  1011. set {
  1012. base.HoverActive = value;
  1013. EnableActor(HoverActive, HoverActorName, delegate()
  1014. {
  1015. return new BSActorHover(PhysScene, this, HoverActorName);
  1016. });
  1017. }
  1018. }
  1019. public override void AddForce(OMV.Vector3 force, bool pushforce) {
  1020. // Per documentation, max force is limited.
  1021. OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
  1022. // Since this force is being applied in only one step, make this a force per second.
  1023. addForce /= PhysScene.LastTimeStep;
  1024. AddForce(addForce, pushforce, false /* inTaintTime */);
  1025. }
  1026. // Applying a force just adds this to the total force on the object.
  1027. // This added force will only last the next simulation tick.
  1028. public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
  1029. // for an object, doesn't matter if force is a pushforce or not
  1030. if (IsPhysicallyActive)
  1031. {
  1032. if (force.IsFinite())
  1033. {
  1034. // DetailLog("{0},BSPrim.addForce,call,force={1}", LocalID, addForce);
  1035. OMV.Vector3 addForce = force;
  1036. PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate()
  1037. {
  1038. // Bullet adds this central force to the total force for this tick.
  1039. // Deep down in Bullet:
  1040. // linearVelocity += totalForce / mass * timeStep;
  1041. DetailLog("{0},BSPrim.addForce,taint,force={1}", LocalID, addForce);
  1042. if (PhysBody.HasPhysicalBody)
  1043. {
  1044. PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
  1045. ActivateIfPhysical(false);
  1046. }
  1047. });
  1048. }
  1049. else
  1050. {
  1051. m_log.WarnFormat("{0}: AddForce: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID);
  1052. return;
  1053. }
  1054. }
  1055. }
  1056. public void AddForceImpulse(OMV.Vector3 impulse, bool pushforce, bool inTaintTime) {
  1057. // for an object, doesn't matter if force is a pushforce or not
  1058. if (!IsPhysicallyActive)
  1059. {
  1060. if (impulse.IsFinite())
  1061. {
  1062. OMV.Vector3 addImpulse = Util.ClampV(impulse, BSParam.MaxAddForceMagnitude);
  1063. // DetailLog("{0},BSPrim.addForceImpulse,call,impulse={1}", LocalID, impulse);
  1064. PhysScene.TaintedObject(inTaintTime, "BSPrim.AddImpulse", delegate()
  1065. {
  1066. // Bullet adds this impulse immediately to the velocity
  1067. DetailLog("{0},BSPrim.addForceImpulse,taint,impulseforce={1}", LocalID, addImpulse);
  1068. if (PhysBody.HasPhysicalBody)
  1069. {
  1070. PhysScene.PE.ApplyCentralImpulse(PhysBody, addImpulse);
  1071. ActivateIfPhysical(false);
  1072. }
  1073. });
  1074. }
  1075. else
  1076. {
  1077. m_log.WarnFormat("{0}: AddForceImpulse: Got a NaN impulse applied to a prim. LocalID={1}", LogHeader, LocalID);
  1078. return;
  1079. }
  1080. }
  1081. }
  1082. // BSPhysObject.AddAngularForce()
  1083. public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime)
  1084. {
  1085. if (force.IsFinite())
  1086. {
  1087. OMV.Vector3 angForce = force;
  1088. PhysScene.TaintedObject(inTaintTime, "BSPrim.AddAngularForce", delegate()
  1089. {
  1090. if (PhysBody.HasPhysicalBody)
  1091. {
  1092. DetailLog("{0},BSPrim.AddAngularForce,taint,angForce={1}", LocalID, angForce);
  1093. PhysScene.PE.ApplyTorque(PhysBody, angForce);
  1094. ActivateIfPhysical(false);
  1095. }
  1096. });
  1097. }
  1098. else
  1099. {
  1100. m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID);
  1101. return;
  1102. }
  1103. }
  1104. // A torque impulse.
  1105. // ApplyTorqueImpulse adds torque directly to the angularVelocity.
  1106. // AddAngularForce accumulates the force and applied it to the angular velocity all at once.
  1107. // Computed as: angularVelocity += impulse * inertia;
  1108. public void ApplyTorqueImpulse(OMV.Vector3 impulse, bool inTaintTime)
  1109. {
  1110. OMV.Vector3 applyImpulse = impulse;
  1111. PhysScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate()
  1112. {
  1113. if (PhysBody.HasPhysicalBody)
  1114. {
  1115. PhysScene.PE.ApplyTorqueImpulse(PhysBody, applyImpulse);
  1116. ActivateIfPhysical(false);
  1117. }
  1118. });
  1119. }
  1120. public override void SetMomentum(OMV.Vector3 momentum) {
  1121. // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum);
  1122. }
  1123. #region Mass Calculation
  1124. private float CalculateMass()
  1125. {
  1126. float volume = _size.X * _size.Y * _size.Z; // default
  1127. float tmp;
  1128. float returnMass = 0;
  1129. float hollowAmount = (float)BaseShape.ProfileHollow * 2.0e-5f;
  1130. float hollowVolume = hollowAmount * hollowAmount;
  1131. switch (BaseShape.ProfileShape)
  1132. {
  1133. case ProfileShape.Square:
  1134. // default box
  1135. if (BaseShape.PathCurve == (byte)Extrusion.Straight)
  1136. {
  1137. if (hollowAmount > 0.0)
  1138. {
  1139. switch (BaseShape.HollowShape)
  1140. {
  1141. case HollowShape.Square:
  1142. case HollowShape.Same:
  1143. break;
  1144. case HollowShape.Circle:
  1145. hollowVolume *= 0.78539816339f;
  1146. break;
  1147. case HollowShape.Triangle:
  1148. hollowVolume *= (0.5f * .5f);
  1149. break;
  1150. default:
  1151. hollowVolume = 0;
  1152. break;
  1153. }
  1154. volume *= (1.0f - hollowVolume);
  1155. }
  1156. }
  1157. else if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1158. {
  1159. //a tube
  1160. volume *= 0.78539816339e-2f * (float)(200 - BaseShape.PathScaleX);
  1161. tmp= 1.0f -2.0e-2f * (float)(200 - BaseShape.PathScaleY);
  1162. volume -= volume*tmp*tmp;
  1163. if (hollowAmount > 0.0)
  1164. {
  1165. hollowVolume *= hollowAmount;
  1166. switch (BaseShape.HollowShape)
  1167. {
  1168. case HollowShape.Square:
  1169. case HollowShape.Same:
  1170. break;
  1171. case HollowShape.Circle:
  1172. hollowVolume *= 0.78539816339f;;
  1173. break;
  1174. case HollowShape.Triangle:
  1175. hollowVolume *= 0.5f * 0.5f;
  1176. break;
  1177. default:
  1178. hollowVolume = 0;
  1179. break;
  1180. }
  1181. volume *= (1.0f - hollowVolume);
  1182. }
  1183. }
  1184. break;
  1185. case ProfileShape.Circle:
  1186. if (BaseShape.PathCurve == (byte)Extrusion.Straight)
  1187. {
  1188. volume *= 0.78539816339f; // elipse base
  1189. if (hollowAmount > 0.0)
  1190. {
  1191. switch (BaseShape.HollowShape)
  1192. {
  1193. case HollowShape.Same:
  1194. case HollowShape.Circle:
  1195. break;
  1196. case HollowShape.Square:
  1197. hollowVolume *= 0.5f * 2.5984480504799f;
  1198. break;
  1199. case HollowShape.Triangle:
  1200. hollowVolume *= .5f * 1.27323954473516f;
  1201. break;
  1202. default:
  1203. hollowVolume = 0;
  1204. break;
  1205. }
  1206. volume *= (1.0f - hollowVolume);
  1207. }
  1208. }
  1209. else if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1210. {
  1211. volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - BaseShape.PathScaleX);
  1212. tmp = 1.0f - .02f * (float)(200 - BaseShape.PathScaleY);
  1213. volume *= (1.0f - tmp * tmp);
  1214. if (hollowAmount > 0.0)
  1215. {
  1216. // calculate the hollow volume by it's shape compared to the prim shape
  1217. hollowVolume *= hollowAmount;
  1218. switch (BaseShape.HollowShape)
  1219. {
  1220. case HollowShape.Same:
  1221. case HollowShape.Circle:
  1222. break;
  1223. case HollowShape.Square:
  1224. hollowVolume *= 0.5f * 2.5984480504799f;
  1225. break;
  1226. case HollowShape.Triangle:
  1227. hollowVolume *= .5f * 1.27323954473516f;
  1228. break;
  1229. default:
  1230. hollowVolume = 0;
  1231. break;
  1232. }
  1233. volume *= (1.0f - hollowVolume);
  1234. }
  1235. }
  1236. break;
  1237. case ProfileShape.HalfCircle:
  1238. if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1239. {
  1240. volume *= 0.52359877559829887307710723054658f;
  1241. }
  1242. break;
  1243. case ProfileShape.EquilateralTriangle:
  1244. if (BaseShape.PathCurve == (byte)Extrusion.Straight)
  1245. {
  1246. volume *= 0.32475953f;
  1247. if (hollowAmount > 0.0)
  1248. {
  1249. // calculate the hollow volume by it's shape compared to the prim shape
  1250. switch (BaseShape.HollowShape)
  1251. {
  1252. case HollowShape.Same:
  1253. case HollowShape.Triangle:
  1254. hollowVolume *= .25f;
  1255. break;
  1256. case HollowShape.Square:
  1257. hollowVolume *= 0.499849f * 3.07920140172638f;
  1258. break;
  1259. case HollowShape.Circle:
  1260. // Hollow shape is a perfect cyllinder in respect to the cube's scale
  1261. // Cyllinder hollow volume calculation
  1262. hollowVolume *= 0.1963495f * 3.07920140172638f;
  1263. break;
  1264. default:
  1265. hollowVolume = 0;
  1266. break;
  1267. }
  1268. volume *= (1.0f - hollowVolume);
  1269. }
  1270. }
  1271. else if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1272. {
  1273. volume *= 0.32475953f;
  1274. volume *= 0.01f * (float)(200 - BaseShape.PathScaleX);
  1275. tmp = 1.0f - .02f * (float)(200 - BaseShape.PathScaleY);
  1276. volume *= (1.0f - tmp * tmp);
  1277. if (hollowAmount > 0.0)
  1278. {
  1279. hollowVolume *= hollowAmount;
  1280. switch (BaseShape.HollowShape)
  1281. {
  1282. case HollowShape.Same:
  1283. case HollowShape.Triangle:
  1284. hollowVolume *= .25f;
  1285. break;
  1286. case HollowShape.Square:
  1287. hollowVolume *= 0.499849f * 3.07920140172638f;
  1288. break;
  1289. case HollowShape.Circle:
  1290. hollowVolume *= 0.1963495f * 3.07920140172638f;
  1291. break;
  1292. default:
  1293. hollowVolume = 0;
  1294. break;
  1295. }
  1296. volume *= (1.0f - hollowVolume);
  1297. }
  1298. }
  1299. break;
  1300. default:
  1301. break;
  1302. }
  1303. float taperX1;
  1304. float taperY1;
  1305. float taperX;
  1306. float taperY;
  1307. float pathBegin;
  1308. float pathEnd;
  1309. float profileBegin;
  1310. float profileEnd;
  1311. if (BaseShape.PathCurve == (byte)Extrusion.Straight || BaseShape.PathCurve == (byte)Extrusion.Flexible)
  1312. {
  1313. taperX1 = BaseShape.PathScaleX * 0.01f;
  1314. if (taperX1 > 1.0f)
  1315. taperX1 = 2.0f - taperX1;
  1316. taperX = 1.0f - taperX1;
  1317. taperY1 = BaseShape.PathScaleY * 0.01f;
  1318. if (taperY1 > 1.0f)
  1319. taperY1 = 2.0f - taperY1;
  1320. taperY = 1.0f - taperY1;
  1321. }
  1322. else
  1323. {
  1324. taperX = BaseShape.PathTaperX * 0.01f;
  1325. if (taperX < 0.0f)
  1326. taperX = -taperX;
  1327. taperX1 = 1.0f - taperX;
  1328. taperY = BaseShape.PathTaperY * 0.01f;
  1329. if (taperY < 0.0f)
  1330. taperY = -taperY;
  1331. taperY1 = 1.0f - taperY;
  1332. }
  1333. volume *= (taperX1 * taperY1 + 0.5f * (taperX1 * taperY + taperX * taperY1) + 0.3333333333f * taperX * taperY);
  1334. pathBegin = (float)BaseShape.PathBegin * 2.0e-5f;
  1335. pathEnd = 1.0f - (float)BaseShape.PathEnd * 2.0e-5f;
  1336. volume *= (pathEnd - pathBegin);
  1337. // this is crude aproximation
  1338. profileBegin = (float)BaseShape.ProfileBegin * 2.0e-5f;
  1339. profileEnd = 1.0f - (float)BaseShape.ProfileEnd * 2.0e-5f;
  1340. volume *= (profileEnd - profileBegin);
  1341. returnMass = Density * BSParam.DensityScaleFactor * volume;
  1342. returnMass = Util.Clamp(returnMass, BSParam.MinimumObjectMass, BSParam.MaximumObjectMass);
  1343. // DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3}", LocalID, Density, volume, returnMass);
  1344. DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3},pathB={4},pathE={5},profB={6},profE={7},siz={8}",
  1345. LocalID, Density, volume, returnMass, pathBegin, pathEnd, profileBegin, profileEnd, _size);
  1346. return returnMass;
  1347. }// end CalculateMass
  1348. #endregion Mass Calculation
  1349. // Rebuild the geometry and object.
  1350. // This is called when the shape changes so we need to recreate the mesh/hull.
  1351. // Called at taint-time!!!
  1352. public void CreateGeomAndObject(bool forceRebuild)
  1353. {
  1354. // Create the correct physical representation for this type of object.
  1355. // Updates base.PhysBody and base.PhysShape with the new information.
  1356. // Ignore 'forceRebuild'. 'GetBodyAndShape' makes the right choices and changes of necessary.
  1357. PhysScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysScene.World, this, delegate(BulletBody pBody, BulletShape pShape)
  1358. {
  1359. // Called if the current prim body is about to be destroyed.
  1360. // Remove all the physical dependencies on the old body.
  1361. // (Maybe someday make the changing of BSShape an event to be subscribed to by BSLinkset, ...)
  1362. // Note: this virtual function is overloaded by BSPrimLinkable to remove linkset constraints.
  1363. RemoveDependencies();
  1364. });
  1365. // Make sure the properties are set on the new object
  1366. UpdatePhysicalParameters();
  1367. return;
  1368. }
  1369. // Called at taint-time
  1370. protected virtual void RemoveDependencies()
  1371. {
  1372. PhysicalActors.RemoveDependencies();
  1373. }
  1374. #region Extension
  1375. public override object Extension(string pFunct, params object[] pParams)
  1376. {
  1377. object ret = null;
  1378. switch (pFunct)
  1379. {
  1380. case BSScene.PhysFunctGetLinksetType:
  1381. {
  1382. BSPrimLinkable myHandle = this as BSPrimLinkable;
  1383. if (myHandle != null)
  1384. {
  1385. ret = (object)myHandle.LinksetType;
  1386. }
  1387. m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret);
  1388. break;
  1389. }
  1390. case BSScene.PhysFunctSetLinksetType:
  1391. {
  1392. if (pParams.Length > 0)
  1393. {
  1394. BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0];
  1395. BSPrimLinkable myHandle = this as BSPrimLinkable;
  1396. if (myHandle != null && myHandle.Linkset.IsRoot(myHandle))
  1397. {
  1398. PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate()
  1399. {
  1400. // Cause the linkset type to change
  1401. m_log.DebugFormat("{0} Extension.physSetLinksetType, oldType={1}, newType={2}",
  1402. LogHeader, myHandle.Linkset.LinksetImpl, linksetType);
  1403. myHandle.ConvertLinkset(linksetType);
  1404. });
  1405. }
  1406. ret = (object)(int)linksetType;
  1407. }
  1408. break;
  1409. }
  1410. default:
  1411. ret = base.Extension(pFunct, pParams);
  1412. break;
  1413. }
  1414. return ret;
  1415. }
  1416. #endregion // Extension
  1417. // The physics engine says that properties have updated. Update same and inform
  1418. // the world that things have changed.
  1419. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimLinkable which modifies updates from root and children prims.
  1420. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimDisplaced which handles mapping physical position to simulator position.
  1421. public override void UpdateProperties(EntityProperties entprop)
  1422. {
  1423. // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
  1424. TriggerPreUpdatePropertyAction(ref entprop);
  1425. // DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG
  1426. // Assign directly to the local variables so the normal set actions do not happen
  1427. RawPosition = entprop.Position;
  1428. RawOrientation = entprop.Rotation;
  1429. // DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be
  1430. // very sensitive to velocity changes.
  1431. if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold))
  1432. RawVelocity = entprop.Velocity;
  1433. _acceleration = entprop.Acceleration;
  1434. _rotationalVelocity = entprop.RotationalVelocity;
  1435. // DetailLog("{0},BSPrim.UpdateProperties,afterAssign,entprop={1}", LocalID, entprop); // DEBUG DEBUG
  1436. // The sanity check can change the velocity and/or position.
  1437. if (PositionSanityCheck(true /* inTaintTime */ ))
  1438. {
  1439. entprop.Position = RawPosition;
  1440. entprop.Velocity = RawVelocity;
  1441. entprop.RotationalVelocity = _rotationalVelocity;
  1442. entprop.Acceleration = _acceleration;
  1443. }
  1444. OMV.Vector3 direction = OMV.Vector3.UnitX * RawOrientation; // DEBUG DEBUG DEBUG
  1445. DetailLog("{0},BSPrim.UpdateProperties,call,entProp={1},dir={2}", LocalID, entprop, direction);
  1446. // remember the current and last set values
  1447. LastEntityProperties = CurrentEntityProperties;
  1448. CurrentEntityProperties = entprop;
  1449. PhysScene.PostUpdate(this);
  1450. }
  1451. }
  1452. }