BSDynamics.cs 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. *
  27. * The quotations from http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial
  28. * are Copyright (c) 2009 Linden Research, Inc and are used under their license
  29. * of Creative Commons Attribution-Share Alike 3.0
  30. * (http://creativecommons.org/licenses/by-sa/3.0/).
  31. */
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Reflection;
  35. using System.Runtime.InteropServices;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Physics.Manager;
  39. namespace OpenSim.Region.Physics.BulletSPlugin
  40. {
  41. public sealed class BSDynamics : BSActor
  42. {
  43. private static string LogHeader = "[BULLETSIM VEHICLE]";
  44. // the prim this dynamic controller belongs to
  45. private BSPrim ControllingPrim { get; set; }
  46. private bool m_haveRegisteredForSceneEvents;
  47. // mass of the vehicle fetched each time we're calles
  48. private float m_vehicleMass;
  49. // Vehicle properties
  50. public Vehicle Type { get; set; }
  51. // private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier
  52. private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings:
  53. // HOVER_TERRAIN_ONLY
  54. // HOVER_GLOBAL_HEIGHT
  55. // NO_DEFLECTION_UP
  56. // HOVER_WATER_ONLY
  57. // HOVER_UP_ONLY
  58. // LIMIT_MOTOR_UP
  59. // LIMIT_ROLL_ONLY
  60. private Vector3 m_BlockingEndPoint = Vector3.Zero;
  61. private Quaternion m_RollreferenceFrame = Quaternion.Identity;
  62. private Quaternion m_referenceFrame = Quaternion.Identity;
  63. // Linear properties
  64. private BSVMotor m_linearMotor = new BSVMotor("LinearMotor");
  65. private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time
  66. private Vector3 m_linearMotorOffset = Vector3.Zero; // the point of force can be offset from the center
  67. private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL
  68. private Vector3 m_linearFrictionTimescale = Vector3.Zero;
  69. private float m_linearMotorDecayTimescale = 0;
  70. private float m_linearMotorTimescale = 0;
  71. private Vector3 m_lastLinearVelocityVector = Vector3.Zero;
  72. private Vector3 m_lastPositionVector = Vector3.Zero;
  73. // private bool m_LinearMotorSetLastFrame = false;
  74. // private Vector3 m_linearMotorOffset = Vector3.Zero;
  75. //Angular properties
  76. private BSVMotor m_angularMotor = new BSVMotor("AngularMotor");
  77. private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
  78. // private int m_angularMotorApply = 0; // application frame counter
  79. private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity
  80. private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
  81. private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
  82. private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
  83. private Vector3 m_lastAngularVelocity = Vector3.Zero;
  84. private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body
  85. //Deflection properties
  86. private BSVMotor m_angularDeflectionMotor = new BSVMotor("AngularDeflection");
  87. private float m_angularDeflectionEfficiency = 0;
  88. private float m_angularDeflectionTimescale = 0;
  89. private float m_linearDeflectionEfficiency = 0;
  90. private float m_linearDeflectionTimescale = 0;
  91. //Banking properties
  92. private float m_bankingEfficiency = 0;
  93. private float m_bankingMix = 0;
  94. private float m_bankingTimescale = 0;
  95. //Hover and Buoyancy properties
  96. private BSVMotor m_hoverMotor = new BSVMotor("Hover");
  97. private float m_VhoverHeight = 0f;
  98. private float m_VhoverEfficiency = 0f;
  99. private float m_VhoverTimescale = 0f;
  100. private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height
  101. // Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity)
  102. private float m_VehicleBuoyancy = 0f;
  103. private Vector3 m_VehicleGravity = Vector3.Zero; // Gravity computed when buoyancy set
  104. //Attractor properties
  105. private BSVMotor m_verticalAttractionMotor = new BSVMotor("VerticalAttraction");
  106. private float m_verticalAttractionEfficiency = 1.0f; // damped
  107. private float m_verticalAttractionCutoff = 500f; // per the documentation
  108. // Timescale > cutoff means no vert attractor.
  109. private float m_verticalAttractionTimescale = 510f;
  110. // Just some recomputed constants:
  111. static readonly float PIOverFour = ((float)Math.PI) / 4f;
  112. static readonly float PIOverTwo = ((float)Math.PI) / 2f;
  113. public BSDynamics(BSScene myScene, BSPrim myPrim, string actorName)
  114. : base(myScene, myPrim, actorName)
  115. {
  116. ControllingPrim = myPrim;
  117. Type = Vehicle.TYPE_NONE;
  118. m_haveRegisteredForSceneEvents = false;
  119. }
  120. // Return 'true' if this vehicle is doing vehicle things
  121. public bool IsActive
  122. {
  123. get { return (Type != Vehicle.TYPE_NONE && ControllingPrim.IsPhysicallyActive); }
  124. }
  125. // Return 'true' if this a vehicle that should be sitting on the ground
  126. public bool IsGroundVehicle
  127. {
  128. get { return (Type == Vehicle.TYPE_CAR || Type == Vehicle.TYPE_SLED); }
  129. }
  130. #region Vehicle parameter setting
  131. public void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
  132. {
  133. VDetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", ControllingPrim.LocalID, pParam, pValue);
  134. switch (pParam)
  135. {
  136. case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
  137. m_angularDeflectionEfficiency = ClampInRange(0f, pValue, 1f);
  138. break;
  139. case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
  140. m_angularDeflectionTimescale = Math.Max(pValue, 0.01f);
  141. break;
  142. case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
  143. m_angularMotorDecayTimescale = ClampInRange(0.01f, pValue, 120);
  144. m_angularMotor.TargetValueDecayTimeScale = m_angularMotorDecayTimescale;
  145. break;
  146. case Vehicle.ANGULAR_MOTOR_TIMESCALE:
  147. m_angularMotorTimescale = Math.Max(pValue, 0.01f);
  148. m_angularMotor.TimeScale = m_angularMotorTimescale;
  149. break;
  150. case Vehicle.BANKING_EFFICIENCY:
  151. m_bankingEfficiency = ClampInRange(-1f, pValue, 1f);
  152. break;
  153. case Vehicle.BANKING_MIX:
  154. m_bankingMix = Math.Max(pValue, 0.01f);
  155. break;
  156. case Vehicle.BANKING_TIMESCALE:
  157. m_bankingTimescale = Math.Max(pValue, 0.01f);
  158. break;
  159. case Vehicle.BUOYANCY:
  160. m_VehicleBuoyancy = ClampInRange(-1f, pValue, 1f);
  161. m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy);
  162. break;
  163. case Vehicle.HOVER_EFFICIENCY:
  164. m_VhoverEfficiency = ClampInRange(0f, pValue, 1f);
  165. break;
  166. case Vehicle.HOVER_HEIGHT:
  167. m_VhoverHeight = pValue;
  168. break;
  169. case Vehicle.HOVER_TIMESCALE:
  170. m_VhoverTimescale = Math.Max(pValue, 0.01f);
  171. break;
  172. case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
  173. m_linearDeflectionEfficiency = ClampInRange(0f, pValue, 1f);
  174. break;
  175. case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
  176. m_linearDeflectionTimescale = Math.Max(pValue, 0.01f);
  177. break;
  178. case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
  179. m_linearMotorDecayTimescale = ClampInRange(0.01f, pValue, 120);
  180. m_linearMotor.TargetValueDecayTimeScale = m_linearMotorDecayTimescale;
  181. break;
  182. case Vehicle.LINEAR_MOTOR_TIMESCALE:
  183. m_linearMotorTimescale = Math.Max(pValue, 0.01f);
  184. m_linearMotor.TimeScale = m_linearMotorTimescale;
  185. break;
  186. case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
  187. m_verticalAttractionEfficiency = ClampInRange(0.1f, pValue, 1f);
  188. m_verticalAttractionMotor.Efficiency = m_verticalAttractionEfficiency;
  189. break;
  190. case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
  191. m_verticalAttractionTimescale = Math.Max(pValue, 0.01f);
  192. m_verticalAttractionMotor.TimeScale = m_verticalAttractionTimescale;
  193. break;
  194. // These are vector properties but the engine lets you use a single float value to
  195. // set all of the components to the same value
  196. case Vehicle.ANGULAR_FRICTION_TIMESCALE:
  197. m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
  198. break;
  199. case Vehicle.ANGULAR_MOTOR_DIRECTION:
  200. m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
  201. m_angularMotor.Zero();
  202. m_angularMotor.SetTarget(m_angularMotorDirection);
  203. break;
  204. case Vehicle.LINEAR_FRICTION_TIMESCALE:
  205. m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
  206. break;
  207. case Vehicle.LINEAR_MOTOR_DIRECTION:
  208. m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
  209. m_linearMotorDirectionLASTSET = new Vector3(pValue, pValue, pValue);
  210. m_linearMotor.SetTarget(m_linearMotorDirection);
  211. break;
  212. case Vehicle.LINEAR_MOTOR_OFFSET:
  213. m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
  214. break;
  215. }
  216. }//end ProcessFloatVehicleParam
  217. internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
  218. {
  219. VDetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", ControllingPrim.LocalID, pParam, pValue);
  220. switch (pParam)
  221. {
  222. case Vehicle.ANGULAR_FRICTION_TIMESCALE:
  223. m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
  224. break;
  225. case Vehicle.ANGULAR_MOTOR_DIRECTION:
  226. // Limit requested angular speed to 2 rps= 4 pi rads/sec
  227. pValue.X = ClampInRange(-12.56f, pValue.X, 12.56f);
  228. pValue.Y = ClampInRange(-12.56f, pValue.Y, 12.56f);
  229. pValue.Z = ClampInRange(-12.56f, pValue.Z, 12.56f);
  230. m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
  231. m_angularMotor.Zero();
  232. m_angularMotor.SetTarget(m_angularMotorDirection);
  233. break;
  234. case Vehicle.LINEAR_FRICTION_TIMESCALE:
  235. m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
  236. break;
  237. case Vehicle.LINEAR_MOTOR_DIRECTION:
  238. m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
  239. m_linearMotorDirectionLASTSET = new Vector3(pValue.X, pValue.Y, pValue.Z);
  240. m_linearMotor.SetTarget(m_linearMotorDirection);
  241. break;
  242. case Vehicle.LINEAR_MOTOR_OFFSET:
  243. m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
  244. break;
  245. case Vehicle.BLOCK_EXIT:
  246. m_BlockingEndPoint = new Vector3(pValue.X, pValue.Y, pValue.Z);
  247. break;
  248. }
  249. }//end ProcessVectorVehicleParam
  250. internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
  251. {
  252. VDetailLog("{0},ProcessRotationalVehicleParam,param={1},val={2}", ControllingPrim.LocalID, pParam, pValue);
  253. switch (pParam)
  254. {
  255. case Vehicle.REFERENCE_FRAME:
  256. m_referenceFrame = pValue;
  257. break;
  258. case Vehicle.ROLL_FRAME:
  259. m_RollreferenceFrame = pValue;
  260. break;
  261. }
  262. }//end ProcessRotationVehicleParam
  263. internal void ProcessVehicleFlags(int pParam, bool remove)
  264. {
  265. VDetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", ControllingPrim.LocalID, pParam, remove);
  266. VehicleFlag parm = (VehicleFlag)pParam;
  267. if (pParam == -1)
  268. m_flags = (VehicleFlag)0;
  269. else
  270. {
  271. if (remove)
  272. m_flags &= ~parm;
  273. else
  274. m_flags |= parm;
  275. }
  276. }
  277. public void ProcessTypeChange(Vehicle pType)
  278. {
  279. VDetailLog("{0},ProcessTypeChange,type={1}", ControllingPrim.LocalID, pType);
  280. // Set Defaults For Type
  281. Type = pType;
  282. switch (pType)
  283. {
  284. case Vehicle.TYPE_NONE:
  285. m_linearMotorDirection = Vector3.Zero;
  286. m_linearMotorTimescale = 0;
  287. m_linearMotorDecayTimescale = 0;
  288. m_linearFrictionTimescale = new Vector3(0, 0, 0);
  289. m_angularMotorDirection = Vector3.Zero;
  290. m_angularMotorDecayTimescale = 0;
  291. m_angularMotorTimescale = 0;
  292. m_angularFrictionTimescale = new Vector3(0, 0, 0);
  293. m_VhoverHeight = 0;
  294. m_VhoverEfficiency = 0;
  295. m_VhoverTimescale = 0;
  296. m_VehicleBuoyancy = 0;
  297. m_linearDeflectionEfficiency = 1;
  298. m_linearDeflectionTimescale = 1;
  299. m_angularDeflectionEfficiency = 0;
  300. m_angularDeflectionTimescale = 1000;
  301. m_verticalAttractionEfficiency = 0;
  302. m_verticalAttractionTimescale = 0;
  303. m_bankingEfficiency = 0;
  304. m_bankingTimescale = 1000;
  305. m_bankingMix = 1;
  306. m_referenceFrame = Quaternion.Identity;
  307. m_flags = (VehicleFlag)0;
  308. break;
  309. case Vehicle.TYPE_SLED:
  310. m_linearMotorDirection = Vector3.Zero;
  311. m_linearMotorTimescale = 1000;
  312. m_linearMotorDecayTimescale = 120;
  313. m_linearFrictionTimescale = new Vector3(30, 1, 1000);
  314. m_angularMotorDirection = Vector3.Zero;
  315. m_angularMotorTimescale = 1000;
  316. m_angularMotorDecayTimescale = 120;
  317. m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
  318. m_VhoverHeight = 0;
  319. m_VhoverEfficiency = 10; // TODO: this looks wrong!!
  320. m_VhoverTimescale = 10;
  321. m_VehicleBuoyancy = 0;
  322. m_linearDeflectionEfficiency = 1;
  323. m_linearDeflectionTimescale = 1;
  324. m_angularDeflectionEfficiency = 1;
  325. m_angularDeflectionTimescale = 1000;
  326. m_verticalAttractionEfficiency = 0;
  327. m_verticalAttractionTimescale = 0;
  328. m_bankingEfficiency = 0;
  329. m_bankingTimescale = 10;
  330. m_bankingMix = 1;
  331. m_referenceFrame = Quaternion.Identity;
  332. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  333. | VehicleFlag.HOVER_TERRAIN_ONLY
  334. | VehicleFlag.HOVER_GLOBAL_HEIGHT
  335. | VehicleFlag.HOVER_UP_ONLY);
  336. m_flags |= (VehicleFlag.NO_DEFLECTION_UP
  337. | VehicleFlag.LIMIT_ROLL_ONLY
  338. | VehicleFlag.LIMIT_MOTOR_UP);
  339. break;
  340. case Vehicle.TYPE_CAR:
  341. m_linearMotorDirection = Vector3.Zero;
  342. m_linearMotorTimescale = 1;
  343. m_linearMotorDecayTimescale = 60;
  344. m_linearFrictionTimescale = new Vector3(100, 2, 1000);
  345. m_angularMotorDirection = Vector3.Zero;
  346. m_angularMotorTimescale = 1;
  347. m_angularMotorDecayTimescale = 0.8f;
  348. m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
  349. m_VhoverHeight = 0;
  350. m_VhoverEfficiency = 0;
  351. m_VhoverTimescale = 1000;
  352. m_VehicleBuoyancy = 0;
  353. m_linearDeflectionEfficiency = 1;
  354. m_linearDeflectionTimescale = 2;
  355. m_angularDeflectionEfficiency = 0;
  356. m_angularDeflectionTimescale = 10;
  357. m_verticalAttractionEfficiency = 1f;
  358. m_verticalAttractionTimescale = 10f;
  359. m_bankingEfficiency = -0.2f;
  360. m_bankingMix = 1;
  361. m_bankingTimescale = 1;
  362. m_referenceFrame = Quaternion.Identity;
  363. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  364. | VehicleFlag.HOVER_TERRAIN_ONLY
  365. | VehicleFlag.HOVER_GLOBAL_HEIGHT);
  366. m_flags |= (VehicleFlag.NO_DEFLECTION_UP
  367. | VehicleFlag.LIMIT_ROLL_ONLY
  368. | VehicleFlag.LIMIT_MOTOR_UP
  369. | VehicleFlag.HOVER_UP_ONLY);
  370. break;
  371. case Vehicle.TYPE_BOAT:
  372. m_linearMotorDirection = Vector3.Zero;
  373. m_linearMotorTimescale = 5;
  374. m_linearMotorDecayTimescale = 60;
  375. m_linearFrictionTimescale = new Vector3(10, 3, 2);
  376. m_angularMotorDirection = Vector3.Zero;
  377. m_angularMotorTimescale = 4;
  378. m_angularMotorDecayTimescale = 4;
  379. m_angularFrictionTimescale = new Vector3(10,10,10);
  380. m_VhoverHeight = 0;
  381. m_VhoverEfficiency = 0.5f;
  382. m_VhoverTimescale = 2;
  383. m_VehicleBuoyancy = 1;
  384. m_linearDeflectionEfficiency = 0.5f;
  385. m_linearDeflectionTimescale = 3;
  386. m_angularDeflectionEfficiency = 0.5f;
  387. m_angularDeflectionTimescale = 5;
  388. m_verticalAttractionEfficiency = 0.5f;
  389. m_verticalAttractionTimescale = 5f;
  390. m_bankingEfficiency = -0.3f;
  391. m_bankingMix = 0.8f;
  392. m_bankingTimescale = 1;
  393. m_referenceFrame = Quaternion.Identity;
  394. m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY
  395. | VehicleFlag.HOVER_GLOBAL_HEIGHT
  396. | VehicleFlag.LIMIT_ROLL_ONLY
  397. | VehicleFlag.HOVER_UP_ONLY);
  398. m_flags |= (VehicleFlag.NO_DEFLECTION_UP
  399. | VehicleFlag.LIMIT_MOTOR_UP
  400. | VehicleFlag.HOVER_WATER_ONLY);
  401. break;
  402. case Vehicle.TYPE_AIRPLANE:
  403. m_linearMotorDirection = Vector3.Zero;
  404. m_linearMotorTimescale = 2;
  405. m_linearMotorDecayTimescale = 60;
  406. m_linearFrictionTimescale = new Vector3(200, 10, 5);
  407. m_angularMotorDirection = Vector3.Zero;
  408. m_angularMotorTimescale = 4;
  409. m_angularMotorDecayTimescale = 4;
  410. m_angularFrictionTimescale = new Vector3(20, 20, 20);
  411. m_VhoverHeight = 0;
  412. m_VhoverEfficiency = 0.5f;
  413. m_VhoverTimescale = 1000;
  414. m_VehicleBuoyancy = 0;
  415. m_linearDeflectionEfficiency = 0.5f;
  416. m_linearDeflectionTimescale = 3;
  417. m_angularDeflectionEfficiency = 1;
  418. m_angularDeflectionTimescale = 2;
  419. m_verticalAttractionEfficiency = 0.9f;
  420. m_verticalAttractionTimescale = 2f;
  421. m_bankingEfficiency = 1;
  422. m_bankingMix = 0.7f;
  423. m_bankingTimescale = 2;
  424. m_referenceFrame = Quaternion.Identity;
  425. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  426. | VehicleFlag.HOVER_TERRAIN_ONLY
  427. | VehicleFlag.HOVER_GLOBAL_HEIGHT
  428. | VehicleFlag.HOVER_UP_ONLY
  429. | VehicleFlag.NO_DEFLECTION_UP
  430. | VehicleFlag.LIMIT_MOTOR_UP);
  431. m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
  432. break;
  433. case Vehicle.TYPE_BALLOON:
  434. m_linearMotorDirection = Vector3.Zero;
  435. m_linearMotorTimescale = 5;
  436. m_linearFrictionTimescale = new Vector3(5, 5, 5);
  437. m_linearMotorDecayTimescale = 60;
  438. m_angularMotorDirection = Vector3.Zero;
  439. m_angularMotorTimescale = 6;
  440. m_angularFrictionTimescale = new Vector3(10, 10, 10);
  441. m_angularMotorDecayTimescale = 10;
  442. m_VhoverHeight = 5;
  443. m_VhoverEfficiency = 0.8f;
  444. m_VhoverTimescale = 10;
  445. m_VehicleBuoyancy = 1;
  446. m_linearDeflectionEfficiency = 0;
  447. m_linearDeflectionTimescale = 5;
  448. m_angularDeflectionEfficiency = 0;
  449. m_angularDeflectionTimescale = 5;
  450. m_verticalAttractionEfficiency = 1f;
  451. m_verticalAttractionTimescale = 100f;
  452. m_bankingEfficiency = 0;
  453. m_bankingMix = 0.7f;
  454. m_bankingTimescale = 5;
  455. m_referenceFrame = Quaternion.Identity;
  456. m_referenceFrame = Quaternion.Identity;
  457. m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY
  458. | VehicleFlag.HOVER_TERRAIN_ONLY
  459. | VehicleFlag.HOVER_UP_ONLY
  460. | VehicleFlag.NO_DEFLECTION_UP
  461. | VehicleFlag.LIMIT_MOTOR_UP);
  462. m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY
  463. | VehicleFlag.HOVER_GLOBAL_HEIGHT);
  464. break;
  465. }
  466. m_linearMotor = new BSVMotor("LinearMotor", m_linearMotorTimescale, m_linearMotorDecayTimescale, 1f);
  467. // m_linearMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging)
  468. m_angularMotor = new BSVMotor("AngularMotor", m_angularMotorTimescale, m_angularMotorDecayTimescale, 1f);
  469. // m_angularMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging)
  470. /* Not implemented
  471. m_verticalAttractionMotor = new BSVMotor("VerticalAttraction", m_verticalAttractionTimescale,
  472. BSMotor.Infinite, BSMotor.InfiniteVector,
  473. m_verticalAttractionEfficiency);
  474. // Z goes away and we keep X and Y
  475. m_verticalAttractionMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG DEBUG (enables detail logging)
  476. */
  477. if (this.Type == Vehicle.TYPE_NONE)
  478. {
  479. UnregisterForSceneEvents();
  480. }
  481. else
  482. {
  483. RegisterForSceneEvents();
  484. }
  485. // Update any physical parameters based on this type.
  486. Refresh();
  487. }
  488. #endregion // Vehicle parameter setting
  489. // BSActor.Refresh()
  490. public override void Refresh()
  491. {
  492. // If asking for a refresh, reset the physical parameters before the next simulation step.
  493. // Called whether active or not since the active state may be updated before the next step.
  494. m_physicsScene.PostTaintObject("BSDynamics.Refresh", ControllingPrim.LocalID, delegate()
  495. {
  496. SetPhysicalParameters();
  497. });
  498. }
  499. // Some of the properties of this prim may have changed.
  500. // Do any updating needed for a vehicle
  501. private void SetPhysicalParameters()
  502. {
  503. if (IsActive)
  504. {
  505. // Remember the mass so we don't have to fetch it every step
  506. m_vehicleMass = ControllingPrim.TotalMass;
  507. // Friction affects are handled by this vehicle code
  508. m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction);
  509. m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution);
  510. // Moderate angular movement introduced by Bullet.
  511. // TODO: possibly set AngularFactor and LinearFactor for the type of vehicle.
  512. // Maybe compute linear and angular factor and damping from params.
  513. m_physicsScene.PE.SetAngularDamping(ControllingPrim.PhysBody, BSParam.VehicleAngularDamping);
  514. m_physicsScene.PE.SetLinearFactor(ControllingPrim.PhysBody, BSParam.VehicleLinearFactor);
  515. m_physicsScene.PE.SetAngularFactorV(ControllingPrim.PhysBody, BSParam.VehicleAngularFactor);
  516. // Vehicles report collision events so we know when it's on the ground
  517. m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS);
  518. Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass);
  519. ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor;
  520. m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia);
  521. m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody);
  522. // Set the gravity for the vehicle depending on the buoyancy
  523. // TODO: what should be done if prim and vehicle buoyancy differ?
  524. m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy);
  525. // The actual vehicle gravity is set to zero in Bullet so we can do all the application of same.
  526. m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero);
  527. VDetailLog("{0},BSDynamics.SetPhysicalParameters,mass={1},inert={2},vehGrav={3},aDamp={4},frict={5},rest={6},lFact={7},aFact={8}",
  528. ControllingPrim.LocalID, m_vehicleMass, ControllingPrim.Inertia, m_VehicleGravity,
  529. BSParam.VehicleAngularDamping, BSParam.VehicleFriction, BSParam.VehicleRestitution,
  530. BSParam.VehicleLinearFactor, BSParam.VehicleAngularFactor
  531. );
  532. }
  533. else
  534. {
  535. if (ControllingPrim.PhysBody.HasPhysicalBody)
  536. m_physicsScene.PE.RemoveFromCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS);
  537. }
  538. }
  539. // BSActor.RemoveBodyDependencies
  540. public override void RemoveDependencies()
  541. {
  542. Refresh();
  543. }
  544. // BSActor.Release()
  545. public override void Dispose()
  546. {
  547. UnregisterForSceneEvents();
  548. Type = Vehicle.TYPE_NONE;
  549. Enabled = false;
  550. return;
  551. }
  552. private void RegisterForSceneEvents()
  553. {
  554. if (!m_haveRegisteredForSceneEvents)
  555. {
  556. m_physicsScene.BeforeStep += this.Step;
  557. m_physicsScene.AfterStep += this.PostStep;
  558. ControllingPrim.OnPreUpdateProperty += this.PreUpdateProperty;
  559. m_haveRegisteredForSceneEvents = true;
  560. }
  561. }
  562. private void UnregisterForSceneEvents()
  563. {
  564. if (m_haveRegisteredForSceneEvents)
  565. {
  566. m_physicsScene.BeforeStep -= this.Step;
  567. m_physicsScene.AfterStep -= this.PostStep;
  568. ControllingPrim.OnPreUpdateProperty -= this.PreUpdateProperty;
  569. m_haveRegisteredForSceneEvents = false;
  570. }
  571. }
  572. private void PreUpdateProperty(ref EntityProperties entprop)
  573. {
  574. // A temporary kludge to suppress the rotational effects introduced on vehicles by Bullet
  575. // TODO: handle physics introduced by Bullet with computed vehicle physics.
  576. if (IsActive)
  577. {
  578. entprop.RotationalVelocity = Vector3.Zero;
  579. }
  580. }
  581. #region Known vehicle value functions
  582. // Vehicle physical parameters that we buffer from constant getting and setting.
  583. // The "m_known*" values are unknown until they are fetched and the m_knownHas flag is set.
  584. // Changing is remembered and the parameter is stored back into the physics engine only if updated.
  585. // This does two things: 1) saves continuious calls into unmanaged code, and
  586. // 2) signals when a physics property update must happen back to the simulator
  587. // to update values modified for the vehicle.
  588. private int m_knownChanged;
  589. private int m_knownHas;
  590. private float m_knownTerrainHeight;
  591. private float m_knownWaterLevel;
  592. private Vector3 m_knownPosition;
  593. private Vector3 m_knownVelocity;
  594. private Vector3 m_knownForce;
  595. private Vector3 m_knownForceImpulse;
  596. private Quaternion m_knownOrientation;
  597. private Vector3 m_knownRotationalVelocity;
  598. private Vector3 m_knownRotationalForce;
  599. private Vector3 m_knownRotationalImpulse;
  600. private const int m_knownChangedPosition = 1 << 0;
  601. private const int m_knownChangedVelocity = 1 << 1;
  602. private const int m_knownChangedForce = 1 << 2;
  603. private const int m_knownChangedForceImpulse = 1 << 3;
  604. private const int m_knownChangedOrientation = 1 << 4;
  605. private const int m_knownChangedRotationalVelocity = 1 << 5;
  606. private const int m_knownChangedRotationalForce = 1 << 6;
  607. private const int m_knownChangedRotationalImpulse = 1 << 7;
  608. private const int m_knownChangedTerrainHeight = 1 << 8;
  609. private const int m_knownChangedWaterLevel = 1 << 9;
  610. public void ForgetKnownVehicleProperties()
  611. {
  612. m_knownHas = 0;
  613. m_knownChanged = 0;
  614. }
  615. // Push all the changed values back into the physics engine
  616. public void PushKnownChanged()
  617. {
  618. if (m_knownChanged != 0)
  619. {
  620. if ((m_knownChanged & m_knownChangedPosition) != 0)
  621. ControllingPrim.ForcePosition = m_knownPosition;
  622. if ((m_knownChanged & m_knownChangedOrientation) != 0)
  623. ControllingPrim.ForceOrientation = m_knownOrientation;
  624. if ((m_knownChanged & m_knownChangedVelocity) != 0)
  625. {
  626. ControllingPrim.ForceVelocity = m_knownVelocity;
  627. // Fake out Bullet by making it think the velocity is the same as last time.
  628. // Bullet does a bunch of smoothing for changing parameters.
  629. // Since the vehicle is demanding this setting, we override Bullet's smoothing
  630. // by telling Bullet the value was the same last time.
  631. // PhysicsScene.PE.SetInterpolationLinearVelocity(Prim.PhysBody, m_knownVelocity);
  632. }
  633. if ((m_knownChanged & m_knownChangedForce) != 0)
  634. ControllingPrim.AddForce((Vector3)m_knownForce, false /*pushForce*/, true /*inTaintTime*/);
  635. if ((m_knownChanged & m_knownChangedForceImpulse) != 0)
  636. ControllingPrim.AddForceImpulse((Vector3)m_knownForceImpulse, false /*pushforce*/, true /*inTaintTime*/);
  637. if ((m_knownChanged & m_knownChangedRotationalVelocity) != 0)
  638. {
  639. ControllingPrim.ForceRotationalVelocity = m_knownRotationalVelocity;
  640. // PhysicsScene.PE.SetInterpolationAngularVelocity(Prim.PhysBody, m_knownRotationalVelocity);
  641. }
  642. if ((m_knownChanged & m_knownChangedRotationalImpulse) != 0)
  643. ControllingPrim.ApplyTorqueImpulse((Vector3)m_knownRotationalImpulse, true /*inTaintTime*/);
  644. if ((m_knownChanged & m_knownChangedRotationalForce) != 0)
  645. {
  646. ControllingPrim.AddAngularForce((Vector3)m_knownRotationalForce, false /*pushForce*/, true /*inTaintTime*/);
  647. }
  648. // If we set one of the values (ie, the physics engine didn't do it) we must force
  649. // an UpdateProperties event to send the changes up to the simulator.
  650. m_physicsScene.PE.PushUpdate(ControllingPrim.PhysBody);
  651. }
  652. m_knownChanged = 0;
  653. }
  654. // Since the computation of terrain height can be a little involved, this routine
  655. // is used to fetch the height only once for each vehicle simulation step.
  656. Vector3 lastRememberedHeightPos = new Vector3(-1, -1, -1);
  657. private float GetTerrainHeight(Vector3 pos)
  658. {
  659. if ((m_knownHas & m_knownChangedTerrainHeight) == 0 || pos != lastRememberedHeightPos)
  660. {
  661. lastRememberedHeightPos = pos;
  662. m_knownTerrainHeight = ControllingPrim.PhysScene.TerrainManager.GetTerrainHeightAtXYZ(pos);
  663. m_knownHas |= m_knownChangedTerrainHeight;
  664. }
  665. return m_knownTerrainHeight;
  666. }
  667. // Since the computation of water level can be a little involved, this routine
  668. // is used ot fetch the level only once for each vehicle simulation step.
  669. Vector3 lastRememberedWaterHeightPos = new Vector3(-1, -1, -1);
  670. private float GetWaterLevel(Vector3 pos)
  671. {
  672. if ((m_knownHas & m_knownChangedWaterLevel) == 0 || pos != lastRememberedWaterHeightPos)
  673. {
  674. lastRememberedWaterHeightPos = pos;
  675. m_knownWaterLevel = ControllingPrim.PhysScene.TerrainManager.GetWaterLevelAtXYZ(pos);
  676. m_knownHas |= m_knownChangedWaterLevel;
  677. }
  678. return m_knownWaterLevel;
  679. }
  680. private Vector3 VehiclePosition
  681. {
  682. get
  683. {
  684. if ((m_knownHas & m_knownChangedPosition) == 0)
  685. {
  686. m_knownPosition = ControllingPrim.ForcePosition;
  687. m_knownHas |= m_knownChangedPosition;
  688. }
  689. return m_knownPosition;
  690. }
  691. set
  692. {
  693. m_knownPosition = value;
  694. m_knownChanged |= m_knownChangedPosition;
  695. m_knownHas |= m_knownChangedPosition;
  696. }
  697. }
  698. private Quaternion VehicleOrientation
  699. {
  700. get
  701. {
  702. if ((m_knownHas & m_knownChangedOrientation) == 0)
  703. {
  704. m_knownOrientation = ControllingPrim.ForceOrientation;
  705. m_knownHas |= m_knownChangedOrientation;
  706. }
  707. return m_knownOrientation;
  708. }
  709. set
  710. {
  711. m_knownOrientation = value;
  712. m_knownChanged |= m_knownChangedOrientation;
  713. m_knownHas |= m_knownChangedOrientation;
  714. }
  715. }
  716. private Vector3 VehicleVelocity
  717. {
  718. get
  719. {
  720. if ((m_knownHas & m_knownChangedVelocity) == 0)
  721. {
  722. m_knownVelocity = ControllingPrim.ForceVelocity;
  723. m_knownHas |= m_knownChangedVelocity;
  724. }
  725. return m_knownVelocity;
  726. }
  727. set
  728. {
  729. m_knownVelocity = value;
  730. m_knownChanged |= m_knownChangedVelocity;
  731. m_knownHas |= m_knownChangedVelocity;
  732. }
  733. }
  734. private void VehicleAddForce(Vector3 pForce)
  735. {
  736. if ((m_knownHas & m_knownChangedForce) == 0)
  737. {
  738. m_knownForce = Vector3.Zero;
  739. m_knownHas |= m_knownChangedForce;
  740. }
  741. m_knownForce += pForce;
  742. m_knownChanged |= m_knownChangedForce;
  743. }
  744. private void VehicleAddForceImpulse(Vector3 pImpulse)
  745. {
  746. if ((m_knownHas & m_knownChangedForceImpulse) == 0)
  747. {
  748. m_knownForceImpulse = Vector3.Zero;
  749. m_knownHas |= m_knownChangedForceImpulse;
  750. }
  751. m_knownForceImpulse += pImpulse;
  752. m_knownChanged |= m_knownChangedForceImpulse;
  753. }
  754. private Vector3 VehicleRotationalVelocity
  755. {
  756. get
  757. {
  758. if ((m_knownHas & m_knownChangedRotationalVelocity) == 0)
  759. {
  760. m_knownRotationalVelocity = ControllingPrim.ForceRotationalVelocity;
  761. m_knownHas |= m_knownChangedRotationalVelocity;
  762. }
  763. return (Vector3)m_knownRotationalVelocity;
  764. }
  765. set
  766. {
  767. m_knownRotationalVelocity = value;
  768. m_knownChanged |= m_knownChangedRotationalVelocity;
  769. m_knownHas |= m_knownChangedRotationalVelocity;
  770. }
  771. }
  772. private void VehicleAddAngularForce(Vector3 aForce)
  773. {
  774. if ((m_knownHas & m_knownChangedRotationalForce) == 0)
  775. {
  776. m_knownRotationalForce = Vector3.Zero;
  777. }
  778. m_knownRotationalForce += aForce;
  779. m_knownChanged |= m_knownChangedRotationalForce;
  780. m_knownHas |= m_knownChangedRotationalForce;
  781. }
  782. private void VehicleAddRotationalImpulse(Vector3 pImpulse)
  783. {
  784. if ((m_knownHas & m_knownChangedRotationalImpulse) == 0)
  785. {
  786. m_knownRotationalImpulse = Vector3.Zero;
  787. m_knownHas |= m_knownChangedRotationalImpulse;
  788. }
  789. m_knownRotationalImpulse += pImpulse;
  790. m_knownChanged |= m_knownChangedRotationalImpulse;
  791. }
  792. // Vehicle relative forward velocity
  793. private Vector3 VehicleForwardVelocity
  794. {
  795. get
  796. {
  797. return VehicleVelocity * Quaternion.Inverse(Quaternion.Normalize(VehicleOrientation));
  798. }
  799. }
  800. private float VehicleForwardSpeed
  801. {
  802. get
  803. {
  804. return VehicleForwardVelocity.X;
  805. }
  806. }
  807. #endregion // Known vehicle value functions
  808. // One step of the vehicle properties for the next 'pTimestep' seconds.
  809. internal void Step(float pTimestep)
  810. {
  811. if (!IsActive) return;
  812. ForgetKnownVehicleProperties();
  813. MoveLinear(pTimestep);
  814. MoveAngular(pTimestep);
  815. LimitRotation(pTimestep);
  816. // remember the position so next step we can limit absolute movement effects
  817. m_lastPositionVector = VehiclePosition;
  818. // If we forced the changing of some vehicle parameters, update the values and
  819. // for the physics engine to note the changes so an UpdateProperties event will happen.
  820. PushKnownChanged();
  821. if (m_physicsScene.VehiclePhysicalLoggingEnabled)
  822. m_physicsScene.PE.DumpRigidBody(m_physicsScene.World, ControllingPrim.PhysBody);
  823. VDetailLog("{0},BSDynamics.Step,done,pos={1}, force={2},velocity={3},angvel={4}",
  824. ControllingPrim.LocalID, VehiclePosition, m_knownForce, VehicleVelocity, VehicleRotationalVelocity);
  825. }
  826. // Called after the simulation step
  827. internal void PostStep(float pTimestep)
  828. {
  829. if (!IsActive) return;
  830. if (m_physicsScene.VehiclePhysicalLoggingEnabled)
  831. m_physicsScene.PE.DumpRigidBody(m_physicsScene.World, ControllingPrim.PhysBody);
  832. }
  833. // Apply the effect of the linear motor and other linear motions (like hover and float).
  834. private void MoveLinear(float pTimestep)
  835. {
  836. ComputeLinearVelocity(pTimestep);
  837. ComputeLinearDeflection(pTimestep);
  838. ComputeLinearTerrainHeightCorrection(pTimestep);
  839. ComputeLinearHover(pTimestep);
  840. ComputeLinearBlockingEndPoint(pTimestep);
  841. ComputeLinearMotorUp(pTimestep);
  842. ApplyGravity(pTimestep);
  843. // If not changing some axis, reduce out velocity
  844. if ((m_flags & (VehicleFlag.NO_X | VehicleFlag.NO_Y | VehicleFlag.NO_Z)) != 0)
  845. {
  846. Vector3 vel = VehicleVelocity;
  847. if ((m_flags & (VehicleFlag.NO_X)) != 0)
  848. {
  849. vel.X = 0;
  850. }
  851. if ((m_flags & (VehicleFlag.NO_Y)) != 0)
  852. {
  853. vel.Y = 0;
  854. }
  855. if ((m_flags & (VehicleFlag.NO_Z)) != 0)
  856. {
  857. vel.Z = 0;
  858. }
  859. VehicleVelocity = vel;
  860. }
  861. // ==================================================================
  862. // Clamp high or low velocities
  863. float newVelocityLengthSq = VehicleVelocity.LengthSquared();
  864. if (newVelocityLengthSq > BSParam.VehicleMaxLinearVelocitySquared)
  865. {
  866. Vector3 origVelW = VehicleVelocity; // DEBUG DEBUG
  867. VehicleVelocity /= VehicleVelocity.Length();
  868. VehicleVelocity *= BSParam.VehicleMaxLinearVelocity;
  869. VDetailLog("{0}, MoveLinear,clampMax,origVelW={1},lenSq={2},maxVelSq={3},,newVelW={4}",
  870. ControllingPrim.LocalID, origVelW, newVelocityLengthSq, BSParam.VehicleMaxLinearVelocitySquared, VehicleVelocity);
  871. }
  872. else if (newVelocityLengthSq < 0.001f)
  873. VehicleVelocity = Vector3.Zero;
  874. VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.IsColliding, VehicleVelocity );
  875. } // end MoveLinear()
  876. public void ComputeLinearVelocity(float pTimestep)
  877. {
  878. // Step the motor from the current value. Get the correction needed this step.
  879. Vector3 origVelW = VehicleVelocity; // DEBUG
  880. Vector3 currentVelV = VehicleForwardVelocity;
  881. Vector3 linearMotorCorrectionV = m_linearMotor.Step(pTimestep, currentVelV);
  882. // Friction reduces vehicle motion based on absolute speed. Slow vehicle down by friction.
  883. Vector3 frictionFactorV = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep);
  884. linearMotorCorrectionV -= (currentVelV * frictionFactorV);
  885. // Motor is vehicle coordinates. Rotate it to world coordinates
  886. Vector3 linearMotorVelocityW = linearMotorCorrectionV * VehicleOrientation;
  887. // If we're a ground vehicle, don't add any upward Z movement
  888. if ((m_flags & VehicleFlag.LIMIT_MOTOR_UP) != 0)
  889. {
  890. if (linearMotorVelocityW.Z > 0f)
  891. linearMotorVelocityW.Z = 0f;
  892. }
  893. // Add this correction to the velocity to make it faster/slower.
  894. VehicleVelocity += linearMotorVelocityW;
  895. VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}",
  896. ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV,
  897. linearMotorVelocityW, VehicleVelocity, frictionFactorV);
  898. }
  899. //Given a Deflection Effiency and a Velocity, Returns a Velocity that is Partially Deflected onto the X Axis
  900. //Clamped so that a DeflectionTimescale of less then 1 does not increase force over original velocity
  901. private void ComputeLinearDeflection(float pTimestep)
  902. {
  903. Vector3 linearDeflectionV = Vector3.Zero;
  904. Vector3 velocityV = VehicleForwardVelocity;
  905. if (BSParam.VehicleEnableLinearDeflection)
  906. {
  907. // Velocity in Y and Z dimensions is movement to the side or turning.
  908. // Compute deflection factor from the to the side and rotational velocity
  909. linearDeflectionV.Y = SortedClampInRange(0, (velocityV.Y * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Y);
  910. linearDeflectionV.Z = SortedClampInRange(0, (velocityV.Z * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Z);
  911. // Velocity to the side and around is corrected and moved into the forward direction
  912. linearDeflectionV.X += Math.Abs(linearDeflectionV.Y);
  913. linearDeflectionV.X += Math.Abs(linearDeflectionV.Z);
  914. // Scale the deflection to the fractional simulation time
  915. linearDeflectionV *= pTimestep;
  916. // Subtract the sideways and rotational velocity deflection factors while adding the correction forward
  917. linearDeflectionV *= new Vector3(1, -1, -1);
  918. // Correction is vehicle relative. Convert to world coordinates.
  919. Vector3 linearDeflectionW = linearDeflectionV * VehicleOrientation;
  920. // Optionally, if not colliding, don't effect world downward velocity. Let falling things fall.
  921. if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.IsColliding)
  922. {
  923. linearDeflectionW.Z = 0f;
  924. }
  925. VehicleVelocity += linearDeflectionW;
  926. VDetailLog("{0}, MoveLinear,LinearDeflection,linDefEff={1},linDefTS={2},linDeflectionV={3}",
  927. ControllingPrim.LocalID, m_linearDeflectionEfficiency, m_linearDeflectionTimescale, linearDeflectionV);
  928. }
  929. }
  930. public void ComputeLinearTerrainHeightCorrection(float pTimestep)
  931. {
  932. // If below the terrain, move us above the ground a little.
  933. // TODO: Consider taking the rotated size of the object or possibly casting a ray.
  934. if (VehiclePosition.Z < GetTerrainHeight(VehiclePosition))
  935. {
  936. // Force position because applying force won't get the vehicle through the terrain
  937. Vector3 newPosition = VehiclePosition;
  938. newPosition.Z = GetTerrainHeight(VehiclePosition) + 1f;
  939. VehiclePosition = newPosition;
  940. VDetailLog("{0}, MoveLinear,terrainHeight,terrainHeight={1},pos={2}",
  941. ControllingPrim.LocalID, GetTerrainHeight(VehiclePosition), VehiclePosition);
  942. }
  943. }
  944. public void ComputeLinearHover(float pTimestep)
  945. {
  946. // m_VhoverEfficiency: 0=bouncy, 1=totally damped
  947. // m_VhoverTimescale: time to achieve height
  948. if ((m_flags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0)
  949. {
  950. // We should hover, get the target height
  951. if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0)
  952. {
  953. m_VhoverTargetHeight = GetWaterLevel(VehiclePosition) + m_VhoverHeight;
  954. }
  955. if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0)
  956. {
  957. m_VhoverTargetHeight = GetTerrainHeight(VehiclePosition) + m_VhoverHeight;
  958. }
  959. if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0)
  960. {
  961. m_VhoverTargetHeight = m_VhoverHeight;
  962. }
  963. if ((m_flags & VehicleFlag.HOVER_UP_ONLY) != 0)
  964. {
  965. // If body is already heigher, use its height as target height
  966. if (VehiclePosition.Z > m_VhoverTargetHeight)
  967. m_VhoverTargetHeight = VehiclePosition.Z;
  968. }
  969. if ((m_flags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0)
  970. {
  971. if (Math.Abs(VehiclePosition.Z - m_VhoverTargetHeight) > 0.2f)
  972. {
  973. Vector3 pos = VehiclePosition;
  974. pos.Z = m_VhoverTargetHeight;
  975. VehiclePosition = pos;
  976. VDetailLog("{0}, MoveLinear,hover,pos={1},lockHoverHeight", ControllingPrim.LocalID, pos);
  977. }
  978. }
  979. else
  980. {
  981. // Error is positive if below the target and negative if above.
  982. Vector3 hpos = VehiclePosition;
  983. float verticalError = m_VhoverTargetHeight - hpos.Z;
  984. float verticalCorrection = verticalError / m_VhoverTimescale;
  985. verticalCorrection *= m_VhoverEfficiency;
  986. hpos.Z += verticalCorrection;
  987. VehiclePosition = hpos;
  988. // Since we are hovering, we need to do the opposite of falling -- get rid of world Z
  989. Vector3 vel = VehicleVelocity;
  990. vel.Z = 0f;
  991. VehicleVelocity = vel;
  992. /*
  993. float verticalCorrectionVelocity = verticalError / m_VhoverTimescale;
  994. Vector3 verticalCorrection = new Vector3(0f, 0f, verticalCorrectionVelocity);
  995. verticalCorrection *= m_vehicleMass;
  996. // TODO: implement m_VhoverEfficiency correctly
  997. VehicleAddForceImpulse(verticalCorrection);
  998. */
  999. VDetailLog("{0}, MoveLinear,hover,pos={1},eff={2},hoverTS={3},height={4},target={5},err={6},corr={7}",
  1000. ControllingPrim.LocalID, VehiclePosition, m_VhoverEfficiency,
  1001. m_VhoverTimescale, m_VhoverHeight, m_VhoverTargetHeight,
  1002. verticalError, verticalCorrection);
  1003. }
  1004. }
  1005. }
  1006. public bool ComputeLinearBlockingEndPoint(float pTimestep)
  1007. {
  1008. bool changed = false;
  1009. Vector3 pos = VehiclePosition;
  1010. Vector3 posChange = pos - m_lastPositionVector;
  1011. if (m_BlockingEndPoint != Vector3.Zero)
  1012. {
  1013. if (pos.X >= (m_BlockingEndPoint.X - (float)1))
  1014. {
  1015. pos.X -= posChange.X + 1;
  1016. changed = true;
  1017. }
  1018. if (pos.Y >= (m_BlockingEndPoint.Y - (float)1))
  1019. {
  1020. pos.Y -= posChange.Y + 1;
  1021. changed = true;
  1022. }
  1023. if (pos.Z >= (m_BlockingEndPoint.Z - (float)1))
  1024. {
  1025. pos.Z -= posChange.Z + 1;
  1026. changed = true;
  1027. }
  1028. if (pos.X <= 0)
  1029. {
  1030. pos.X += posChange.X + 1;
  1031. changed = true;
  1032. }
  1033. if (pos.Y <= 0)
  1034. {
  1035. pos.Y += posChange.Y + 1;
  1036. changed = true;
  1037. }
  1038. if (changed)
  1039. {
  1040. VehiclePosition = pos;
  1041. VDetailLog("{0}, MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}",
  1042. ControllingPrim.LocalID, m_BlockingEndPoint, posChange, pos);
  1043. }
  1044. }
  1045. return changed;
  1046. }
  1047. // From http://wiki.secondlife.com/wiki/LlSetVehicleFlags :
  1048. // Prevent ground vehicles from motoring into the sky. This flag has a subtle effect when
  1049. // used with conjunction with banking: the strength of the banking will decay when the
  1050. // vehicle no longer experiences collisions. The decay timescale is the same as
  1051. // VEHICLE_BANKING_TIMESCALE. This is to help prevent ground vehicles from steering
  1052. // when they are in mid jump.
  1053. // TODO: this code is wrong. Also, what should it do for boats (height from water)?
  1054. // This is just using the ground and a general collision check. Should really be using
  1055. // a downward raycast to find what is below.
  1056. public void ComputeLinearMotorUp(float pTimestep)
  1057. {
  1058. if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0)
  1059. {
  1060. // This code tries to decide if the object is not on the ground and then pushing down
  1061. /*
  1062. float targetHeight = Type == Vehicle.TYPE_BOAT ? GetWaterLevel(VehiclePosition) : GetTerrainHeight(VehiclePosition);
  1063. distanceAboveGround = VehiclePosition.Z - targetHeight;
  1064. // Not colliding if the vehicle is off the ground
  1065. if (!Prim.IsColliding)
  1066. {
  1067. // downForce = new Vector3(0, 0, -distanceAboveGround / m_bankingTimescale);
  1068. VehicleVelocity += new Vector3(0, 0, -distanceAboveGround);
  1069. }
  1070. // TODO: this calculation is wrong. From the description at
  1071. // (http://wiki.secondlife.com/wiki/Category:LSL_Vehicle), the downForce
  1072. // has a decay factor. This says this force should
  1073. // be computed with a motor.
  1074. // TODO: add interaction with banking.
  1075. VDetailLog("{0}, MoveLinear,limitMotorUp,distAbove={1},colliding={2},ret={3}",
  1076. Prim.LocalID, distanceAboveGround, Prim.IsColliding, ret);
  1077. */
  1078. // Another approach is to measure if we're going up. If going up and not colliding,
  1079. // the vehicle is in the air. Fix that by pushing down.
  1080. if (!ControllingPrim.IsColliding && VehicleVelocity.Z > 0.1)
  1081. {
  1082. // Get rid of any of the velocity vector that is pushing us up.
  1083. float upVelocity = VehicleVelocity.Z;
  1084. VehicleVelocity += new Vector3(0, 0, -upVelocity);
  1085. /*
  1086. // If we're pointed up into the air, we should nose down
  1087. Vector3 pointingDirection = Vector3.UnitX * VehicleOrientation;
  1088. // The rotation around the Y axis is pitch up or down
  1089. if (pointingDirection.Y > 0.01f)
  1090. {
  1091. float angularCorrectionForce = -(float)Math.Asin(pointingDirection.Y);
  1092. Vector3 angularCorrectionVector = new Vector3(0f, angularCorrectionForce, 0f);
  1093. // Rotate into world coordinates and apply to vehicle
  1094. angularCorrectionVector *= VehicleOrientation;
  1095. VehicleAddAngularForce(angularCorrectionVector);
  1096. VDetailLog("{0}, MoveLinear,limitMotorUp,newVel={1},pntDir={2},corrFrc={3},aCorr={4}",
  1097. Prim.LocalID, VehicleVelocity, pointingDirection, angularCorrectionForce, angularCorrectionVector);
  1098. }
  1099. */
  1100. VDetailLog("{0}, MoveLinear,limitMotorUp,collide={1},upVel={2},newVel={3}",
  1101. ControllingPrim.LocalID, ControllingPrim.IsColliding, upVelocity, VehicleVelocity);
  1102. }
  1103. }
  1104. }
  1105. private void ApplyGravity(float pTimeStep)
  1106. {
  1107. Vector3 appliedGravity = m_VehicleGravity * m_vehicleMass;
  1108. // Hack to reduce downward force if the vehicle is probably sitting on the ground
  1109. if (ControllingPrim.IsColliding && IsGroundVehicle)
  1110. appliedGravity *= BSParam.VehicleGroundGravityFudge;
  1111. VehicleAddForce(appliedGravity);
  1112. VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={5}",
  1113. ControllingPrim.LocalID, m_VehicleGravity,
  1114. ControllingPrim.IsColliding, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity);
  1115. }
  1116. // =======================================================================
  1117. // =======================================================================
  1118. // Apply the effect of the angular motor.
  1119. // The 'contribution' is how much angular correction velocity each function wants.
  1120. // All the contributions are added together and the resulting velocity is
  1121. // set directly on the vehicle.
  1122. private void MoveAngular(float pTimestep)
  1123. {
  1124. ComputeAngularTurning(pTimestep);
  1125. ComputeAngularVerticalAttraction();
  1126. ComputeAngularDeflection();
  1127. ComputeAngularBanking();
  1128. // ==================================================================
  1129. if (VehicleRotationalVelocity.ApproxEquals(Vector3.Zero, 0.0001f))
  1130. {
  1131. // The vehicle is not adding anything angular wise.
  1132. VehicleRotationalVelocity = Vector3.Zero;
  1133. VDetailLog("{0}, MoveAngular,done,zero", ControllingPrim.LocalID);
  1134. }
  1135. else
  1136. {
  1137. VDetailLog("{0}, MoveAngular,done,nonZero,angVel={1}", ControllingPrim.LocalID, VehicleRotationalVelocity);
  1138. }
  1139. // ==================================================================
  1140. //Offset section
  1141. if (m_linearMotorOffset != Vector3.Zero)
  1142. {
  1143. //Offset of linear velocity doesn't change the linear velocity,
  1144. // but causes a torque to be applied, for example...
  1145. //
  1146. // IIIII >>> IIIII
  1147. // IIIII >>> IIIII
  1148. // IIIII >>> IIIII
  1149. // ^
  1150. // | Applying a force at the arrow will cause the object to move forward, but also rotate
  1151. //
  1152. //
  1153. // The torque created is the linear velocity crossed with the offset
  1154. // TODO: this computation should be in the linear section
  1155. // because that is where we know the impulse being applied.
  1156. Vector3 torqueFromOffset = Vector3.Zero;
  1157. // torqueFromOffset = Vector3.Cross(m_linearMotorOffset, appliedImpulse);
  1158. if (float.IsNaN(torqueFromOffset.X))
  1159. torqueFromOffset.X = 0;
  1160. if (float.IsNaN(torqueFromOffset.Y))
  1161. torqueFromOffset.Y = 0;
  1162. if (float.IsNaN(torqueFromOffset.Z))
  1163. torqueFromOffset.Z = 0;
  1164. VehicleAddAngularForce(torqueFromOffset * m_vehicleMass);
  1165. VDetailLog("{0}, BSDynamic.MoveAngular,motorOffset,applyTorqueImpulse={1}", ControllingPrim.LocalID, torqueFromOffset);
  1166. }
  1167. }
  1168. private void ComputeAngularTurning(float pTimestep)
  1169. {
  1170. // The user wants this many radians per second angular change?
  1171. Vector3 currentAngularV = VehicleRotationalVelocity * Quaternion.Inverse(VehicleOrientation);
  1172. Vector3 angularMotorContributionV = m_angularMotor.Step(pTimestep, currentAngularV);
  1173. // ==================================================================
  1174. // From http://wiki.secondlife.com/wiki/LlSetVehicleFlags :
  1175. // This flag prevents linear deflection parallel to world z-axis. This is useful
  1176. // for preventing ground vehicles with large linear deflection, like bumper cars,
  1177. // from climbing their linear deflection into the sky.
  1178. // That is, NO_DEFLECTION_UP says angular motion should not add any pitch or roll movement
  1179. // TODO: This is here because this is where ODE put it but documentation says it
  1180. // is a linear effect. Where should this check go?
  1181. //if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0)
  1182. // {
  1183. // angularMotorContributionV.X = 0f;
  1184. // angularMotorContributionV.Y = 0f;
  1185. // }
  1186. // Reduce any velocity by friction.
  1187. Vector3 frictionFactorW = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep);
  1188. angularMotorContributionV -= (currentAngularV * frictionFactorW);
  1189. VehicleRotationalVelocity += angularMotorContributionV * VehicleOrientation;
  1190. VDetailLog("{0}, MoveAngular,angularTurning,angContribV={1}", ControllingPrim.LocalID, angularMotorContributionV);
  1191. }
  1192. // From http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial:
  1193. // Some vehicles, like boats, should always keep their up-side up. This can be done by
  1194. // enabling the "vertical attractor" behavior that springs the vehicle's local z-axis to
  1195. // the world z-axis (a.k.a. "up"). To take advantage of this feature you would set the
  1196. // VEHICLE_VERTICAL_ATTRACTION_TIMESCALE to control the period of the spring frequency,
  1197. // and then set the VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY to control the damping. An
  1198. // efficiency of 0.0 will cause the spring to wobble around its equilibrium, while an
  1199. // efficiency of 1.0 will cause the spring to reach its equilibrium with exponential decay.
  1200. public void ComputeAngularVerticalAttraction()
  1201. {
  1202. // If vertical attaction timescale is reasonable
  1203. if (BSParam.VehicleEnableAngularVerticalAttraction && m_verticalAttractionTimescale < m_verticalAttractionCutoff)
  1204. {
  1205. Vector3 vehicleUpAxis = Vector3.UnitZ * VehicleOrientation;
  1206. switch (BSParam.VehicleAngularVerticalAttractionAlgorithm)
  1207. {
  1208. case 0:
  1209. {
  1210. //Another formula to try got from :
  1211. //http://answers.unity3d.com/questions/10425/how-to-stabilize-angular-motion-alignment-of-hover.html
  1212. // Flipping what was originally a timescale into a speed variable and then multiplying it by 2
  1213. // since only computing half the distance between the angles.
  1214. float VerticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f;
  1215. // Make a prediction of where the up axis will be when this is applied rather then where it is now as
  1216. // this makes for a smoother adjustment and less fighting between the various forces.
  1217. Vector3 predictedUp = vehicleUpAxis * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f);
  1218. // This is only half the distance to the target so it will take 2 seconds to complete the turn.
  1219. Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ);
  1220. // Scale vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared
  1221. Vector3 vertContributionV = torqueVector * VerticalAttractionSpeed * VerticalAttractionSpeed;
  1222. VehicleRotationalVelocity += vertContributionV;
  1223. VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},PredictedUp={2},torqueVector={3},contrib={4}",
  1224. ControllingPrim.LocalID,
  1225. vehicleUpAxis,
  1226. predictedUp,
  1227. torqueVector,
  1228. vertContributionV);
  1229. break;
  1230. }
  1231. case 1:
  1232. {
  1233. // Possible solution derived from a discussion at:
  1234. // http://stackoverflow.com/questions/14939657/computing-vector-from-quaternion-works-computing-quaternion-from-vector-does-no
  1235. // Create a rotation that is only the vehicle's rotation around Z
  1236. Vector3 currentEuler = Vector3.Zero;
  1237. VehicleOrientation.GetEulerAngles(out currentEuler.X, out currentEuler.Y, out currentEuler.Z);
  1238. Quaternion justZOrientation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, currentEuler.Z);
  1239. // Create the axis that is perpendicular to the up vector and the rotated up vector.
  1240. Vector3 differenceAxis = Vector3.Cross(Vector3.UnitZ * justZOrientation, Vector3.UnitZ * VehicleOrientation);
  1241. // Compute the angle between those to vectors.
  1242. double differenceAngle = Math.Acos((double)Vector3.Dot(Vector3.UnitZ, Vector3.Normalize(Vector3.UnitZ * VehicleOrientation)));
  1243. // 'differenceAngle' is the angle to rotate and 'differenceAxis' is the plane to rotate in to get the vehicle vertical
  1244. // Reduce the change by the time period it is to change in. Timestep is handled when velocity is applied.
  1245. // TODO: add 'efficiency'.
  1246. differenceAngle /= m_verticalAttractionTimescale;
  1247. // Create the quaterian representing the correction angle
  1248. Quaternion correctionRotation = Quaternion.CreateFromAxisAngle(differenceAxis, (float)differenceAngle);
  1249. // Turn that quaternion into Euler values to make it into velocities to apply.
  1250. Vector3 vertContributionV = Vector3.Zero;
  1251. correctionRotation.GetEulerAngles(out vertContributionV.X, out vertContributionV.Y, out vertContributionV.Z);
  1252. vertContributionV *= -1f;
  1253. VehicleRotationalVelocity += vertContributionV;
  1254. VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},diffAxis={2},diffAng={3},corrRot={4},contrib={5}",
  1255. ControllingPrim.LocalID,
  1256. vehicleUpAxis,
  1257. differenceAxis,
  1258. differenceAngle,
  1259. correctionRotation,
  1260. vertContributionV);
  1261. break;
  1262. }
  1263. case 2:
  1264. {
  1265. Vector3 vertContributionV = Vector3.Zero;
  1266. Vector3 origRotVelW = VehicleRotationalVelocity; // DEBUG DEBUG
  1267. // Take a vector pointing up and convert it from world to vehicle relative coords.
  1268. Vector3 verticalError = Vector3.Normalize(Vector3.UnitZ * VehicleOrientation);
  1269. // If vertical attraction correction is needed, the vector that was pointing up (UnitZ)
  1270. // is now:
  1271. // leaning to one side: rotated around the X axis with the Y value going
  1272. // from zero (nearly straight up) to one (completely to the side)) or
  1273. // leaning front-to-back: rotated around the Y axis with the value of X being between
  1274. // zero and one.
  1275. // The value of Z is how far the rotation is off with 1 meaning none and 0 being 90 degrees.
  1276. // Y error means needed rotation around X axis and visa versa.
  1277. // Since the error goes from zero to one, the asin is the corresponding angle.
  1278. vertContributionV.X = (float)Math.Asin(verticalError.Y);
  1279. // (Tilt forward (positive X) needs to tilt back (rotate negative) around Y axis.)
  1280. vertContributionV.Y = -(float)Math.Asin(verticalError.X);
  1281. // If verticalError.Z is negative, the vehicle is upside down. Add additional push.
  1282. if (verticalError.Z < 0f)
  1283. {
  1284. vertContributionV.X += Math.Sign(vertContributionV.X) * PIOverFour;
  1285. // vertContribution.Y -= PIOverFour;
  1286. }
  1287. // 'vertContrbution' is now the necessary angular correction to correct tilt in one second.
  1288. // Correction happens over a number of seconds.
  1289. Vector3 unscaledContribVerticalErrorV = vertContributionV; // DEBUG DEBUG
  1290. // The correction happens over the user's time period
  1291. vertContributionV /= m_verticalAttractionTimescale;
  1292. // Rotate the vehicle rotation to the world coordinates.
  1293. VehicleRotationalVelocity += (vertContributionV * VehicleOrientation);
  1294. VDetailLog("{0}, MoveAngular,verticalAttraction,,upAxis={1},origRotVW={2},vertError={3},unscaledV={4},eff={5},ts={6},vertContribV={7}",
  1295. ControllingPrim.LocalID,
  1296. vehicleUpAxis,
  1297. origRotVelW,
  1298. verticalError,
  1299. unscaledContribVerticalErrorV,
  1300. m_verticalAttractionEfficiency,
  1301. m_verticalAttractionTimescale,
  1302. vertContributionV);
  1303. break;
  1304. }
  1305. default:
  1306. {
  1307. break;
  1308. }
  1309. }
  1310. }
  1311. }
  1312. // Angular correction to correct the direction the vehicle is pointing to be
  1313. // the direction is should want to be pointing.
  1314. // The vehicle is moving in some direction and correct its orientation to it is pointing
  1315. // in that direction.
  1316. // TODO: implement reference frame.
  1317. public void ComputeAngularDeflection()
  1318. {
  1319. if (BSParam.VehicleEnableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2)
  1320. {
  1321. Vector3 deflectContributionV = Vector3.Zero;
  1322. // The direction the vehicle is moving
  1323. Vector3 movingDirection = VehicleVelocity;
  1324. movingDirection.Normalize();
  1325. // If the vehicle is going backward, it is still pointing forward
  1326. movingDirection *= Math.Sign(VehicleForwardSpeed);
  1327. // The direction the vehicle is pointing
  1328. Vector3 pointingDirection = Vector3.UnitX * VehicleOrientation;
  1329. //Predict where the Vehicle will be pointing after AngularVelocity change is applied. This will keep
  1330. // from overshooting and allow this correction to merge with the Vertical Attraction peacefully.
  1331. Vector3 predictedPointingDirection = pointingDirection * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f);
  1332. predictedPointingDirection.Normalize();
  1333. // The difference between what is and what should be.
  1334. // Vector3 deflectionError = movingDirection - predictedPointingDirection;
  1335. Vector3 deflectionError = Vector3.Cross(movingDirection, predictedPointingDirection);
  1336. // Don't try to correct very large errors (not our job)
  1337. // if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = PIOverTwo * Math.Sign(deflectionError.X);
  1338. // if (Math.Abs(deflectionError.Y) > PIOverFour) deflectionError.Y = PIOverTwo * Math.Sign(deflectionError.Y);
  1339. // if (Math.Abs(deflectionError.Z) > PIOverFour) deflectionError.Z = PIOverTwo * Math.Sign(deflectionError.Z);
  1340. if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = 0f;
  1341. if (Math.Abs(deflectionError.Y) > PIOverFour) deflectionError.Y = 0f;
  1342. if (Math.Abs(deflectionError.Z) > PIOverFour) deflectionError.Z = 0f;
  1343. // ret = m_angularDeflectionCorrectionMotor(1f, deflectionError);
  1344. // Scale the correction by recovery timescale and efficiency
  1345. // Not modeling a spring so clamp the scale to no more then the arc
  1346. deflectContributionV = (-deflectionError) * ClampInRange(0, m_angularDeflectionEfficiency/m_angularDeflectionTimescale,1f);
  1347. //deflectContributionV /= m_angularDeflectionTimescale;
  1348. // VehicleRotationalVelocity += deflectContributionV * VehicleOrientation;
  1349. VehicleRotationalVelocity += deflectContributionV;
  1350. VDetailLog("{0}, MoveAngular,Deflection,movingDir={1},pointingDir={2},deflectError={3},ret={4}",
  1351. ControllingPrim.LocalID, movingDirection, pointingDirection, deflectionError, deflectContributionV);
  1352. VDetailLog("{0}, MoveAngular,Deflection,fwdSpd={1},defEff={2},defTS={3},PredictedPointingDir={4}",
  1353. ControllingPrim.LocalID, VehicleForwardSpeed, m_angularDeflectionEfficiency, m_angularDeflectionTimescale, predictedPointingDirection);
  1354. }
  1355. }
  1356. // Angular change to rotate the vehicle around the Z axis when the vehicle
  1357. // is tipped around the X axis.
  1358. // From http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial:
  1359. // The vertical attractor feature must be enabled in order for the banking behavior to
  1360. // function. The way banking works is this: a rotation around the vehicle's roll-axis will
  1361. // produce a angular velocity around the yaw-axis, causing the vehicle to turn. The magnitude
  1362. // of the yaw effect will be proportional to the
  1363. // VEHICLE_BANKING_EFFICIENCY, the angle of the roll rotation, and sometimes the vehicle's
  1364. // velocity along its preferred axis of motion.
  1365. // The VEHICLE_BANKING_EFFICIENCY can vary between -1 and +1. When it is positive then any
  1366. // positive rotation (by the right-hand rule) about the roll-axis will effect a
  1367. // (negative) torque around the yaw-axis, making it turn to the right--that is the
  1368. // vehicle will lean into the turn, which is how real airplanes and motorcycle's work.
  1369. // Negating the banking coefficient will make it so that the vehicle leans to the
  1370. // outside of the turn (not very "physical" but might allow interesting vehicles so why not?).
  1371. // The VEHICLE_BANKING_MIX is a fake (i.e. non-physical) parameter that is useful for making
  1372. // banking vehicles do what you want rather than what the laws of physics allow.
  1373. // For example, consider a real motorcycle...it must be moving forward in order for
  1374. // it to turn while banking, however video-game motorcycles are often configured
  1375. // to turn in place when at a dead stop--because they are often easier to control
  1376. // that way using the limited interface of the keyboard or game controller. The
  1377. // VEHICLE_BANKING_MIX enables combinations of both realistic and non-realistic
  1378. // banking by functioning as a slider between a banking that is correspondingly
  1379. // totally static (0.0) and totally dynamic (1.0). By "static" we mean that the
  1380. // banking effect depends only on the vehicle's rotation about its roll-axis compared
  1381. // to "dynamic" where the banking is also proportional to its velocity along its
  1382. // roll-axis. Finding the best value of the "mixture" will probably require trial and error.
  1383. // The time it takes for the banking behavior to defeat a preexisting angular velocity about the
  1384. // world z-axis is determined by the VEHICLE_BANKING_TIMESCALE. So if you want the vehicle to
  1385. // bank quickly then give it a banking timescale of about a second or less, otherwise you can
  1386. // make a sluggish vehicle by giving it a timescale of several seconds.
  1387. public void ComputeAngularBanking()
  1388. {
  1389. if (BSParam.VehicleEnableAngularBanking && m_bankingEfficiency != 0 && m_verticalAttractionTimescale < m_verticalAttractionCutoff)
  1390. {
  1391. Vector3 bankingContributionV = Vector3.Zero;
  1392. // Rotate a UnitZ vector (pointing up) to how the vehicle is oriented.
  1393. // As the vehicle rolls to the right or left, the Y value will increase from
  1394. // zero (straight up) to 1 or -1 (full tilt right or left)
  1395. Vector3 rollComponents = Vector3.UnitZ * VehicleOrientation;
  1396. // Figure out the yaw value for this much roll.
  1397. float yawAngle = m_angularMotorDirection.X * m_bankingEfficiency;
  1398. // actual error = static turn error + dynamic turn error
  1399. float mixedYawAngle =(yawAngle * (1f - m_bankingMix)) + ((yawAngle * m_bankingMix) * VehicleForwardSpeed);
  1400. // TODO: the banking effect should not go to infinity but what to limit it to?
  1401. // And what should happen when this is being added to a user defined yaw that is already PI*4?
  1402. mixedYawAngle = ClampInRange(-12, mixedYawAngle, 12);
  1403. // Build the force vector to change rotation from what it is to what it should be
  1404. bankingContributionV.Z = -mixedYawAngle;
  1405. // Don't do it all at once. Fudge because 1 second is too fast with most user defined roll as PI*4.
  1406. bankingContributionV /= m_bankingTimescale * BSParam.VehicleAngularBankingTimescaleFudge;
  1407. //VehicleRotationalVelocity += bankingContributionV * VehicleOrientation;
  1408. VehicleRotationalVelocity += bankingContributionV;
  1409. VDetailLog("{0}, MoveAngular,Banking,rollComp={1},speed={2},rollComp={3},yAng={4},mYAng={5},ret={6}",
  1410. ControllingPrim.LocalID, rollComponents, VehicleForwardSpeed, rollComponents, yawAngle, mixedYawAngle, bankingContributionV);
  1411. }
  1412. }
  1413. // This is from previous instantiations of XXXDynamics.cs.
  1414. // Applies roll reference frame.
  1415. // TODO: is this the right way to separate the code to do this operation?
  1416. // Should this be in MoveAngular()?
  1417. internal void LimitRotation(float timestep)
  1418. {
  1419. Quaternion rotq = VehicleOrientation;
  1420. Quaternion m_rot = rotq;
  1421. if (m_RollreferenceFrame != Quaternion.Identity)
  1422. {
  1423. if (rotq.X >= m_RollreferenceFrame.X)
  1424. {
  1425. m_rot.X = rotq.X - (m_RollreferenceFrame.X / 2);
  1426. }
  1427. if (rotq.Y >= m_RollreferenceFrame.Y)
  1428. {
  1429. m_rot.Y = rotq.Y - (m_RollreferenceFrame.Y / 2);
  1430. }
  1431. if (rotq.X <= -m_RollreferenceFrame.X)
  1432. {
  1433. m_rot.X = rotq.X + (m_RollreferenceFrame.X / 2);
  1434. }
  1435. if (rotq.Y <= -m_RollreferenceFrame.Y)
  1436. {
  1437. m_rot.Y = rotq.Y + (m_RollreferenceFrame.Y / 2);
  1438. }
  1439. }
  1440. if ((m_flags & VehicleFlag.LOCK_ROTATION) != 0)
  1441. {
  1442. m_rot.X = 0;
  1443. m_rot.Y = 0;
  1444. }
  1445. if (rotq != m_rot)
  1446. {
  1447. VehicleOrientation = m_rot;
  1448. VDetailLog("{0}, LimitRotation,done,orig={1},new={2}", ControllingPrim.LocalID, rotq, m_rot);
  1449. }
  1450. }
  1451. // Given a friction vector (reduction in seconds) and a timestep, return the factor to reduce
  1452. // some value by to apply this friction.
  1453. private Vector3 ComputeFrictionFactor(Vector3 friction, float pTimestep)
  1454. {
  1455. Vector3 frictionFactor = Vector3.Zero;
  1456. if (friction != BSMotor.InfiniteVector)
  1457. {
  1458. // frictionFactor = (Vector3.One / FrictionTimescale) * timeStep;
  1459. // Individual friction components can be 'infinite' so compute each separately.
  1460. frictionFactor.X = (friction.X == BSMotor.Infinite) ? 0f : (1f / friction.X);
  1461. frictionFactor.Y = (friction.Y == BSMotor.Infinite) ? 0f : (1f / friction.Y);
  1462. frictionFactor.Z = (friction.Z == BSMotor.Infinite) ? 0f : (1f / friction.Z);
  1463. frictionFactor *= pTimestep;
  1464. }
  1465. return frictionFactor;
  1466. }
  1467. private float SortedClampInRange(float clampa, float val, float clampb)
  1468. {
  1469. if (clampa > clampb)
  1470. {
  1471. float temp = clampa;
  1472. clampa = clampb;
  1473. clampb = temp;
  1474. }
  1475. return ClampInRange(clampa, val, clampb);
  1476. }
  1477. private float ClampInRange(float low, float val, float high)
  1478. {
  1479. return Math.Max(low, Math.Min(val, high));
  1480. // return Utils.Clamp(val, low, high);
  1481. }
  1482. // Invoke the detailed logger and output something if it's enabled.
  1483. private void VDetailLog(string msg, params Object[] args)
  1484. {
  1485. if (ControllingPrim.PhysScene.VehicleLoggingEnabled)
  1486. ControllingPrim.PhysScene.DetailLog(msg, args);
  1487. }
  1488. }
  1489. }