BSDynamics.cs 80 KB

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