1
0

BSDynamics.cs 86 KB

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