ODEPrim.cs 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375
  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. /*
  28. * Revised August 26 2009 by Kitto Flora. ODEDynamics.cs replaces
  29. * ODEVehicleSettings.cs. It and ODEPrim.cs are re-organised:
  30. * ODEPrim.cs contains methods dealing with Prim editing, Prim
  31. * characteristics and Kinetic motion.
  32. * ODEDynamics.cs contains methods dealing with Prim Physical motion
  33. * (dynamics) and the associated settings. Old Linear and angular
  34. * motors for dynamic motion have been replace with MoveLinear()
  35. * and MoveAngular(); 'Physical' is used only to switch ODE dynamic
  36. * simualtion on/off; VEHICAL_TYPE_NONE/VEHICAL_TYPE_<other> is to
  37. * switch between 'VEHICLE' parameter use and general dynamics
  38. * settings use.
  39. */
  40. //#define SPAM
  41. using System;
  42. using System.Collections.Generic;
  43. using System.Reflection;
  44. using System.Runtime.InteropServices;
  45. using System.Threading;
  46. using log4net;
  47. using OpenMetaverse;
  48. using Ode.NET;
  49. using OpenSim.Framework;
  50. using OpenSim.Region.Physics.Manager;
  51. namespace OpenSim.Region.Physics.OdePlugin
  52. {
  53. /// <summary>
  54. /// Various properties that ODE uses for AMotors but isn't exposed in ODE.NET so we must define them ourselves.
  55. /// </summary>
  56. public class OdePrim : PhysicsActor
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. private bool m_isphysical;
  60. public int ExpectedCollisionContacts { get { return m_expectedCollisionContacts; } }
  61. private int m_expectedCollisionContacts = 0;
  62. /// <summary>
  63. /// Gets collide bits so that we can still perform land collisions if a mesh fails to load.
  64. /// </summary>
  65. private int BadMeshAssetCollideBits
  66. {
  67. get { return m_isphysical ? (int)CollisionCategories.Land : 0; }
  68. }
  69. /// <summary>
  70. /// Is this prim subject to physics? Even if not, it's still solid for collision purposes.
  71. /// </summary>
  72. public override bool IsPhysical
  73. {
  74. get { return m_isphysical; }
  75. set
  76. {
  77. m_isphysical = value;
  78. if (!m_isphysical) // Zero the remembered last velocity
  79. m_lastVelocity = Vector3.Zero;
  80. }
  81. }
  82. private Vector3 _position;
  83. private Vector3 _velocity;
  84. private Vector3 _torque;
  85. private Vector3 m_lastVelocity;
  86. private Vector3 m_lastposition;
  87. private Quaternion m_lastorientation = new Quaternion();
  88. private Vector3 m_rotationalVelocity;
  89. private Vector3 _size;
  90. private Vector3 _acceleration;
  91. // private d.Vector3 _zeroPosition = new d.Vector3(0.0f, 0.0f, 0.0f);
  92. private Quaternion _orientation;
  93. private Vector3 m_taintposition;
  94. private Vector3 m_taintsize;
  95. private Vector3 m_taintVelocity;
  96. private Vector3 m_taintTorque;
  97. private Quaternion m_taintrot;
  98. private Vector3 m_angularlock = Vector3.One;
  99. private Vector3 m_taintAngularLock = Vector3.One;
  100. private IntPtr Amotor = IntPtr.Zero;
  101. private object m_assetsLock = new object();
  102. private bool m_assetFailed = false;
  103. private Vector3 m_PIDTarget;
  104. private float m_PIDTau;
  105. private float PID_D = 35f;
  106. private float PID_G = 25f;
  107. private bool m_usePID;
  108. // KF: These next 7 params apply to llSetHoverHeight(float height, integer water, float tau),
  109. // and are for non-VEHICLES only.
  110. private float m_PIDHoverHeight;
  111. private float m_PIDHoverTau;
  112. private bool m_useHoverPID;
  113. private PIDHoverType m_PIDHoverType = PIDHoverType.Ground;
  114. private float m_targetHoverHeight;
  115. private float m_groundHeight;
  116. private float m_waterHeight;
  117. private float m_buoyancy; //KF: m_buoyancy should be set by llSetBuoyancy() for non-vehicle.
  118. // private float m_tensor = 5f;
  119. private int body_autodisable_frames = 20;
  120. private const CollisionCategories m_default_collisionFlags = (CollisionCategories.Geom
  121. | CollisionCategories.Space
  122. | CollisionCategories.Body
  123. | CollisionCategories.Character
  124. );
  125. private bool m_taintshape;
  126. private bool m_taintPhysics;
  127. private bool m_collidesLand = true;
  128. private bool m_collidesWater;
  129. // Default we're a Geometry
  130. private CollisionCategories m_collisionCategories = (CollisionCategories.Geom);
  131. // Default, Collide with Other Geometries, spaces and Bodies
  132. private CollisionCategories m_collisionFlags = m_default_collisionFlags;
  133. public bool m_taintremove { get; private set; }
  134. public bool m_taintdisable { get; private set; }
  135. internal bool m_disabled;
  136. public bool m_taintadd { get; private set; }
  137. public bool m_taintselected { get; private set; }
  138. public bool m_taintCollidesWater { get; private set; }
  139. private bool m_taintforce = false;
  140. private bool m_taintaddangularforce = false;
  141. private Vector3 m_force;
  142. private List<Vector3> m_forcelist = new List<Vector3>();
  143. private List<Vector3> m_angularforcelist = new List<Vector3>();
  144. private PrimitiveBaseShape _pbs;
  145. private OdeScene _parent_scene;
  146. /// <summary>
  147. /// The physics space which contains prim geometries
  148. /// </summary>
  149. public IntPtr m_targetSpace = IntPtr.Zero;
  150. /// <summary>
  151. /// The prim geometry, used for collision detection.
  152. /// </summary>
  153. /// <remarks>
  154. /// This is never null except for a brief period when the geometry needs to be replaced (due to resizing or
  155. /// mesh change) or when the physical prim is being removed from the scene.
  156. /// </remarks>
  157. public IntPtr prim_geom { get; private set; }
  158. public IntPtr _triMeshData { get; private set; }
  159. private IntPtr _linkJointGroup = IntPtr.Zero;
  160. private PhysicsActor _parent;
  161. private PhysicsActor m_taintparent;
  162. private List<OdePrim> childrenPrim = new List<OdePrim>();
  163. private bool iscolliding;
  164. private bool m_isSelected;
  165. internal bool m_isVolumeDetect; // If true, this prim only detects collisions but doesn't collide actively
  166. private bool m_throttleUpdates;
  167. private int throttleCounter;
  168. public int m_interpenetrationcount { get; private set; }
  169. internal float m_collisionscore;
  170. public int m_roundsUnderMotionThreshold { get; private set; }
  171. private int m_crossingfailures;
  172. public bool outofBounds { get; private set; }
  173. private float m_density = 10.000006836f; // Aluminum g/cm3;
  174. public bool _zeroFlag { get; private set; }
  175. private bool m_lastUpdateSent;
  176. public IntPtr Body = IntPtr.Zero;
  177. private Vector3 _target_velocity;
  178. private d.Mass pMass;
  179. private int m_eventsubscription;
  180. private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
  181. /// <summary>
  182. /// Signal whether there were collisions on the previous frame, so we know if we need to send the
  183. /// empty CollisionEventsThisFrame to the prim so that it can detect the end of a collision.
  184. /// </summary>
  185. /// <remarks>
  186. /// This is probably a temporary measure, pending storing this information consistently in CollisionEventUpdate itself.
  187. /// </remarks>
  188. private bool m_collisionsOnPreviousFrame;
  189. private IntPtr m_linkJoint = IntPtr.Zero;
  190. internal volatile bool childPrim;
  191. private ODEDynamics m_vehicle;
  192. internal int m_material = (int)Material.Wood;
  193. public OdePrim(
  194. String primName, OdeScene parent_scene, Vector3 pos, Vector3 size,
  195. Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
  196. {
  197. Name = primName;
  198. m_vehicle = new ODEDynamics();
  199. //gc = GCHandle.Alloc(prim_geom, GCHandleType.Pinned);
  200. if (!pos.IsFinite())
  201. {
  202. pos = new Vector3(((float)Constants.RegionSize * 0.5f), ((float)Constants.RegionSize * 0.5f),
  203. parent_scene.GetTerrainHeightAtXY(((float)Constants.RegionSize * 0.5f), ((float)Constants.RegionSize * 0.5f)) + 0.5f);
  204. m_log.WarnFormat("[PHYSICS]: Got nonFinite Object create Position for {0}", Name);
  205. }
  206. _position = pos;
  207. m_taintposition = pos;
  208. PID_D = parent_scene.bodyPIDD;
  209. PID_G = parent_scene.bodyPIDG;
  210. m_density = parent_scene.geomDefaultDensity;
  211. // m_tensor = parent_scene.bodyMotorJointMaxforceTensor;
  212. body_autodisable_frames = parent_scene.bodyFramesAutoDisable;
  213. prim_geom = IntPtr.Zero;
  214. if (!pos.IsFinite())
  215. {
  216. size = new Vector3(0.5f, 0.5f, 0.5f);
  217. m_log.WarnFormat("[PHYSICS]: Got nonFinite Object create Size for {0}", Name);
  218. }
  219. if (size.X <= 0) size.X = 0.01f;
  220. if (size.Y <= 0) size.Y = 0.01f;
  221. if (size.Z <= 0) size.Z = 0.01f;
  222. _size = size;
  223. m_taintsize = _size;
  224. if (!QuaternionIsFinite(rotation))
  225. {
  226. rotation = Quaternion.Identity;
  227. m_log.WarnFormat("[PHYSICS]: Got nonFinite Object create Rotation for {0}", Name);
  228. }
  229. _orientation = rotation;
  230. m_taintrot = _orientation;
  231. _pbs = pbs;
  232. _parent_scene = parent_scene;
  233. m_targetSpace = (IntPtr)0;
  234. if (pos.Z < 0)
  235. {
  236. IsPhysical = false;
  237. }
  238. else
  239. {
  240. IsPhysical = pisPhysical;
  241. // If we're physical, we need to be in the master space for now.
  242. // linksets *should* be in a space together.. but are not currently
  243. if (IsPhysical)
  244. m_targetSpace = _parent_scene.space;
  245. }
  246. m_taintadd = true;
  247. m_assetFailed = false;
  248. _parent_scene.AddPhysicsActorTaint(this);
  249. }
  250. public override int PhysicsActorType
  251. {
  252. get { return (int) ActorTypes.Prim; }
  253. set { return; }
  254. }
  255. public override bool SetAlwaysRun
  256. {
  257. get { return false; }
  258. set { return; }
  259. }
  260. public override bool Grabbed
  261. {
  262. set { return; }
  263. }
  264. public override bool Selected
  265. {
  266. set
  267. {
  268. // This only makes the object not collidable if the object
  269. // is physical or the object is modified somehow *IN THE FUTURE*
  270. // without this, if an avatar selects prim, they can walk right
  271. // through it while it's selected
  272. m_collisionscore = 0;
  273. if ((IsPhysical && !_zeroFlag) || !value)
  274. {
  275. m_taintselected = value;
  276. _parent_scene.AddPhysicsActorTaint(this);
  277. }
  278. else
  279. {
  280. m_taintselected = value;
  281. m_isSelected = value;
  282. }
  283. if (m_isSelected)
  284. disableBodySoft();
  285. }
  286. }
  287. /// <summary>
  288. /// Set a new geometry for this prim.
  289. /// </summary>
  290. /// <param name="geom"></param>
  291. private void SetGeom(IntPtr geom)
  292. {
  293. prim_geom = geom;
  294. //Console.WriteLine("SetGeom to " + prim_geom + " for " + Name);
  295. if (m_assetFailed)
  296. {
  297. d.GeomSetCategoryBits(prim_geom, 0);
  298. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  299. }
  300. else
  301. {
  302. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  303. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  304. }
  305. _parent_scene.geom_name_map[prim_geom] = Name;
  306. _parent_scene.actor_name_map[prim_geom] = this;
  307. if (childPrim)
  308. {
  309. if (_parent != null && _parent is OdePrim)
  310. {
  311. OdePrim parent = (OdePrim)_parent;
  312. //Console.WriteLine("SetGeom calls ChildSetGeom");
  313. parent.ChildSetGeom(this);
  314. }
  315. }
  316. //m_log.Warn("Setting Geom to: " + prim_geom);
  317. }
  318. private void enableBodySoft()
  319. {
  320. if (!childPrim)
  321. {
  322. if (IsPhysical && Body != IntPtr.Zero)
  323. {
  324. d.BodyEnable(Body);
  325. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  326. m_vehicle.Enable(Body, _parent_scene);
  327. }
  328. m_disabled = false;
  329. }
  330. }
  331. private void disableBodySoft()
  332. {
  333. m_disabled = true;
  334. if (IsPhysical && Body != IntPtr.Zero)
  335. {
  336. d.BodyDisable(Body);
  337. }
  338. }
  339. /// <summary>
  340. /// Make a prim subject to physics.
  341. /// </summary>
  342. private void enableBody()
  343. {
  344. // Don't enable this body if we're a child prim
  345. // this should be taken care of in the parent function not here
  346. if (!childPrim)
  347. {
  348. // Sets the geom to a body
  349. Body = d.BodyCreate(_parent_scene.world);
  350. setMass();
  351. d.BodySetPosition(Body, _position.X, _position.Y, _position.Z);
  352. d.Quaternion myrot = new d.Quaternion();
  353. myrot.X = _orientation.X;
  354. myrot.Y = _orientation.Y;
  355. myrot.Z = _orientation.Z;
  356. myrot.W = _orientation.W;
  357. d.BodySetQuaternion(Body, ref myrot);
  358. d.GeomSetBody(prim_geom, Body);
  359. if (m_assetFailed)
  360. {
  361. d.GeomSetCategoryBits(prim_geom, 0);
  362. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  363. }
  364. else
  365. {
  366. m_collisionCategories |= CollisionCategories.Body;
  367. m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  368. }
  369. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  370. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  371. d.BodySetAutoDisableFlag(Body, true);
  372. d.BodySetAutoDisableSteps(Body, body_autodisable_frames);
  373. // disconnect from world gravity so we can apply buoyancy
  374. d.BodySetGravityMode (Body, false);
  375. m_interpenetrationcount = 0;
  376. m_collisionscore = 0;
  377. m_disabled = false;
  378. // The body doesn't already have a finite rotation mode set here
  379. if ((!m_angularlock.ApproxEquals(Vector3.Zero, 0.0f)) && _parent == null)
  380. {
  381. createAMotor(m_angularlock);
  382. }
  383. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  384. {
  385. m_vehicle.Enable(Body, _parent_scene);
  386. }
  387. _parent_scene.ActivatePrim(this);
  388. }
  389. }
  390. #region Mass Calculation
  391. private float CalculateMass()
  392. {
  393. float volume = _size.X * _size.Y * _size.Z; // default
  394. float tmp;
  395. float returnMass = 0;
  396. float hollowAmount = (float)_pbs.ProfileHollow * 2.0e-5f;
  397. float hollowVolume = hollowAmount * hollowAmount;
  398. switch (_pbs.ProfileShape)
  399. {
  400. case ProfileShape.Square:
  401. // default box
  402. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  403. {
  404. if (hollowAmount > 0.0)
  405. {
  406. switch (_pbs.HollowShape)
  407. {
  408. case HollowShape.Square:
  409. case HollowShape.Same:
  410. break;
  411. case HollowShape.Circle:
  412. hollowVolume *= 0.78539816339f;
  413. break;
  414. case HollowShape.Triangle:
  415. hollowVolume *= (0.5f * .5f);
  416. break;
  417. default:
  418. hollowVolume = 0;
  419. break;
  420. }
  421. volume *= (1.0f - hollowVolume);
  422. }
  423. }
  424. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  425. {
  426. //a tube
  427. volume *= 0.78539816339e-2f * (float)(200 - _pbs.PathScaleX);
  428. tmp= 1.0f -2.0e-2f * (float)(200 - _pbs.PathScaleY);
  429. volume -= volume*tmp*tmp;
  430. if (hollowAmount > 0.0)
  431. {
  432. hollowVolume *= hollowAmount;
  433. switch (_pbs.HollowShape)
  434. {
  435. case HollowShape.Square:
  436. case HollowShape.Same:
  437. break;
  438. case HollowShape.Circle:
  439. hollowVolume *= 0.78539816339f;;
  440. break;
  441. case HollowShape.Triangle:
  442. hollowVolume *= 0.5f * 0.5f;
  443. break;
  444. default:
  445. hollowVolume = 0;
  446. break;
  447. }
  448. volume *= (1.0f - hollowVolume);
  449. }
  450. }
  451. break;
  452. case ProfileShape.Circle:
  453. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  454. {
  455. volume *= 0.78539816339f; // elipse base
  456. if (hollowAmount > 0.0)
  457. {
  458. switch (_pbs.HollowShape)
  459. {
  460. case HollowShape.Same:
  461. case HollowShape.Circle:
  462. break;
  463. case HollowShape.Square:
  464. hollowVolume *= 0.5f * 2.5984480504799f;
  465. break;
  466. case HollowShape.Triangle:
  467. hollowVolume *= .5f * 1.27323954473516f;
  468. break;
  469. default:
  470. hollowVolume = 0;
  471. break;
  472. }
  473. volume *= (1.0f - hollowVolume);
  474. }
  475. }
  476. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  477. {
  478. volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - _pbs.PathScaleX);
  479. tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY);
  480. volume *= (1.0f - tmp * tmp);
  481. if (hollowAmount > 0.0)
  482. {
  483. // calculate the hollow volume by it's shape compared to the prim shape
  484. hollowVolume *= hollowAmount;
  485. switch (_pbs.HollowShape)
  486. {
  487. case HollowShape.Same:
  488. case HollowShape.Circle:
  489. break;
  490. case HollowShape.Square:
  491. hollowVolume *= 0.5f * 2.5984480504799f;
  492. break;
  493. case HollowShape.Triangle:
  494. hollowVolume *= .5f * 1.27323954473516f;
  495. break;
  496. default:
  497. hollowVolume = 0;
  498. break;
  499. }
  500. volume *= (1.0f - hollowVolume);
  501. }
  502. }
  503. break;
  504. case ProfileShape.HalfCircle:
  505. if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  506. {
  507. volume *= 0.52359877559829887307710723054658f;
  508. }
  509. break;
  510. case ProfileShape.EquilateralTriangle:
  511. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  512. {
  513. volume *= 0.32475953f;
  514. if (hollowAmount > 0.0)
  515. {
  516. // calculate the hollow volume by it's shape compared to the prim shape
  517. switch (_pbs.HollowShape)
  518. {
  519. case HollowShape.Same:
  520. case HollowShape.Triangle:
  521. hollowVolume *= .25f;
  522. break;
  523. case HollowShape.Square:
  524. hollowVolume *= 0.499849f * 3.07920140172638f;
  525. break;
  526. case HollowShape.Circle:
  527. // Hollow shape is a perfect cyllinder in respect to the cube's scale
  528. // Cyllinder hollow volume calculation
  529. hollowVolume *= 0.1963495f * 3.07920140172638f;
  530. break;
  531. default:
  532. hollowVolume = 0;
  533. break;
  534. }
  535. volume *= (1.0f - hollowVolume);
  536. }
  537. }
  538. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  539. {
  540. volume *= 0.32475953f;
  541. volume *= 0.01f * (float)(200 - _pbs.PathScaleX);
  542. tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY);
  543. volume *= (1.0f - tmp * tmp);
  544. if (hollowAmount > 0.0)
  545. {
  546. hollowVolume *= hollowAmount;
  547. switch (_pbs.HollowShape)
  548. {
  549. case HollowShape.Same:
  550. case HollowShape.Triangle:
  551. hollowVolume *= .25f;
  552. break;
  553. case HollowShape.Square:
  554. hollowVolume *= 0.499849f * 3.07920140172638f;
  555. break;
  556. case HollowShape.Circle:
  557. hollowVolume *= 0.1963495f * 3.07920140172638f;
  558. break;
  559. default:
  560. hollowVolume = 0;
  561. break;
  562. }
  563. volume *= (1.0f - hollowVolume);
  564. }
  565. }
  566. break;
  567. default:
  568. break;
  569. }
  570. float taperX1;
  571. float taperY1;
  572. float taperX;
  573. float taperY;
  574. float pathBegin;
  575. float pathEnd;
  576. float profileBegin;
  577. float profileEnd;
  578. if (_pbs.PathCurve == (byte)Extrusion.Straight || _pbs.PathCurve == (byte)Extrusion.Flexible)
  579. {
  580. taperX1 = _pbs.PathScaleX * 0.01f;
  581. if (taperX1 > 1.0f)
  582. taperX1 = 2.0f - taperX1;
  583. taperX = 1.0f - taperX1;
  584. taperY1 = _pbs.PathScaleY * 0.01f;
  585. if (taperY1 > 1.0f)
  586. taperY1 = 2.0f - taperY1;
  587. taperY = 1.0f - taperY1;
  588. }
  589. else
  590. {
  591. taperX = _pbs.PathTaperX * 0.01f;
  592. if (taperX < 0.0f)
  593. taperX = -taperX;
  594. taperX1 = 1.0f - taperX;
  595. taperY = _pbs.PathTaperY * 0.01f;
  596. if (taperY < 0.0f)
  597. taperY = -taperY;
  598. taperY1 = 1.0f - taperY;
  599. }
  600. volume *= (taperX1 * taperY1 + 0.5f * (taperX1 * taperY + taperX * taperY1) + 0.3333333333f * taperX * taperY);
  601. pathBegin = (float)_pbs.PathBegin * 2.0e-5f;
  602. pathEnd = 1.0f - (float)_pbs.PathEnd * 2.0e-5f;
  603. volume *= (pathEnd - pathBegin);
  604. // this is crude aproximation
  605. profileBegin = (float)_pbs.ProfileBegin * 2.0e-5f;
  606. profileEnd = 1.0f - (float)_pbs.ProfileEnd * 2.0e-5f;
  607. volume *= (profileEnd - profileBegin);
  608. returnMass = m_density * volume;
  609. if (returnMass <= 0)
  610. returnMass = 0.0001f;//ckrinke: Mass must be greater then zero.
  611. // else if (returnMass > _parent_scene.maximumMassObject)
  612. // returnMass = _parent_scene.maximumMassObject;
  613. // Recursively calculate mass
  614. bool HasChildPrim = false;
  615. lock (childrenPrim)
  616. {
  617. if (childrenPrim.Count > 0)
  618. {
  619. HasChildPrim = true;
  620. }
  621. }
  622. if (HasChildPrim)
  623. {
  624. OdePrim[] childPrimArr = new OdePrim[0];
  625. lock (childrenPrim)
  626. childPrimArr = childrenPrim.ToArray();
  627. for (int i = 0; i < childPrimArr.Length; i++)
  628. {
  629. if (childPrimArr[i] != null && !childPrimArr[i].m_taintremove)
  630. returnMass += childPrimArr[i].CalculateMass();
  631. // failsafe, this shouldn't happen but with OpenSim, you never know :)
  632. if (i > 256)
  633. break;
  634. }
  635. }
  636. if (returnMass > _parent_scene.maximumMassObject)
  637. returnMass = _parent_scene.maximumMassObject;
  638. return returnMass;
  639. }
  640. #endregion
  641. private void setMass()
  642. {
  643. if (Body != (IntPtr) 0)
  644. {
  645. float newmass = CalculateMass();
  646. //m_log.Info("[PHYSICS]: New Mass: " + newmass.ToString());
  647. d.MassSetBoxTotal(out pMass, newmass, _size.X, _size.Y, _size.Z);
  648. d.BodySetMass(Body, ref pMass);
  649. }
  650. }
  651. /// <summary>
  652. /// Stop a prim from being subject to physics.
  653. /// </summary>
  654. internal void disableBody()
  655. {
  656. //this kills the body so things like 'mesh' can re-create it.
  657. lock (this)
  658. {
  659. if (!childPrim)
  660. {
  661. if (Body != IntPtr.Zero)
  662. {
  663. _parent_scene.DeactivatePrim(this);
  664. m_collisionCategories &= ~CollisionCategories.Body;
  665. m_collisionFlags &= ~(CollisionCategories.Wind | CollisionCategories.Land);
  666. if (m_assetFailed)
  667. {
  668. d.GeomSetCategoryBits(prim_geom, 0);
  669. d.GeomSetCollideBits(prim_geom, 0);
  670. }
  671. else
  672. {
  673. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  674. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  675. }
  676. d.BodyDestroy(Body);
  677. lock (childrenPrim)
  678. {
  679. if (childrenPrim.Count > 0)
  680. {
  681. foreach (OdePrim prm in childrenPrim)
  682. {
  683. _parent_scene.DeactivatePrim(prm);
  684. prm.Body = IntPtr.Zero;
  685. }
  686. }
  687. }
  688. Body = IntPtr.Zero;
  689. }
  690. }
  691. else
  692. {
  693. _parent_scene.DeactivatePrim(this);
  694. m_collisionCategories &= ~CollisionCategories.Body;
  695. m_collisionFlags &= ~(CollisionCategories.Wind | CollisionCategories.Land);
  696. if (m_assetFailed)
  697. {
  698. d.GeomSetCategoryBits(prim_geom, 0);
  699. d.GeomSetCollideBits(prim_geom, 0);
  700. }
  701. else
  702. {
  703. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  704. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  705. }
  706. Body = IntPtr.Zero;
  707. }
  708. }
  709. m_disabled = true;
  710. m_collisionscore = 0;
  711. }
  712. private static Dictionary<IMesh, IntPtr> m_MeshToTriMeshMap = new Dictionary<IMesh, IntPtr>();
  713. private void setMesh(OdeScene parent_scene, IMesh mesh)
  714. {
  715. // m_log.DebugFormat("[ODE PRIM]: Setting mesh on {0} to {1}", Name, mesh);
  716. // This sleeper is there to moderate how long it takes between
  717. // setting up the mesh and pre-processing it when we get rapid fire mesh requests on a single object
  718. //Thread.Sleep(10);
  719. //Kill Body so that mesh can re-make the geom
  720. if (IsPhysical && Body != IntPtr.Zero)
  721. {
  722. if (childPrim)
  723. {
  724. if (_parent != null)
  725. {
  726. OdePrim parent = (OdePrim)_parent;
  727. parent.ChildDelink(this);
  728. }
  729. }
  730. else
  731. {
  732. disableBody();
  733. }
  734. }
  735. IntPtr vertices, indices;
  736. int vertexCount, indexCount;
  737. int vertexStride, triStride;
  738. mesh.getVertexListAsPtrToFloatArray(out vertices, out vertexStride, out vertexCount); // Note, that vertices are fixed in unmanaged heap
  739. mesh.getIndexListAsPtrToIntArray(out indices, out triStride, out indexCount); // Also fixed, needs release after usage
  740. m_expectedCollisionContacts = indexCount;
  741. mesh.releaseSourceMeshData(); // free up the original mesh data to save memory
  742. // We must lock here since m_MeshToTriMeshMap is static and multiple scene threads may call this method at
  743. // the same time.
  744. lock (m_MeshToTriMeshMap)
  745. {
  746. if (m_MeshToTriMeshMap.ContainsKey(mesh))
  747. {
  748. _triMeshData = m_MeshToTriMeshMap[mesh];
  749. }
  750. else
  751. {
  752. _triMeshData = d.GeomTriMeshDataCreate();
  753. d.GeomTriMeshDataBuildSimple(_triMeshData, vertices, vertexStride, vertexCount, indices, indexCount, triStride);
  754. d.GeomTriMeshDataPreprocess(_triMeshData);
  755. m_MeshToTriMeshMap[mesh] = _triMeshData;
  756. }
  757. }
  758. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  759. try
  760. {
  761. SetGeom(d.CreateTriMesh(m_targetSpace, _triMeshData, parent_scene.triCallback, null, null));
  762. }
  763. catch (AccessViolationException)
  764. {
  765. m_log.ErrorFormat("[PHYSICS]: MESH LOCKED FOR {0}", Name);
  766. return;
  767. }
  768. // if (IsPhysical && Body == (IntPtr) 0)
  769. // {
  770. // Recreate the body
  771. // m_interpenetrationcount = 0;
  772. // m_collisionscore = 0;
  773. // enableBody();
  774. // }
  775. }
  776. internal void ProcessTaints()
  777. {
  778. #if SPAM
  779. Console.WriteLine("ZProcessTaints for " + Name);
  780. #endif
  781. // This must be processed as the very first taint so that later operations have a prim_geom to work with
  782. // if this is a new prim.
  783. if (m_taintadd)
  784. changeadd();
  785. if (!_position.ApproxEquals(m_taintposition, 0f))
  786. changemove();
  787. if (m_taintrot != _orientation)
  788. {
  789. if (childPrim && IsPhysical) // For physical child prim...
  790. {
  791. rotate();
  792. // KF: ODE will also rotate the parent prim!
  793. // so rotate the root back to where it was
  794. OdePrim parent = (OdePrim)_parent;
  795. parent.rotate();
  796. }
  797. else
  798. {
  799. //Just rotate the prim
  800. rotate();
  801. }
  802. }
  803. if (m_taintPhysics != IsPhysical && !(m_taintparent != _parent))
  804. changePhysicsStatus();
  805. if (!_size.ApproxEquals(m_taintsize, 0f))
  806. changesize();
  807. if (m_taintshape)
  808. changeshape();
  809. if (m_taintforce)
  810. changeAddForce();
  811. if (m_taintaddangularforce)
  812. changeAddAngularForce();
  813. if (!m_taintTorque.ApproxEquals(Vector3.Zero, 0.001f))
  814. changeSetTorque();
  815. if (m_taintdisable)
  816. changedisable();
  817. if (m_taintselected != m_isSelected)
  818. changeSelectedStatus();
  819. if (!m_taintVelocity.ApproxEquals(Vector3.Zero, 0.001f))
  820. changevelocity();
  821. if (m_taintparent != _parent)
  822. changelink();
  823. if (m_taintCollidesWater != m_collidesWater)
  824. changefloatonwater();
  825. if (!m_angularlock.ApproxEquals(m_taintAngularLock,0f))
  826. changeAngularLock();
  827. }
  828. /// <summary>
  829. /// Change prim in response to an angular lock taint.
  830. /// </summary>
  831. private void changeAngularLock()
  832. {
  833. // do we have a Physical object?
  834. if (Body != IntPtr.Zero)
  835. {
  836. //Check that we have a Parent
  837. //If we have a parent then we're not authorative here
  838. if (_parent == null)
  839. {
  840. if (!m_taintAngularLock.ApproxEquals(Vector3.One, 0f))
  841. {
  842. //d.BodySetFiniteRotationMode(Body, 0);
  843. //d.BodySetFiniteRotationAxis(Body,m_taintAngularLock.X,m_taintAngularLock.Y,m_taintAngularLock.Z);
  844. createAMotor(m_taintAngularLock);
  845. }
  846. else
  847. {
  848. if (Amotor != IntPtr.Zero)
  849. {
  850. d.JointDestroy(Amotor);
  851. Amotor = IntPtr.Zero;
  852. }
  853. }
  854. }
  855. }
  856. // Store this for later in case we get turned into a separate body
  857. m_angularlock = m_taintAngularLock;
  858. }
  859. /// <summary>
  860. /// Change prim in response to a link taint.
  861. /// </summary>
  862. private void changelink()
  863. {
  864. // If the newly set parent is not null
  865. // create link
  866. if (_parent == null && m_taintparent != null)
  867. {
  868. if (m_taintparent.PhysicsActorType == (int)ActorTypes.Prim)
  869. {
  870. OdePrim obj = (OdePrim)m_taintparent;
  871. //obj.disableBody();
  872. //Console.WriteLine("changelink calls ParentPrim");
  873. obj.AddChildPrim(this);
  874. /*
  875. if (obj.Body != (IntPtr)0 && Body != (IntPtr)0 && obj.Body != Body)
  876. {
  877. _linkJointGroup = d.JointGroupCreate(0);
  878. m_linkJoint = d.JointCreateFixed(_parent_scene.world, _linkJointGroup);
  879. d.JointAttach(m_linkJoint, obj.Body, Body);
  880. d.JointSetFixed(m_linkJoint);
  881. }
  882. */
  883. }
  884. }
  885. // If the newly set parent is null
  886. // destroy link
  887. else if (_parent != null && m_taintparent == null)
  888. {
  889. //Console.WriteLine(" changelink B");
  890. if (_parent is OdePrim)
  891. {
  892. OdePrim obj = (OdePrim)_parent;
  893. obj.ChildDelink(this);
  894. childPrim = false;
  895. //_parent = null;
  896. }
  897. /*
  898. if (Body != (IntPtr)0 && _linkJointGroup != (IntPtr)0)
  899. d.JointGroupDestroy(_linkJointGroup);
  900. _linkJointGroup = (IntPtr)0;
  901. m_linkJoint = (IntPtr)0;
  902. */
  903. }
  904. _parent = m_taintparent;
  905. m_taintPhysics = IsPhysical;
  906. }
  907. /// <summary>
  908. /// Add a child prim to this parent prim.
  909. /// </summary>
  910. /// <param name="prim">Child prim</param>
  911. private void AddChildPrim(OdePrim prim)
  912. {
  913. if (LocalID == prim.LocalID)
  914. return;
  915. if (Body == IntPtr.Zero)
  916. {
  917. Body = d.BodyCreate(_parent_scene.world);
  918. setMass();
  919. }
  920. lock (childrenPrim)
  921. {
  922. if (childrenPrim.Contains(prim))
  923. return;
  924. // m_log.DebugFormat(
  925. // "[ODE PRIM]: Linking prim {0} {1} to {2} {3}", prim.Name, prim.LocalID, Name, LocalID);
  926. childrenPrim.Add(prim);
  927. foreach (OdePrim prm in childrenPrim)
  928. {
  929. d.Mass m2;
  930. d.MassSetZero(out m2);
  931. d.MassSetBoxTotal(out m2, prim.CalculateMass(), prm._size.X, prm._size.Y, prm._size.Z);
  932. d.Quaternion quat = new d.Quaternion();
  933. quat.W = prm._orientation.W;
  934. quat.X = prm._orientation.X;
  935. quat.Y = prm._orientation.Y;
  936. quat.Z = prm._orientation.Z;
  937. d.Matrix3 mat = new d.Matrix3();
  938. d.RfromQ(out mat, ref quat);
  939. d.MassRotate(ref m2, ref mat);
  940. d.MassTranslate(ref m2, Position.X - prm.Position.X, Position.Y - prm.Position.Y, Position.Z - prm.Position.Z);
  941. d.MassAdd(ref pMass, ref m2);
  942. }
  943. foreach (OdePrim prm in childrenPrim)
  944. {
  945. prm.m_collisionCategories |= CollisionCategories.Body;
  946. prm.m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  947. //Console.WriteLine(" GeomSetCategoryBits 1: " + prm.prim_geom + " - " + (int)prm.m_collisionCategories + " for " + Name);
  948. if (prm.m_assetFailed)
  949. {
  950. d.GeomSetCategoryBits(prm.prim_geom, 0);
  951. d.GeomSetCollideBits(prm.prim_geom, prm.BadMeshAssetCollideBits);
  952. }
  953. else
  954. {
  955. d.GeomSetCategoryBits(prm.prim_geom, (int)prm.m_collisionCategories);
  956. d.GeomSetCollideBits(prm.prim_geom, (int)prm.m_collisionFlags);
  957. }
  958. d.Quaternion quat = new d.Quaternion();
  959. quat.W = prm._orientation.W;
  960. quat.X = prm._orientation.X;
  961. quat.Y = prm._orientation.Y;
  962. quat.Z = prm._orientation.Z;
  963. d.Matrix3 mat = new d.Matrix3();
  964. d.RfromQ(out mat, ref quat);
  965. if (Body != IntPtr.Zero)
  966. {
  967. d.GeomSetBody(prm.prim_geom, Body);
  968. prm.childPrim = true;
  969. d.GeomSetOffsetWorldPosition(prm.prim_geom, prm.Position.X , prm.Position.Y, prm.Position.Z);
  970. //d.GeomSetOffsetPosition(prim.prim_geom,
  971. // (Position.X - prm.Position.X) - pMass.c.X,
  972. // (Position.Y - prm.Position.Y) - pMass.c.Y,
  973. // (Position.Z - prm.Position.Z) - pMass.c.Z);
  974. d.GeomSetOffsetWorldRotation(prm.prim_geom, ref mat);
  975. //d.GeomSetOffsetRotation(prm.prim_geom, ref mat);
  976. d.MassTranslate(ref pMass, -pMass.c.X, -pMass.c.Y, -pMass.c.Z);
  977. d.BodySetMass(Body, ref pMass);
  978. }
  979. else
  980. {
  981. m_log.DebugFormat("[PHYSICS]: {0} ain't got no boooooooooddy, no body", Name);
  982. }
  983. prm.m_interpenetrationcount = 0;
  984. prm.m_collisionscore = 0;
  985. prm.m_disabled = false;
  986. // The body doesn't already have a finite rotation mode set here
  987. if ((!m_angularlock.ApproxEquals(Vector3.Zero, 0f)) && _parent == null)
  988. {
  989. prm.createAMotor(m_angularlock);
  990. }
  991. prm.Body = Body;
  992. _parent_scene.ActivatePrim(prm);
  993. }
  994. m_collisionCategories |= CollisionCategories.Body;
  995. m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  996. if (m_assetFailed)
  997. {
  998. d.GeomSetCategoryBits(prim_geom, 0);
  999. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1000. }
  1001. else
  1002. {
  1003. //Console.WriteLine("GeomSetCategoryBits 2: " + prim_geom + " - " + (int)m_collisionCategories + " for " + Name);
  1004. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1005. //Console.WriteLine(" Post GeomSetCategoryBits 2");
  1006. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1007. }
  1008. d.Quaternion quat2 = new d.Quaternion();
  1009. quat2.W = _orientation.W;
  1010. quat2.X = _orientation.X;
  1011. quat2.Y = _orientation.Y;
  1012. quat2.Z = _orientation.Z;
  1013. d.Matrix3 mat2 = new d.Matrix3();
  1014. d.RfromQ(out mat2, ref quat2);
  1015. d.GeomSetBody(prim_geom, Body);
  1016. d.GeomSetOffsetWorldPosition(prim_geom, Position.X - pMass.c.X, Position.Y - pMass.c.Y, Position.Z - pMass.c.Z);
  1017. //d.GeomSetOffsetPosition(prim.prim_geom,
  1018. // (Position.X - prm.Position.X) - pMass.c.X,
  1019. // (Position.Y - prm.Position.Y) - pMass.c.Y,
  1020. // (Position.Z - prm.Position.Z) - pMass.c.Z);
  1021. //d.GeomSetOffsetRotation(prim_geom, ref mat2);
  1022. d.MassTranslate(ref pMass, -pMass.c.X, -pMass.c.Y, -pMass.c.Z);
  1023. d.BodySetMass(Body, ref pMass);
  1024. d.BodySetAutoDisableFlag(Body, true);
  1025. d.BodySetAutoDisableSteps(Body, body_autodisable_frames);
  1026. m_interpenetrationcount = 0;
  1027. m_collisionscore = 0;
  1028. m_disabled = false;
  1029. // The body doesn't already have a finite rotation mode set here
  1030. if ((!m_angularlock.ApproxEquals(Vector3.Zero, 0f)) && _parent == null)
  1031. {
  1032. createAMotor(m_angularlock);
  1033. }
  1034. d.BodySetPosition(Body, Position.X, Position.Y, Position.Z);
  1035. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1036. m_vehicle.Enable(Body, _parent_scene);
  1037. _parent_scene.ActivatePrim(this);
  1038. }
  1039. }
  1040. private void ChildSetGeom(OdePrim odePrim)
  1041. {
  1042. // m_log.DebugFormat(
  1043. // "[ODE PRIM]: ChildSetGeom {0} {1} for {2} {3}", odePrim.Name, odePrim.LocalID, Name, LocalID);
  1044. //if (IsPhysical && Body != IntPtr.Zero)
  1045. lock (childrenPrim)
  1046. {
  1047. foreach (OdePrim prm in childrenPrim)
  1048. {
  1049. //prm.childPrim = true;
  1050. prm.disableBody();
  1051. //prm.m_taintparent = null;
  1052. //prm._parent = null;
  1053. //prm.m_taintPhysics = false;
  1054. //prm.m_disabled = true;
  1055. //prm.childPrim = false;
  1056. }
  1057. }
  1058. disableBody();
  1059. // Spurious - Body == IntPtr.Zero after disableBody()
  1060. // if (Body != IntPtr.Zero)
  1061. // {
  1062. // _parent_scene.DeactivatePrim(this);
  1063. // }
  1064. lock (childrenPrim)
  1065. {
  1066. foreach (OdePrim prm in childrenPrim)
  1067. {
  1068. //Console.WriteLine("ChildSetGeom calls ParentPrim");
  1069. AddChildPrim(prm);
  1070. }
  1071. }
  1072. }
  1073. private void ChildDelink(OdePrim odePrim)
  1074. {
  1075. // m_log.DebugFormat(
  1076. // "[ODE PRIM]: Delinking prim {0} {1} from {2} {3}", odePrim.Name, odePrim.LocalID, Name, LocalID);
  1077. // Okay, we have a delinked child.. need to rebuild the body.
  1078. lock (childrenPrim)
  1079. {
  1080. foreach (OdePrim prm in childrenPrim)
  1081. {
  1082. prm.childPrim = true;
  1083. prm.disableBody();
  1084. //prm.m_taintparent = null;
  1085. //prm._parent = null;
  1086. //prm.m_taintPhysics = false;
  1087. //prm.m_disabled = true;
  1088. //prm.childPrim = false;
  1089. }
  1090. }
  1091. disableBody();
  1092. lock (childrenPrim)
  1093. {
  1094. //Console.WriteLine("childrenPrim.Remove " + odePrim);
  1095. childrenPrim.Remove(odePrim);
  1096. }
  1097. // Spurious - Body == IntPtr.Zero after disableBody()
  1098. // if (Body != IntPtr.Zero)
  1099. // {
  1100. // _parent_scene.DeactivatePrim(this);
  1101. // }
  1102. lock (childrenPrim)
  1103. {
  1104. foreach (OdePrim prm in childrenPrim)
  1105. {
  1106. //Console.WriteLine("ChildDelink calls ParentPrim");
  1107. AddChildPrim(prm);
  1108. }
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// Change prim in response to a selection taint.
  1113. /// </summary>
  1114. private void changeSelectedStatus()
  1115. {
  1116. if (m_taintselected)
  1117. {
  1118. m_collisionCategories = CollisionCategories.Selected;
  1119. m_collisionFlags = (CollisionCategories.Sensor | CollisionCategories.Space);
  1120. // We do the body disable soft twice because 'in theory' a collision could have happened
  1121. // in between the disabling and the collision properties setting
  1122. // which would wake the physical body up from a soft disabling and potentially cause it to fall
  1123. // through the ground.
  1124. // NOTE FOR JOINTS: this doesn't always work for jointed assemblies because if you select
  1125. // just one part of the assembly, the rest of the assembly is non-selected and still simulating,
  1126. // so that causes the selected part to wake up and continue moving.
  1127. // even if you select all parts of a jointed assembly, it is not guaranteed that the entire
  1128. // assembly will stop simulating during the selection, because of the lack of atomicity
  1129. // of select operations (their processing could be interrupted by a thread switch, causing
  1130. // simulation to continue before all of the selected object notifications trickle down to
  1131. // the physics engine).
  1132. // e.g. we select 100 prims that are connected by joints. non-atomically, the first 50 are
  1133. // selected and disabled. then, due to a thread switch, the selection processing is
  1134. // interrupted and the physics engine continues to simulate, so the last 50 items, whose
  1135. // selection was not yet processed, continues to simulate. this wakes up ALL of the
  1136. // first 50 again. then the last 50 are disabled. then the first 50, which were just woken
  1137. // up, start simulating again, which in turn wakes up the last 50.
  1138. if (IsPhysical)
  1139. {
  1140. disableBodySoft();
  1141. }
  1142. if (m_assetFailed)
  1143. {
  1144. d.GeomSetCategoryBits(prim_geom, 0);
  1145. d.GeomSetCollideBits(prim_geom, 0);
  1146. }
  1147. else
  1148. {
  1149. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1150. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1151. }
  1152. if (IsPhysical)
  1153. {
  1154. disableBodySoft();
  1155. }
  1156. }
  1157. else
  1158. {
  1159. m_collisionCategories = CollisionCategories.Geom;
  1160. if (IsPhysical)
  1161. m_collisionCategories |= CollisionCategories.Body;
  1162. m_collisionFlags = m_default_collisionFlags;
  1163. if (m_collidesLand)
  1164. m_collisionFlags |= CollisionCategories.Land;
  1165. if (m_collidesWater)
  1166. m_collisionFlags |= CollisionCategories.Water;
  1167. if (m_assetFailed)
  1168. {
  1169. d.GeomSetCategoryBits(prim_geom, 0);
  1170. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1171. }
  1172. else
  1173. {
  1174. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1175. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1176. }
  1177. if (IsPhysical)
  1178. {
  1179. if (Body != IntPtr.Zero)
  1180. {
  1181. d.BodySetLinearVel(Body, 0f, 0f, 0f);
  1182. d.BodySetForce(Body, 0, 0, 0);
  1183. enableBodySoft();
  1184. }
  1185. }
  1186. }
  1187. resetCollisionAccounting();
  1188. m_isSelected = m_taintselected;
  1189. }//end changeSelectedStatus
  1190. internal void ResetTaints()
  1191. {
  1192. m_taintposition = _position;
  1193. m_taintrot = _orientation;
  1194. m_taintPhysics = IsPhysical;
  1195. m_taintselected = m_isSelected;
  1196. m_taintsize = _size;
  1197. m_taintshape = false;
  1198. m_taintforce = false;
  1199. m_taintdisable = false;
  1200. m_taintVelocity = Vector3.Zero;
  1201. }
  1202. /// <summary>
  1203. /// Create a geometry for the given mesh in the given target space.
  1204. /// </summary>
  1205. /// <param name="m_targetSpace"></param>
  1206. /// <param name="mesh">If null, then a mesh is used that is based on the profile shape data.</param>
  1207. private void CreateGeom(IntPtr m_targetSpace, IMesh mesh)
  1208. {
  1209. #if SPAM
  1210. Console.WriteLine("CreateGeom:");
  1211. #endif
  1212. if (mesh != null)
  1213. {
  1214. setMesh(_parent_scene, mesh);
  1215. }
  1216. else
  1217. {
  1218. if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1)
  1219. {
  1220. if (_size.X == _size.Y && _size.Y == _size.Z && _size.X == _size.Z)
  1221. {
  1222. if (((_size.X / 2f) > 0f))
  1223. {
  1224. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1225. try
  1226. {
  1227. //Console.WriteLine(" CreateGeom 1");
  1228. SetGeom(d.CreateSphere(m_targetSpace, _size.X / 2));
  1229. m_expectedCollisionContacts = 3;
  1230. }
  1231. catch (AccessViolationException)
  1232. {
  1233. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1234. return;
  1235. }
  1236. }
  1237. else
  1238. {
  1239. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1240. try
  1241. {
  1242. //Console.WriteLine(" CreateGeom 2");
  1243. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1244. m_expectedCollisionContacts = 4;
  1245. }
  1246. catch (AccessViolationException)
  1247. {
  1248. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1249. return;
  1250. }
  1251. }
  1252. }
  1253. else
  1254. {
  1255. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1256. try
  1257. {
  1258. //Console.WriteLine(" CreateGeom 3");
  1259. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1260. m_expectedCollisionContacts = 4;
  1261. }
  1262. catch (AccessViolationException)
  1263. {
  1264. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1265. return;
  1266. }
  1267. }
  1268. }
  1269. else
  1270. {
  1271. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1272. try
  1273. {
  1274. //Console.WriteLine(" CreateGeom 4");
  1275. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1276. m_expectedCollisionContacts = 4;
  1277. }
  1278. catch (AccessViolationException)
  1279. {
  1280. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1281. return;
  1282. }
  1283. }
  1284. }
  1285. }
  1286. /// <summary>
  1287. /// Remove the existing geom from this prim.
  1288. /// </summary>
  1289. /// <param name="m_targetSpace"></param>
  1290. /// <param name="mesh">If null, then a mesh is used that is based on the profile shape data.</param>
  1291. /// <returns>true if the geom was successfully removed, false if it was already gone or the remove failed.</returns>
  1292. internal bool RemoveGeom()
  1293. {
  1294. if (prim_geom != IntPtr.Zero)
  1295. {
  1296. try
  1297. {
  1298. _parent_scene.geom_name_map.Remove(prim_geom);
  1299. _parent_scene.actor_name_map.Remove(prim_geom);
  1300. d.GeomDestroy(prim_geom);
  1301. m_expectedCollisionContacts = 0;
  1302. prim_geom = IntPtr.Zero;
  1303. }
  1304. catch (System.AccessViolationException)
  1305. {
  1306. prim_geom = IntPtr.Zero;
  1307. m_expectedCollisionContacts = 0;
  1308. m_log.ErrorFormat("[PHYSICS]: PrimGeom dead for {0}", Name);
  1309. return false;
  1310. }
  1311. return true;
  1312. }
  1313. else
  1314. {
  1315. m_log.WarnFormat(
  1316. "[ODE PRIM]: Called RemoveGeom() on {0} {1} where geometry was already null.", Name, LocalID);
  1317. return false;
  1318. }
  1319. }
  1320. /// <summary>
  1321. /// Add prim in response to an add taint.
  1322. /// </summary>
  1323. private void changeadd()
  1324. {
  1325. // m_log.DebugFormat("[ODE PRIM]: Adding prim {0}", Name);
  1326. int[] iprimspaceArrItem = _parent_scene.calculateSpaceArrayItemFromPos(_position);
  1327. IntPtr targetspace = _parent_scene.calculateSpaceForGeom(_position);
  1328. if (targetspace == IntPtr.Zero)
  1329. targetspace = _parent_scene.createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  1330. m_targetSpace = targetspace;
  1331. IMesh mesh = null;
  1332. if (_parent_scene.needsMeshing(_pbs))
  1333. {
  1334. // Don't need to re-enable body.. it's done in SetMesh
  1335. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical);
  1336. // createmesh returns null when it's a shape that isn't a cube.
  1337. // m_log.Debug(m_localID);
  1338. if (mesh == null)
  1339. CheckMeshAsset();
  1340. else
  1341. m_assetFailed = false;
  1342. }
  1343. #if SPAM
  1344. Console.WriteLine("changeadd 1");
  1345. #endif
  1346. CreateGeom(m_targetSpace, mesh);
  1347. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1348. d.Quaternion myrot = new d.Quaternion();
  1349. myrot.X = _orientation.X;
  1350. myrot.Y = _orientation.Y;
  1351. myrot.Z = _orientation.Z;
  1352. myrot.W = _orientation.W;
  1353. d.GeomSetQuaternion(prim_geom, ref myrot);
  1354. if (IsPhysical && Body == IntPtr.Zero)
  1355. enableBody();
  1356. changeSelectedStatus();
  1357. m_taintadd = false;
  1358. }
  1359. /// <summary>
  1360. /// Move prim in response to a move taint.
  1361. /// </summary>
  1362. private void changemove()
  1363. {
  1364. if (IsPhysical)
  1365. {
  1366. if (!m_disabled && !m_taintremove && !childPrim)
  1367. {
  1368. if (Body == IntPtr.Zero)
  1369. enableBody();
  1370. //Prim auto disable after 20 frames,
  1371. //if you move it, re-enable the prim manually.
  1372. if (_parent != null)
  1373. {
  1374. if (m_linkJoint != IntPtr.Zero)
  1375. {
  1376. d.JointDestroy(m_linkJoint);
  1377. m_linkJoint = IntPtr.Zero;
  1378. }
  1379. }
  1380. if (Body != IntPtr.Zero)
  1381. {
  1382. d.BodySetPosition(Body, _position.X, _position.Y, _position.Z);
  1383. if (_parent != null)
  1384. {
  1385. OdePrim odParent = (OdePrim)_parent;
  1386. if (Body != (IntPtr)0 && odParent.Body != (IntPtr)0 && Body != odParent.Body)
  1387. {
  1388. // KF: Fixed Joints were removed? Anyway - this Console.WriteLine does not show up, so routine is not used??
  1389. Console.WriteLine(" JointCreateFixed");
  1390. m_linkJoint = d.JointCreateFixed(_parent_scene.world, _linkJointGroup);
  1391. d.JointAttach(m_linkJoint, Body, odParent.Body);
  1392. d.JointSetFixed(m_linkJoint);
  1393. }
  1394. }
  1395. d.BodyEnable(Body);
  1396. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1397. {
  1398. m_vehicle.Enable(Body, _parent_scene);
  1399. }
  1400. }
  1401. else
  1402. {
  1403. m_log.WarnFormat("[PHYSICS]: Body for {0} still null after enableBody(). This is a crash scenario.", Name);
  1404. }
  1405. }
  1406. //else
  1407. // {
  1408. //m_log.Debug("[BUG]: race!");
  1409. //}
  1410. }
  1411. // string primScenAvatarIn = _parent_scene.whichspaceamIin(_position);
  1412. // int[] arrayitem = _parent_scene.calculateSpaceArrayItemFromPos(_position);
  1413. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1414. IntPtr tempspace = _parent_scene.recalculateSpaceForGeom(prim_geom, _position, m_targetSpace);
  1415. m_targetSpace = tempspace;
  1416. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1417. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1418. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1419. d.SpaceAdd(m_targetSpace, prim_geom);
  1420. changeSelectedStatus();
  1421. resetCollisionAccounting();
  1422. m_taintposition = _position;
  1423. }
  1424. internal void Move(float timestep)
  1425. {
  1426. float fx = 0;
  1427. float fy = 0;
  1428. float fz = 0;
  1429. if (IsPhysical && (Body != IntPtr.Zero) && !m_isSelected && !childPrim) // KF: Only move root prims.
  1430. {
  1431. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1432. {
  1433. // 'VEHICLES' are dealt with in ODEDynamics.cs
  1434. m_vehicle.Step(timestep, _parent_scene);
  1435. }
  1436. else
  1437. {
  1438. //Console.WriteLine("Move " + Name);
  1439. if (!d.BodyIsEnabled (Body)) d.BodyEnable (Body); // KF add 161009
  1440. // NON-'VEHICLES' are dealt with here
  1441. // if (d.BodyIsEnabled(Body) && !m_angularlock.ApproxEquals(Vector3.Zero, 0.003f))
  1442. // {
  1443. // d.Vector3 avel2 = d.BodyGetAngularVel(Body);
  1444. // /*
  1445. // if (m_angularlock.X == 1)
  1446. // avel2.X = 0;
  1447. // if (m_angularlock.Y == 1)
  1448. // avel2.Y = 0;
  1449. // if (m_angularlock.Z == 1)
  1450. // avel2.Z = 0;
  1451. // d.BodySetAngularVel(Body, avel2.X, avel2.Y, avel2.Z);
  1452. // */
  1453. // }
  1454. //float PID_P = 900.0f;
  1455. float m_mass = CalculateMass();
  1456. // fz = 0f;
  1457. //m_log.Info(m_collisionFlags.ToString());
  1458. //KF: m_buoyancy should be set by llSetBuoyancy() for non-vehicle.
  1459. // would come from SceneObjectPart.cs, public void SetBuoyancy(float fvalue) , PhysActor.Buoyancy = fvalue; ??
  1460. // m_buoyancy: (unlimited value) <0=Falls fast; 0=1g; 1=0g; >1 = floats up
  1461. // gravityz multiplier = 1 - m_buoyancy
  1462. fz = _parent_scene.gravityz * (1.0f - m_buoyancy) * m_mass;
  1463. if (m_usePID)
  1464. {
  1465. //Console.WriteLine("PID " + Name);
  1466. // KF - this is for object move? eg. llSetPos() ?
  1467. //if (!d.BodyIsEnabled(Body))
  1468. //d.BodySetForce(Body, 0f, 0f, 0f);
  1469. // If we're using the PID controller, then we have no gravity
  1470. //fz = (-1 * _parent_scene.gravityz) * m_mass; //KF: ?? Prims have no global gravity,so simply...
  1471. fz = 0f;
  1472. // no lock; for now it's only called from within Simulate()
  1473. // If the PID Controller isn't active then we set our force
  1474. // calculating base velocity to the current position
  1475. if ((m_PIDTau < 1) && (m_PIDTau != 0))
  1476. {
  1477. //PID_G = PID_G / m_PIDTau;
  1478. m_PIDTau = 1;
  1479. }
  1480. if ((PID_G - m_PIDTau) <= 0)
  1481. {
  1482. PID_G = m_PIDTau + 1;
  1483. }
  1484. //PidStatus = true;
  1485. // PhysicsVector vec = new PhysicsVector();
  1486. d.Vector3 vel = d.BodyGetLinearVel(Body);
  1487. d.Vector3 pos = d.BodyGetPosition(Body);
  1488. _target_velocity =
  1489. new Vector3(
  1490. (m_PIDTarget.X - pos.X) * ((PID_G - m_PIDTau) * timestep),
  1491. (m_PIDTarget.Y - pos.Y) * ((PID_G - m_PIDTau) * timestep),
  1492. (m_PIDTarget.Z - pos.Z) * ((PID_G - m_PIDTau) * timestep)
  1493. );
  1494. // if velocity is zero, use position control; otherwise, velocity control
  1495. if (_target_velocity.ApproxEquals(Vector3.Zero,0.1f))
  1496. {
  1497. // keep track of where we stopped. No more slippin' & slidin'
  1498. // We only want to deactivate the PID Controller if we think we want to have our surrogate
  1499. // react to the physics scene by moving it's position.
  1500. // Avatar to Avatar collisions
  1501. // Prim to avatar collisions
  1502. //fx = (_target_velocity.X - vel.X) * (PID_D) + (_zeroPosition.X - pos.X) * (PID_P * 2);
  1503. //fy = (_target_velocity.Y - vel.Y) * (PID_D) + (_zeroPosition.Y - pos.Y) * (PID_P * 2);
  1504. //fz = fz + (_target_velocity.Z - vel.Z) * (PID_D) + (_zeroPosition.Z - pos.Z) * PID_P;
  1505. d.BodySetPosition(Body, m_PIDTarget.X, m_PIDTarget.Y, m_PIDTarget.Z);
  1506. d.BodySetLinearVel(Body, 0, 0, 0);
  1507. d.BodyAddForce(Body, 0, 0, fz);
  1508. return;
  1509. }
  1510. else
  1511. {
  1512. _zeroFlag = false;
  1513. // We're flying and colliding with something
  1514. fx = ((_target_velocity.X) - vel.X) * (PID_D);
  1515. fy = ((_target_velocity.Y) - vel.Y) * (PID_D);
  1516. // vec.Z = (_target_velocity.Z - vel.Z) * PID_D + (_zeroPosition.Z - pos.Z) * PID_P;
  1517. fz = fz + ((_target_velocity.Z - vel.Z) * (PID_D) * m_mass);
  1518. }
  1519. } // end if (m_usePID)
  1520. // Hover PID Controller needs to be mutually exlusive to MoveTo PID controller
  1521. if (m_useHoverPID && !m_usePID)
  1522. {
  1523. //Console.WriteLine("Hover " + Name);
  1524. // If we're using the PID controller, then we have no gravity
  1525. fz = (-1 * _parent_scene.gravityz) * m_mass;
  1526. // no lock; for now it's only called from within Simulate()
  1527. // If the PID Controller isn't active then we set our force
  1528. // calculating base velocity to the current position
  1529. if ((m_PIDTau < 1))
  1530. {
  1531. PID_G = PID_G / m_PIDTau;
  1532. }
  1533. if ((PID_G - m_PIDTau) <= 0)
  1534. {
  1535. PID_G = m_PIDTau + 1;
  1536. }
  1537. // Where are we, and where are we headed?
  1538. d.Vector3 pos = d.BodyGetPosition(Body);
  1539. d.Vector3 vel = d.BodyGetLinearVel(Body);
  1540. // Non-Vehicles have a limited set of Hover options.
  1541. // determine what our target height really is based on HoverType
  1542. switch (m_PIDHoverType)
  1543. {
  1544. case PIDHoverType.Ground:
  1545. m_groundHeight = _parent_scene.GetTerrainHeightAtXY(pos.X, pos.Y);
  1546. m_targetHoverHeight = m_groundHeight + m_PIDHoverHeight;
  1547. break;
  1548. case PIDHoverType.GroundAndWater:
  1549. m_groundHeight = _parent_scene.GetTerrainHeightAtXY(pos.X, pos.Y);
  1550. m_waterHeight = _parent_scene.GetWaterLevel();
  1551. if (m_groundHeight > m_waterHeight)
  1552. {
  1553. m_targetHoverHeight = m_groundHeight + m_PIDHoverHeight;
  1554. }
  1555. else
  1556. {
  1557. m_targetHoverHeight = m_waterHeight + m_PIDHoverHeight;
  1558. }
  1559. break;
  1560. } // end switch (m_PIDHoverType)
  1561. _target_velocity =
  1562. new Vector3(0.0f, 0.0f,
  1563. (m_targetHoverHeight - pos.Z) * ((PID_G - m_PIDHoverTau) * timestep)
  1564. );
  1565. // if velocity is zero, use position control; otherwise, velocity control
  1566. if (_target_velocity.ApproxEquals(Vector3.Zero, 0.1f))
  1567. {
  1568. // keep track of where we stopped. No more slippin' & slidin'
  1569. // We only want to deactivate the PID Controller if we think we want to have our surrogate
  1570. // react to the physics scene by moving it's position.
  1571. // Avatar to Avatar collisions
  1572. // Prim to avatar collisions
  1573. d.BodySetPosition(Body, pos.X, pos.Y, m_targetHoverHeight);
  1574. d.BodySetLinearVel(Body, vel.X, vel.Y, 0);
  1575. d.BodyAddForce(Body, 0, 0, fz);
  1576. return;
  1577. }
  1578. else
  1579. {
  1580. _zeroFlag = false;
  1581. // We're flying and colliding with something
  1582. fz = fz + ((_target_velocity.Z - vel.Z) * (PID_D) * m_mass);
  1583. }
  1584. }
  1585. fx *= m_mass;
  1586. fy *= m_mass;
  1587. //fz *= m_mass;
  1588. fx += m_force.X;
  1589. fy += m_force.Y;
  1590. fz += m_force.Z;
  1591. //m_log.Info("[OBJPID]: X:" + fx.ToString() + " Y:" + fy.ToString() + " Z:" + fz.ToString());
  1592. if (fx != 0 || fy != 0 || fz != 0)
  1593. {
  1594. //m_taintdisable = true;
  1595. //base.RaiseOutOfBounds(Position);
  1596. //d.BodySetLinearVel(Body, fx, fy, 0f);
  1597. if (!d.BodyIsEnabled(Body))
  1598. {
  1599. // A physical body at rest on a surface will auto-disable after a while,
  1600. // this appears to re-enable it incase the surface it is upon vanishes,
  1601. // and the body should fall again.
  1602. d.BodySetLinearVel(Body, 0f, 0f, 0f);
  1603. d.BodySetForce(Body, 0, 0, 0);
  1604. enableBodySoft();
  1605. }
  1606. // 35x10 = 350n times the mass per second applied maximum.
  1607. float nmax = 35f * m_mass;
  1608. float nmin = -35f * m_mass;
  1609. if (fx > nmax)
  1610. fx = nmax;
  1611. if (fx < nmin)
  1612. fx = nmin;
  1613. if (fy > nmax)
  1614. fy = nmax;
  1615. if (fy < nmin)
  1616. fy = nmin;
  1617. d.BodyAddForce(Body, fx, fy, fz);
  1618. //Console.WriteLine("AddForce " + fx + "," + fy + "," + fz);
  1619. }
  1620. }
  1621. }
  1622. else
  1623. { // is not physical, or is not a body or is selected
  1624. // _zeroPosition = d.BodyGetPosition(Body);
  1625. return;
  1626. //Console.WriteLine("Nothing " + Name);
  1627. }
  1628. }
  1629. private void rotate()
  1630. {
  1631. d.Quaternion myrot = new d.Quaternion();
  1632. myrot.X = _orientation.X;
  1633. myrot.Y = _orientation.Y;
  1634. myrot.Z = _orientation.Z;
  1635. myrot.W = _orientation.W;
  1636. if (Body != IntPtr.Zero)
  1637. {
  1638. // KF: If this is a root prim do BodySet
  1639. d.BodySetQuaternion(Body, ref myrot);
  1640. if (IsPhysical)
  1641. {
  1642. if (!m_angularlock.ApproxEquals(Vector3.One, 0f))
  1643. createAMotor(m_angularlock);
  1644. }
  1645. }
  1646. else
  1647. {
  1648. // daughter prim, do Geom set
  1649. d.GeomSetQuaternion(prim_geom, ref myrot);
  1650. }
  1651. resetCollisionAccounting();
  1652. m_taintrot = _orientation;
  1653. }
  1654. private void resetCollisionAccounting()
  1655. {
  1656. m_collisionscore = 0;
  1657. m_interpenetrationcount = 0;
  1658. m_disabled = false;
  1659. }
  1660. /// <summary>
  1661. /// Change prim in response to a disable taint.
  1662. /// </summary>
  1663. private void changedisable()
  1664. {
  1665. m_disabled = true;
  1666. if (Body != IntPtr.Zero)
  1667. {
  1668. d.BodyDisable(Body);
  1669. Body = IntPtr.Zero;
  1670. }
  1671. m_taintdisable = false;
  1672. }
  1673. /// <summary>
  1674. /// Change prim in response to a physics status taint
  1675. /// </summary>
  1676. private void changePhysicsStatus()
  1677. {
  1678. if (IsPhysical)
  1679. {
  1680. if (Body == IntPtr.Zero)
  1681. {
  1682. if (_pbs.SculptEntry && _parent_scene.meshSculptedPrim)
  1683. {
  1684. changeshape();
  1685. }
  1686. else
  1687. {
  1688. enableBody();
  1689. }
  1690. }
  1691. }
  1692. else
  1693. {
  1694. if (Body != IntPtr.Zero)
  1695. {
  1696. if (_pbs.SculptEntry && _parent_scene.meshSculptedPrim)
  1697. {
  1698. RemoveGeom();
  1699. //Console.WriteLine("changePhysicsStatus for " + Name);
  1700. changeadd();
  1701. }
  1702. if (childPrim)
  1703. {
  1704. if (_parent != null)
  1705. {
  1706. OdePrim parent = (OdePrim)_parent;
  1707. parent.ChildDelink(this);
  1708. }
  1709. }
  1710. else
  1711. {
  1712. disableBody();
  1713. }
  1714. }
  1715. }
  1716. changeSelectedStatus();
  1717. resetCollisionAccounting();
  1718. m_taintPhysics = IsPhysical;
  1719. }
  1720. /// <summary>
  1721. /// Change prim in response to a size taint.
  1722. /// </summary>
  1723. private void changesize()
  1724. {
  1725. #if SPAM
  1726. m_log.DebugFormat("[ODE PRIM]: Called changesize");
  1727. #endif
  1728. if (_size.X <= 0) _size.X = 0.01f;
  1729. if (_size.Y <= 0) _size.Y = 0.01f;
  1730. if (_size.Z <= 0) _size.Z = 0.01f;
  1731. //kill body to rebuild
  1732. if (IsPhysical && Body != IntPtr.Zero)
  1733. {
  1734. if (childPrim)
  1735. {
  1736. if (_parent != null)
  1737. {
  1738. OdePrim parent = (OdePrim)_parent;
  1739. parent.ChildDelink(this);
  1740. }
  1741. }
  1742. else
  1743. {
  1744. disableBody();
  1745. }
  1746. }
  1747. if (d.SpaceQuery(m_targetSpace, prim_geom))
  1748. {
  1749. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1750. d.SpaceRemove(m_targetSpace, prim_geom);
  1751. }
  1752. RemoveGeom();
  1753. // we don't need to do space calculation because the client sends a position update also.
  1754. IMesh mesh = null;
  1755. // Construction of new prim
  1756. if (_parent_scene.needsMeshing(_pbs))
  1757. {
  1758. float meshlod = _parent_scene.meshSculptLOD;
  1759. if (IsPhysical)
  1760. meshlod = _parent_scene.MeshSculptphysicalLOD;
  1761. // Don't need to re-enable body.. it's done in SetMesh
  1762. if (_parent_scene.needsMeshing(_pbs))
  1763. {
  1764. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical);
  1765. if (mesh == null)
  1766. CheckMeshAsset();
  1767. else
  1768. m_assetFailed = false;
  1769. }
  1770. }
  1771. CreateGeom(m_targetSpace, mesh);
  1772. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1773. d.Quaternion myrot = new d.Quaternion();
  1774. myrot.X = _orientation.X;
  1775. myrot.Y = _orientation.Y;
  1776. myrot.Z = _orientation.Z;
  1777. myrot.W = _orientation.W;
  1778. d.GeomSetQuaternion(prim_geom, ref myrot);
  1779. //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
  1780. if (IsPhysical && Body == IntPtr.Zero && !childPrim)
  1781. {
  1782. // Re creates body on size.
  1783. // EnableBody also does setMass()
  1784. enableBody();
  1785. d.BodyEnable(Body);
  1786. }
  1787. changeSelectedStatus();
  1788. if (childPrim)
  1789. {
  1790. if (_parent is OdePrim)
  1791. {
  1792. OdePrim parent = (OdePrim)_parent;
  1793. parent.ChildSetGeom(this);
  1794. }
  1795. }
  1796. resetCollisionAccounting();
  1797. m_taintsize = _size;
  1798. }
  1799. /// <summary>
  1800. /// Change prim in response to a float on water taint.
  1801. /// </summary>
  1802. /// <param name="timestep"></param>
  1803. private void changefloatonwater()
  1804. {
  1805. m_collidesWater = m_taintCollidesWater;
  1806. if (m_collidesWater)
  1807. {
  1808. m_collisionFlags |= CollisionCategories.Water;
  1809. }
  1810. else
  1811. {
  1812. m_collisionFlags &= ~CollisionCategories.Water;
  1813. }
  1814. if (m_assetFailed)
  1815. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1816. else
  1817. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1818. }
  1819. /// <summary>
  1820. /// Change prim in response to a shape taint.
  1821. /// </summary>
  1822. private void changeshape()
  1823. {
  1824. m_taintshape = false;
  1825. // Cleanup of old prim geometry and Bodies
  1826. if (IsPhysical && Body != IntPtr.Zero)
  1827. {
  1828. if (childPrim)
  1829. {
  1830. if (_parent != null)
  1831. {
  1832. OdePrim parent = (OdePrim)_parent;
  1833. parent.ChildDelink(this);
  1834. }
  1835. }
  1836. else
  1837. {
  1838. disableBody();
  1839. }
  1840. }
  1841. RemoveGeom();
  1842. // we don't need to do space calculation because the client sends a position update also.
  1843. if (_size.X <= 0) _size.X = 0.01f;
  1844. if (_size.Y <= 0) _size.Y = 0.01f;
  1845. if (_size.Z <= 0) _size.Z = 0.01f;
  1846. // Construction of new prim
  1847. IMesh mesh = null;
  1848. if (_parent_scene.needsMeshing(_pbs))
  1849. {
  1850. // Don't need to re-enable body.. it's done in CreateMesh
  1851. float meshlod = _parent_scene.meshSculptLOD;
  1852. if (IsPhysical)
  1853. meshlod = _parent_scene.MeshSculptphysicalLOD;
  1854. // createmesh returns null when it doesn't mesh.
  1855. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical);
  1856. if (mesh == null)
  1857. CheckMeshAsset();
  1858. else
  1859. m_assetFailed = false;
  1860. }
  1861. CreateGeom(m_targetSpace, mesh);
  1862. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1863. d.Quaternion myrot = new d.Quaternion();
  1864. //myrot.W = _orientation.w;
  1865. myrot.W = _orientation.W;
  1866. myrot.X = _orientation.X;
  1867. myrot.Y = _orientation.Y;
  1868. myrot.Z = _orientation.Z;
  1869. d.GeomSetQuaternion(prim_geom, ref myrot);
  1870. //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
  1871. if (IsPhysical && Body == IntPtr.Zero)
  1872. {
  1873. // Re creates body on size.
  1874. // EnableBody also does setMass()
  1875. enableBody();
  1876. if (Body != IntPtr.Zero)
  1877. {
  1878. d.BodyEnable(Body);
  1879. }
  1880. }
  1881. changeSelectedStatus();
  1882. if (childPrim)
  1883. {
  1884. if (_parent is OdePrim)
  1885. {
  1886. OdePrim parent = (OdePrim)_parent;
  1887. parent.ChildSetGeom(this);
  1888. }
  1889. }
  1890. resetCollisionAccounting();
  1891. // m_taintshape = false;
  1892. }
  1893. /// <summary>
  1894. /// Change prim in response to an add force taint.
  1895. /// </summary>
  1896. private void changeAddForce()
  1897. {
  1898. if (!m_isSelected)
  1899. {
  1900. lock (m_forcelist)
  1901. {
  1902. //m_log.Info("[PHYSICS]: dequeing forcelist");
  1903. if (IsPhysical)
  1904. {
  1905. Vector3 iforce = Vector3.Zero;
  1906. int i = 0;
  1907. try
  1908. {
  1909. for (i = 0; i < m_forcelist.Count; i++)
  1910. {
  1911. iforce = iforce + (m_forcelist[i] * 100);
  1912. }
  1913. }
  1914. catch (IndexOutOfRangeException)
  1915. {
  1916. m_forcelist = new List<Vector3>();
  1917. m_collisionscore = 0;
  1918. m_interpenetrationcount = 0;
  1919. m_taintforce = false;
  1920. return;
  1921. }
  1922. catch (ArgumentOutOfRangeException)
  1923. {
  1924. m_forcelist = new List<Vector3>();
  1925. m_collisionscore = 0;
  1926. m_interpenetrationcount = 0;
  1927. m_taintforce = false;
  1928. return;
  1929. }
  1930. d.BodyEnable(Body);
  1931. d.BodyAddForce(Body, iforce.X, iforce.Y, iforce.Z);
  1932. }
  1933. m_forcelist.Clear();
  1934. }
  1935. m_collisionscore = 0;
  1936. m_interpenetrationcount = 0;
  1937. }
  1938. m_taintforce = false;
  1939. }
  1940. /// <summary>
  1941. /// Change prim in response to a torque taint.
  1942. /// </summary>
  1943. private void changeSetTorque()
  1944. {
  1945. if (!m_isSelected)
  1946. {
  1947. if (IsPhysical && Body != IntPtr.Zero)
  1948. {
  1949. d.BodySetTorque(Body, m_taintTorque.X, m_taintTorque.Y, m_taintTorque.Z);
  1950. }
  1951. }
  1952. m_taintTorque = Vector3.Zero;
  1953. }
  1954. /// <summary>
  1955. /// Change prim in response to an angular force taint.
  1956. /// </summary>
  1957. private void changeAddAngularForce()
  1958. {
  1959. if (!m_isSelected)
  1960. {
  1961. lock (m_angularforcelist)
  1962. {
  1963. //m_log.Info("[PHYSICS]: dequeing forcelist");
  1964. if (IsPhysical)
  1965. {
  1966. Vector3 iforce = Vector3.Zero;
  1967. for (int i = 0; i < m_angularforcelist.Count; i++)
  1968. {
  1969. iforce = iforce + (m_angularforcelist[i] * 100);
  1970. }
  1971. d.BodyEnable(Body);
  1972. d.BodyAddTorque(Body, iforce.X, iforce.Y, iforce.Z);
  1973. }
  1974. m_angularforcelist.Clear();
  1975. }
  1976. m_collisionscore = 0;
  1977. m_interpenetrationcount = 0;
  1978. }
  1979. m_taintaddangularforce = false;
  1980. }
  1981. /// <summary>
  1982. /// Change prim in response to a velocity taint.
  1983. /// </summary>
  1984. private void changevelocity()
  1985. {
  1986. if (!m_isSelected)
  1987. {
  1988. // Not sure exactly why this sleep is here, but from experimentation it appears to stop an avatar
  1989. // walking through a default rez size prim if it keeps kicking it around - justincc.
  1990. Thread.Sleep(20);
  1991. if (IsPhysical)
  1992. {
  1993. if (Body != IntPtr.Zero)
  1994. {
  1995. d.BodySetLinearVel(Body, m_taintVelocity.X, m_taintVelocity.Y, m_taintVelocity.Z);
  1996. }
  1997. }
  1998. //resetCollisionAccounting();
  1999. }
  2000. m_taintVelocity = Vector3.Zero;
  2001. }
  2002. internal void setPrimForRemoval()
  2003. {
  2004. m_taintremove = true;
  2005. }
  2006. public override bool Flying
  2007. {
  2008. // no flying prims for you
  2009. get { return false; }
  2010. set { }
  2011. }
  2012. public override bool IsColliding
  2013. {
  2014. get { return iscolliding; }
  2015. set { iscolliding = value; }
  2016. }
  2017. public override bool CollidingGround
  2018. {
  2019. get { return false; }
  2020. set { return; }
  2021. }
  2022. public override bool CollidingObj
  2023. {
  2024. get { return false; }
  2025. set { return; }
  2026. }
  2027. public override bool ThrottleUpdates
  2028. {
  2029. get { return m_throttleUpdates; }
  2030. set { m_throttleUpdates = value; }
  2031. }
  2032. public override bool Stopped
  2033. {
  2034. get { return _zeroFlag; }
  2035. }
  2036. public override Vector3 Position
  2037. {
  2038. get { return _position; }
  2039. set { _position = value;
  2040. //m_log.Info("[PHYSICS]: " + _position.ToString());
  2041. }
  2042. }
  2043. public override Vector3 Size
  2044. {
  2045. get { return _size; }
  2046. set
  2047. {
  2048. if (value.IsFinite())
  2049. {
  2050. _size = value;
  2051. // m_log.DebugFormat("[PHYSICS]: Set size on {0} to {1}", Name, value);
  2052. }
  2053. else
  2054. {
  2055. m_log.WarnFormat("[PHYSICS]: Got NaN Size on object {0}", Name);
  2056. }
  2057. }
  2058. }
  2059. public override float Mass
  2060. {
  2061. get { return CalculateMass(); }
  2062. }
  2063. public override Vector3 Force
  2064. {
  2065. //get { return Vector3.Zero; }
  2066. get { return m_force; }
  2067. set
  2068. {
  2069. if (value.IsFinite())
  2070. {
  2071. m_force = value;
  2072. }
  2073. else
  2074. {
  2075. m_log.WarnFormat("[PHYSICS]: NaN in Force Applied to an Object {0}", Name);
  2076. }
  2077. }
  2078. }
  2079. public override int VehicleType
  2080. {
  2081. get { return (int)m_vehicle.Type; }
  2082. set { m_vehicle.ProcessTypeChange((Vehicle)value); }
  2083. }
  2084. public override void VehicleFloatParam(int param, float value)
  2085. {
  2086. m_vehicle.ProcessFloatVehicleParam((Vehicle) param, value);
  2087. }
  2088. public override void VehicleVectorParam(int param, Vector3 value)
  2089. {
  2090. m_vehicle.ProcessVectorVehicleParam((Vehicle) param, value);
  2091. }
  2092. public override void VehicleRotationParam(int param, Quaternion rotation)
  2093. {
  2094. m_vehicle.ProcessRotationVehicleParam((Vehicle) param, rotation);
  2095. }
  2096. public override void VehicleFlags(int param, bool remove)
  2097. {
  2098. m_vehicle.ProcessVehicleFlags(param, remove);
  2099. }
  2100. public override void SetVolumeDetect(int param)
  2101. {
  2102. // We have to lock the scene here so that an entire simulate loop either uses volume detect for all
  2103. // possible collisions with this prim or for none of them.
  2104. lock (_parent_scene.OdeLock)
  2105. {
  2106. m_isVolumeDetect = (param != 0);
  2107. }
  2108. }
  2109. public override Vector3 CenterOfMass
  2110. {
  2111. get { return Vector3.Zero; }
  2112. }
  2113. public override Vector3 GeometricCenter
  2114. {
  2115. get { return Vector3.Zero; }
  2116. }
  2117. public override PrimitiveBaseShape Shape
  2118. {
  2119. set
  2120. {
  2121. _pbs = value;
  2122. m_assetFailed = false;
  2123. m_taintshape = true;
  2124. }
  2125. }
  2126. public override Vector3 Velocity
  2127. {
  2128. get
  2129. {
  2130. // Average previous velocity with the new one so
  2131. // client object interpolation works a 'little' better
  2132. if (_zeroFlag)
  2133. return Vector3.Zero;
  2134. Vector3 returnVelocity = Vector3.Zero;
  2135. returnVelocity.X = (m_lastVelocity.X + _velocity.X) * 0.5f; // 0.5f is mathematically equiv to '/ 2'
  2136. returnVelocity.Y = (m_lastVelocity.Y + _velocity.Y) * 0.5f;
  2137. returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z) * 0.5f;
  2138. return returnVelocity;
  2139. }
  2140. set
  2141. {
  2142. if (value.IsFinite())
  2143. {
  2144. _velocity = value;
  2145. m_taintVelocity = value;
  2146. _parent_scene.AddPhysicsActorTaint(this);
  2147. }
  2148. else
  2149. {
  2150. m_log.WarnFormat("[PHYSICS]: Got NaN Velocity in Object {0}", Name);
  2151. }
  2152. }
  2153. }
  2154. public override Vector3 Torque
  2155. {
  2156. get
  2157. {
  2158. if (!IsPhysical || Body == IntPtr.Zero)
  2159. return Vector3.Zero;
  2160. return _torque;
  2161. }
  2162. set
  2163. {
  2164. if (value.IsFinite())
  2165. {
  2166. m_taintTorque = value;
  2167. _parent_scene.AddPhysicsActorTaint(this);
  2168. }
  2169. else
  2170. {
  2171. m_log.WarnFormat("[PHYSICS]: Got NaN Torque in Object {0}", Name);
  2172. }
  2173. }
  2174. }
  2175. public override float CollisionScore
  2176. {
  2177. get { return m_collisionscore; }
  2178. set { m_collisionscore = value; }
  2179. }
  2180. public override bool Kinematic
  2181. {
  2182. get { return false; }
  2183. set { }
  2184. }
  2185. public override Quaternion Orientation
  2186. {
  2187. get { return _orientation; }
  2188. set
  2189. {
  2190. if (QuaternionIsFinite(value))
  2191. _orientation = value;
  2192. else
  2193. m_log.WarnFormat("[PHYSICS]: Got NaN quaternion Orientation from Scene in Object {0}", Name);
  2194. }
  2195. }
  2196. private static bool QuaternionIsFinite(Quaternion q)
  2197. {
  2198. if (Single.IsNaN(q.X) || Single.IsInfinity(q.X))
  2199. return false;
  2200. if (Single.IsNaN(q.Y) || Single.IsInfinity(q.Y))
  2201. return false;
  2202. if (Single.IsNaN(q.Z) || Single.IsInfinity(q.Z))
  2203. return false;
  2204. if (Single.IsNaN(q.W) || Single.IsInfinity(q.W))
  2205. return false;
  2206. return true;
  2207. }
  2208. public override Vector3 Acceleration
  2209. {
  2210. get { return _acceleration; }
  2211. set { _acceleration = value; }
  2212. }
  2213. public override void AddForce(Vector3 force, bool pushforce)
  2214. {
  2215. if (force.IsFinite())
  2216. {
  2217. lock (m_forcelist)
  2218. m_forcelist.Add(force);
  2219. m_taintforce = true;
  2220. }
  2221. else
  2222. {
  2223. m_log.WarnFormat("[PHYSICS]: Got Invalid linear force vector from Scene in Object {0}", Name);
  2224. }
  2225. //m_log.Info("[PHYSICS]: Added Force:" + force.ToString() + " to prim at " + Position.ToString());
  2226. }
  2227. public override void AddAngularForce(Vector3 force, bool pushforce)
  2228. {
  2229. if (force.IsFinite())
  2230. {
  2231. m_angularforcelist.Add(force);
  2232. m_taintaddangularforce = true;
  2233. }
  2234. else
  2235. {
  2236. m_log.WarnFormat("[PHYSICS]: Got Invalid Angular force vector from Scene in Object {0}", Name);
  2237. }
  2238. }
  2239. public override Vector3 RotationalVelocity
  2240. {
  2241. get
  2242. {
  2243. Vector3 pv = Vector3.Zero;
  2244. if (_zeroFlag)
  2245. return pv;
  2246. m_lastUpdateSent = false;
  2247. if (m_rotationalVelocity.ApproxEquals(pv, 0.2f))
  2248. return pv;
  2249. return m_rotationalVelocity;
  2250. }
  2251. set
  2252. {
  2253. if (value.IsFinite())
  2254. {
  2255. m_rotationalVelocity = value;
  2256. }
  2257. else
  2258. {
  2259. m_log.WarnFormat("[PHYSICS]: Got NaN RotationalVelocity in Object {0}", Name);
  2260. }
  2261. }
  2262. }
  2263. public override void CrossingFailure()
  2264. {
  2265. m_crossingfailures++;
  2266. if (m_crossingfailures > _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2267. {
  2268. base.RaiseOutOfBounds(_position);
  2269. return;
  2270. }
  2271. else if (m_crossingfailures == _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2272. {
  2273. m_log.Warn("[PHYSICS]: Too many crossing failures for: " + Name);
  2274. }
  2275. }
  2276. public override float Buoyancy
  2277. {
  2278. get { return m_buoyancy; }
  2279. set { m_buoyancy = value; }
  2280. }
  2281. public override void link(PhysicsActor obj)
  2282. {
  2283. m_taintparent = obj;
  2284. }
  2285. public override void delink()
  2286. {
  2287. m_taintparent = null;
  2288. }
  2289. public override void LockAngularMotion(Vector3 axis)
  2290. {
  2291. // reverse the zero/non zero values for ODE.
  2292. if (axis.IsFinite())
  2293. {
  2294. axis.X = (axis.X > 0) ? 1f : 0f;
  2295. axis.Y = (axis.Y > 0) ? 1f : 0f;
  2296. axis.Z = (axis.Z > 0) ? 1f : 0f;
  2297. m_log.DebugFormat("[axislock]: <{0},{1},{2}>", axis.X, axis.Y, axis.Z);
  2298. m_taintAngularLock = axis;
  2299. }
  2300. else
  2301. {
  2302. m_log.WarnFormat("[PHYSICS]: Got NaN locking axis from Scene on Object {0}", Name);
  2303. }
  2304. }
  2305. internal void UpdatePositionAndVelocity()
  2306. {
  2307. // no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
  2308. if (_parent == null)
  2309. {
  2310. Vector3 pv = Vector3.Zero;
  2311. bool lastZeroFlag = _zeroFlag;
  2312. float m_minvelocity = 0;
  2313. if (Body != (IntPtr)0) // FIXME -> or if it is a joint
  2314. {
  2315. d.Vector3 vec = d.BodyGetPosition(Body);
  2316. d.Quaternion ori = d.BodyGetQuaternion(Body);
  2317. d.Vector3 vel = d.BodyGetLinearVel(Body);
  2318. d.Vector3 rotvel = d.BodyGetAngularVel(Body);
  2319. d.Vector3 torque = d.BodyGetTorque(Body);
  2320. _torque = new Vector3(torque.X, torque.Y, torque.Z);
  2321. Vector3 l_position = Vector3.Zero;
  2322. Quaternion l_orientation = Quaternion.Identity;
  2323. // kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
  2324. //if (vec.X < 0.0f) { vec.X = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2325. //if (vec.Y < 0.0f) { vec.Y = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2326. //if (vec.X > 255.95f) { vec.X = 255.95f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2327. //if (vec.Y > 255.95f) { vec.Y = 255.95f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2328. m_lastposition = _position;
  2329. m_lastorientation = _orientation;
  2330. l_position.X = vec.X;
  2331. l_position.Y = vec.Y;
  2332. l_position.Z = vec.Z;
  2333. l_orientation.X = ori.X;
  2334. l_orientation.Y = ori.Y;
  2335. l_orientation.Z = ori.Z;
  2336. l_orientation.W = ori.W;
  2337. if (l_position.X > ((int)_parent_scene.WorldExtents.X - 0.05f) || l_position.X < 0f || l_position.Y > ((int)_parent_scene.WorldExtents.Y - 0.05f) || l_position.Y < 0f)
  2338. {
  2339. //base.RaiseOutOfBounds(l_position);
  2340. if (m_crossingfailures < _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2341. {
  2342. _position = l_position;
  2343. //_parent_scene.remActivePrim(this);
  2344. if (_parent == null)
  2345. base.RequestPhysicsterseUpdate();
  2346. return;
  2347. }
  2348. else
  2349. {
  2350. if (_parent == null)
  2351. base.RaiseOutOfBounds(l_position);
  2352. return;
  2353. }
  2354. }
  2355. if (l_position.Z < 0)
  2356. {
  2357. // This is so prim that get lost underground don't fall forever and suck up
  2358. //
  2359. // Sim resources and memory.
  2360. // Disables the prim's movement physics....
  2361. // It's a hack and will generate a console message if it fails.
  2362. //IsPhysical = false;
  2363. if (_parent == null)
  2364. base.RaiseOutOfBounds(_position);
  2365. _acceleration.X = 0;
  2366. _acceleration.Y = 0;
  2367. _acceleration.Z = 0;
  2368. _velocity.X = 0;
  2369. _velocity.Y = 0;
  2370. _velocity.Z = 0;
  2371. m_rotationalVelocity.X = 0;
  2372. m_rotationalVelocity.Y = 0;
  2373. m_rotationalVelocity.Z = 0;
  2374. if (_parent == null)
  2375. base.RequestPhysicsterseUpdate();
  2376. m_throttleUpdates = false;
  2377. throttleCounter = 0;
  2378. _zeroFlag = true;
  2379. //outofBounds = true;
  2380. }
  2381. //float Adiff = 1.0f - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation));
  2382. //Console.WriteLine("Adiff " + Name + " = " + Adiff);
  2383. if ((Math.Abs(m_lastposition.X - l_position.X) < 0.02)
  2384. && (Math.Abs(m_lastposition.Y - l_position.Y) < 0.02)
  2385. && (Math.Abs(m_lastposition.Z - l_position.Z) < 0.02)
  2386. // && (1.0 - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation)) < 0.01))
  2387. && (1.0 - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation)) < 0.0001)) // KF 0.01 is far to large
  2388. {
  2389. _zeroFlag = true;
  2390. //Console.WriteLine("ZFT 2");
  2391. m_throttleUpdates = false;
  2392. }
  2393. else
  2394. {
  2395. //m_log.Debug(Math.Abs(m_lastposition.X - l_position.X).ToString());
  2396. _zeroFlag = false;
  2397. m_lastUpdateSent = false;
  2398. //m_throttleUpdates = false;
  2399. }
  2400. if (_zeroFlag)
  2401. {
  2402. _velocity.X = 0.0f;
  2403. _velocity.Y = 0.0f;
  2404. _velocity.Z = 0.0f;
  2405. _acceleration.X = 0;
  2406. _acceleration.Y = 0;
  2407. _acceleration.Z = 0;
  2408. //_orientation.w = 0f;
  2409. //_orientation.X = 0f;
  2410. //_orientation.Y = 0f;
  2411. //_orientation.Z = 0f;
  2412. m_rotationalVelocity.X = 0;
  2413. m_rotationalVelocity.Y = 0;
  2414. m_rotationalVelocity.Z = 0;
  2415. if (!m_lastUpdateSent)
  2416. {
  2417. m_throttleUpdates = false;
  2418. throttleCounter = 0;
  2419. m_rotationalVelocity = pv;
  2420. if (_parent == null)
  2421. {
  2422. base.RequestPhysicsterseUpdate();
  2423. }
  2424. m_lastUpdateSent = true;
  2425. }
  2426. }
  2427. else
  2428. {
  2429. if (lastZeroFlag != _zeroFlag)
  2430. {
  2431. if (_parent == null)
  2432. {
  2433. base.RequestPhysicsterseUpdate();
  2434. }
  2435. }
  2436. m_lastVelocity = _velocity;
  2437. _position = l_position;
  2438. _velocity.X = vel.X;
  2439. _velocity.Y = vel.Y;
  2440. _velocity.Z = vel.Z;
  2441. _acceleration = ((_velocity - m_lastVelocity) / 0.1f);
  2442. _acceleration = new Vector3(_velocity.X - m_lastVelocity.X / 0.1f, _velocity.Y - m_lastVelocity.Y / 0.1f, _velocity.Z - m_lastVelocity.Z / 0.1f);
  2443. //m_log.Info("[PHYSICS]: V1: " + _velocity + " V2: " + m_lastVelocity + " Acceleration: " + _acceleration.ToString());
  2444. // Note here that linearvelocity is affecting angular velocity... so I'm guessing this is a vehicle specific thing...
  2445. // it does make sense to do this for tiny little instabilities with physical prim, however 0.5m/frame is fairly large.
  2446. // reducing this to 0.02m/frame seems to help the angular rubberbanding quite a bit, however, to make sure it doesn't affect elevators and vehicles
  2447. // adding these logical exclusion situations to maintain this where I think it was intended to be.
  2448. if (m_throttleUpdates || m_usePID || (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE) || (Amotor != IntPtr.Zero))
  2449. {
  2450. m_minvelocity = 0.5f;
  2451. }
  2452. else
  2453. {
  2454. m_minvelocity = 0.02f;
  2455. }
  2456. if (_velocity.ApproxEquals(pv, m_minvelocity))
  2457. {
  2458. m_rotationalVelocity = pv;
  2459. }
  2460. else
  2461. {
  2462. m_rotationalVelocity = new Vector3(rotvel.X, rotvel.Y, rotvel.Z);
  2463. }
  2464. //m_log.Debug("ODE: " + m_rotationalVelocity.ToString());
  2465. _orientation.X = ori.X;
  2466. _orientation.Y = ori.Y;
  2467. _orientation.Z = ori.Z;
  2468. _orientation.W = ori.W;
  2469. m_lastUpdateSent = false;
  2470. if (!m_throttleUpdates || throttleCounter > _parent_scene.geomUpdatesPerThrottledUpdate)
  2471. {
  2472. if (_parent == null)
  2473. {
  2474. base.RequestPhysicsterseUpdate();
  2475. }
  2476. }
  2477. else
  2478. {
  2479. throttleCounter++;
  2480. }
  2481. }
  2482. m_lastposition = l_position;
  2483. }
  2484. else
  2485. {
  2486. // Not a body.. so Make sure the client isn't interpolating
  2487. _velocity.X = 0;
  2488. _velocity.Y = 0;
  2489. _velocity.Z = 0;
  2490. _acceleration.X = 0;
  2491. _acceleration.Y = 0;
  2492. _acceleration.Z = 0;
  2493. m_rotationalVelocity.X = 0;
  2494. m_rotationalVelocity.Y = 0;
  2495. m_rotationalVelocity.Z = 0;
  2496. _zeroFlag = true;
  2497. }
  2498. }
  2499. }
  2500. public override bool FloatOnWater
  2501. {
  2502. set {
  2503. m_taintCollidesWater = value;
  2504. _parent_scene.AddPhysicsActorTaint(this);
  2505. }
  2506. }
  2507. public override void SetMomentum(Vector3 momentum)
  2508. {
  2509. }
  2510. public override Vector3 PIDTarget
  2511. {
  2512. set
  2513. {
  2514. if (value.IsFinite())
  2515. {
  2516. m_PIDTarget = value;
  2517. }
  2518. else
  2519. m_log.WarnFormat("[PHYSICS]: Got NaN PIDTarget from Scene on Object {0}", Name);
  2520. }
  2521. }
  2522. public override bool PIDActive { set { m_usePID = value; } }
  2523. public override float PIDTau { set { m_PIDTau = value; } }
  2524. public override float PIDHoverHeight { set { m_PIDHoverHeight = value; ; } }
  2525. public override bool PIDHoverActive { set { m_useHoverPID = value; } }
  2526. public override PIDHoverType PIDHoverType { set { m_PIDHoverType = value; } }
  2527. public override float PIDHoverTau { set { m_PIDHoverTau = value; } }
  2528. public override Quaternion APIDTarget{ set { return; } }
  2529. public override bool APIDActive{ set { return; } }
  2530. public override float APIDStrength{ set { return; } }
  2531. public override float APIDDamping{ set { return; } }
  2532. private void createAMotor(Vector3 axis)
  2533. {
  2534. if (Body == IntPtr.Zero)
  2535. return;
  2536. if (Amotor != IntPtr.Zero)
  2537. {
  2538. d.JointDestroy(Amotor);
  2539. Amotor = IntPtr.Zero;
  2540. }
  2541. float axisnum = 3;
  2542. axisnum = (axisnum - (axis.X + axis.Y + axis.Z));
  2543. // PhysicsVector totalSize = new PhysicsVector(_size.X, _size.Y, _size.Z);
  2544. // Inverse Inertia Matrix, set the X, Y, and/r Z inertia to 0 then invert it again.
  2545. d.Mass objMass;
  2546. d.MassSetZero(out objMass);
  2547. DMassCopy(ref pMass, ref objMass);
  2548. //m_log.DebugFormat("1-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", objMass.I.M00, objMass.I.M01, objMass.I.M02, objMass.I.M10, objMass.I.M11, objMass.I.M12, objMass.I.M20, objMass.I.M21, objMass.I.M22);
  2549. Matrix4 dMassMat = FromDMass(objMass);
  2550. Matrix4 mathmat = Inverse(dMassMat);
  2551. /*
  2552. //m_log.DebugFormat("2-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", mathmat[0, 0], mathmat[0, 1], mathmat[0, 2], mathmat[1, 0], mathmat[1, 1], mathmat[1, 2], mathmat[2, 0], mathmat[2, 1], mathmat[2, 2]);
  2553. mathmat = Inverse(mathmat);
  2554. objMass = FromMatrix4(mathmat, ref objMass);
  2555. //m_log.DebugFormat("3-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", objMass.I.M00, objMass.I.M01, objMass.I.M02, objMass.I.M10, objMass.I.M11, objMass.I.M12, objMass.I.M20, objMass.I.M21, objMass.I.M22);
  2556. mathmat = Inverse(mathmat);
  2557. */
  2558. if (axis.X == 0)
  2559. {
  2560. mathmat.M33 = 50.0000001f;
  2561. //objMass.I.M22 = 0;
  2562. }
  2563. if (axis.Y == 0)
  2564. {
  2565. mathmat.M22 = 50.0000001f;
  2566. //objMass.I.M11 = 0;
  2567. }
  2568. if (axis.Z == 0)
  2569. {
  2570. mathmat.M11 = 50.0000001f;
  2571. //objMass.I.M00 = 0;
  2572. }
  2573. mathmat = Inverse(mathmat);
  2574. objMass = FromMatrix4(mathmat, ref objMass);
  2575. //m_log.DebugFormat("4-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", objMass.I.M00, objMass.I.M01, objMass.I.M02, objMass.I.M10, objMass.I.M11, objMass.I.M12, objMass.I.M20, objMass.I.M21, objMass.I.M22);
  2576. //return;
  2577. if (d.MassCheck(ref objMass))
  2578. {
  2579. d.BodySetMass(Body, ref objMass);
  2580. }
  2581. else
  2582. {
  2583. //m_log.Debug("[PHYSICS]: Mass invalid, ignoring");
  2584. }
  2585. if (axisnum <= 0)
  2586. return;
  2587. // int dAMotorEuler = 1;
  2588. Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
  2589. d.JointAttach(Amotor, Body, IntPtr.Zero);
  2590. d.JointSetAMotorMode(Amotor, 0);
  2591. d.JointSetAMotorNumAxes(Amotor,(int)axisnum);
  2592. int i = 0;
  2593. if (axis.X == 0)
  2594. {
  2595. d.JointSetAMotorAxis(Amotor, i, 0, 1, 0, 0);
  2596. i++;
  2597. }
  2598. if (axis.Y == 0)
  2599. {
  2600. d.JointSetAMotorAxis(Amotor, i, 0, 0, 1, 0);
  2601. i++;
  2602. }
  2603. if (axis.Z == 0)
  2604. {
  2605. d.JointSetAMotorAxis(Amotor, i, 0, 0, 0, 1);
  2606. i++;
  2607. }
  2608. for (int j = 0; j < (int)axisnum; j++)
  2609. {
  2610. //d.JointSetAMotorAngle(Amotor, j, 0);
  2611. }
  2612. //d.JointSetAMotorAngle(Amotor, 1, 0);
  2613. //d.JointSetAMotorAngle(Amotor, 2, 0);
  2614. // These lowstops and high stops are effectively (no wiggle room)
  2615. d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -0f);
  2616. d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0f);
  2617. d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -0f);
  2618. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0f);
  2619. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f);
  2620. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0f);
  2621. //d.JointSetAMotorParam(Amotor, (int) dParam.Vel, 9000f);
  2622. d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f);
  2623. d.JointSetAMotorParam(Amotor, (int)dParam.FMax, Mass * 50f);//
  2624. }
  2625. private Matrix4 FromDMass(d.Mass pMass)
  2626. {
  2627. Matrix4 obj;
  2628. obj.M11 = pMass.I.M00;
  2629. obj.M12 = pMass.I.M01;
  2630. obj.M13 = pMass.I.M02;
  2631. obj.M14 = 0;
  2632. obj.M21 = pMass.I.M10;
  2633. obj.M22 = pMass.I.M11;
  2634. obj.M23 = pMass.I.M12;
  2635. obj.M24 = 0;
  2636. obj.M31 = pMass.I.M20;
  2637. obj.M32 = pMass.I.M21;
  2638. obj.M33 = pMass.I.M22;
  2639. obj.M34 = 0;
  2640. obj.M41 = 0;
  2641. obj.M42 = 0;
  2642. obj.M43 = 0;
  2643. obj.M44 = 1;
  2644. return obj;
  2645. }
  2646. private d.Mass FromMatrix4(Matrix4 pMat, ref d.Mass obj)
  2647. {
  2648. obj.I.M00 = pMat[0, 0];
  2649. obj.I.M01 = pMat[0, 1];
  2650. obj.I.M02 = pMat[0, 2];
  2651. obj.I.M10 = pMat[1, 0];
  2652. obj.I.M11 = pMat[1, 1];
  2653. obj.I.M12 = pMat[1, 2];
  2654. obj.I.M20 = pMat[2, 0];
  2655. obj.I.M21 = pMat[2, 1];
  2656. obj.I.M22 = pMat[2, 2];
  2657. return obj;
  2658. }
  2659. public override void SubscribeEvents(int ms)
  2660. {
  2661. m_eventsubscription = ms;
  2662. _parent_scene.AddCollisionEventReporting(this);
  2663. }
  2664. public override void UnSubscribeEvents()
  2665. {
  2666. _parent_scene.RemoveCollisionEventReporting(this);
  2667. m_eventsubscription = 0;
  2668. }
  2669. public void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
  2670. {
  2671. CollisionEventsThisFrame.AddCollider(CollidedWith, contact);
  2672. }
  2673. public void SendCollisions()
  2674. {
  2675. if (m_collisionsOnPreviousFrame || CollisionEventsThisFrame.Count > 0)
  2676. {
  2677. base.SendCollisionUpdate(CollisionEventsThisFrame);
  2678. if (CollisionEventsThisFrame.Count > 0)
  2679. {
  2680. m_collisionsOnPreviousFrame = true;
  2681. CollisionEventsThisFrame.Clear();
  2682. }
  2683. else
  2684. {
  2685. m_collisionsOnPreviousFrame = false;
  2686. }
  2687. }
  2688. }
  2689. public override bool SubscribedEvents()
  2690. {
  2691. if (m_eventsubscription > 0)
  2692. return true;
  2693. return false;
  2694. }
  2695. public static Matrix4 Inverse(Matrix4 pMat)
  2696. {
  2697. if (determinant3x3(pMat) == 0)
  2698. {
  2699. return Matrix4.Identity; // should probably throw an error. singluar matrix inverse not possible
  2700. }
  2701. return (Adjoint(pMat) / determinant3x3(pMat));
  2702. }
  2703. public static Matrix4 Adjoint(Matrix4 pMat)
  2704. {
  2705. Matrix4 adjointMatrix = new Matrix4();
  2706. for (int i=0; i<4; i++)
  2707. {
  2708. for (int j=0; j<4; j++)
  2709. {
  2710. Matrix4SetValue(ref adjointMatrix, i, j, (float)(Math.Pow(-1, i + j) * (determinant3x3(Minor(pMat, i, j)))));
  2711. }
  2712. }
  2713. adjointMatrix = Transpose(adjointMatrix);
  2714. return adjointMatrix;
  2715. }
  2716. public static Matrix4 Minor(Matrix4 matrix, int iRow, int iCol)
  2717. {
  2718. Matrix4 minor = new Matrix4();
  2719. int m = 0, n = 0;
  2720. for (int i = 0; i < 4; i++)
  2721. {
  2722. if (i == iRow)
  2723. continue;
  2724. n = 0;
  2725. for (int j = 0; j < 4; j++)
  2726. {
  2727. if (j == iCol)
  2728. continue;
  2729. Matrix4SetValue(ref minor, m,n, matrix[i, j]);
  2730. n++;
  2731. }
  2732. m++;
  2733. }
  2734. return minor;
  2735. }
  2736. public static Matrix4 Transpose(Matrix4 pMat)
  2737. {
  2738. Matrix4 transposeMatrix = new Matrix4();
  2739. for (int i = 0; i < 4; i++)
  2740. for (int j = 0; j < 4; j++)
  2741. Matrix4SetValue(ref transposeMatrix, i, j, pMat[j, i]);
  2742. return transposeMatrix;
  2743. }
  2744. public static void Matrix4SetValue(ref Matrix4 pMat, int r, int c, float val)
  2745. {
  2746. switch (r)
  2747. {
  2748. case 0:
  2749. switch (c)
  2750. {
  2751. case 0:
  2752. pMat.M11 = val;
  2753. break;
  2754. case 1:
  2755. pMat.M12 = val;
  2756. break;
  2757. case 2:
  2758. pMat.M13 = val;
  2759. break;
  2760. case 3:
  2761. pMat.M14 = val;
  2762. break;
  2763. }
  2764. break;
  2765. case 1:
  2766. switch (c)
  2767. {
  2768. case 0:
  2769. pMat.M21 = val;
  2770. break;
  2771. case 1:
  2772. pMat.M22 = val;
  2773. break;
  2774. case 2:
  2775. pMat.M23 = val;
  2776. break;
  2777. case 3:
  2778. pMat.M24 = val;
  2779. break;
  2780. }
  2781. break;
  2782. case 2:
  2783. switch (c)
  2784. {
  2785. case 0:
  2786. pMat.M31 = val;
  2787. break;
  2788. case 1:
  2789. pMat.M32 = val;
  2790. break;
  2791. case 2:
  2792. pMat.M33 = val;
  2793. break;
  2794. case 3:
  2795. pMat.M34 = val;
  2796. break;
  2797. }
  2798. break;
  2799. case 3:
  2800. switch (c)
  2801. {
  2802. case 0:
  2803. pMat.M41 = val;
  2804. break;
  2805. case 1:
  2806. pMat.M42 = val;
  2807. break;
  2808. case 2:
  2809. pMat.M43 = val;
  2810. break;
  2811. case 3:
  2812. pMat.M44 = val;
  2813. break;
  2814. }
  2815. break;
  2816. }
  2817. }
  2818. private static float determinant3x3(Matrix4 pMat)
  2819. {
  2820. float det = 0;
  2821. float diag1 = pMat[0, 0]*pMat[1, 1]*pMat[2, 2];
  2822. float diag2 = pMat[0, 1]*pMat[2, 1]*pMat[2, 0];
  2823. float diag3 = pMat[0, 2]*pMat[1, 0]*pMat[2, 1];
  2824. float diag4 = pMat[2, 0]*pMat[1, 1]*pMat[0, 2];
  2825. float diag5 = pMat[2, 1]*pMat[1, 2]*pMat[0, 0];
  2826. float diag6 = pMat[2, 2]*pMat[1, 0]*pMat[0, 1];
  2827. det = diag1 + diag2 + diag3 - (diag4 + diag5 + diag6);
  2828. return det;
  2829. }
  2830. private static void DMassCopy(ref d.Mass src, ref d.Mass dst)
  2831. {
  2832. dst.c.W = src.c.W;
  2833. dst.c.X = src.c.X;
  2834. dst.c.Y = src.c.Y;
  2835. dst.c.Z = src.c.Z;
  2836. dst.mass = src.mass;
  2837. dst.I.M00 = src.I.M00;
  2838. dst.I.M01 = src.I.M01;
  2839. dst.I.M02 = src.I.M02;
  2840. dst.I.M10 = src.I.M10;
  2841. dst.I.M11 = src.I.M11;
  2842. dst.I.M12 = src.I.M12;
  2843. dst.I.M20 = src.I.M20;
  2844. dst.I.M21 = src.I.M21;
  2845. dst.I.M22 = src.I.M22;
  2846. }
  2847. public override void SetMaterial(int pMaterial)
  2848. {
  2849. m_material = pMaterial;
  2850. }
  2851. private void CheckMeshAsset()
  2852. {
  2853. if (_pbs.SculptEntry && !m_assetFailed && _pbs.SculptTexture != UUID.Zero)
  2854. {
  2855. m_assetFailed = true;
  2856. Util.FireAndForget(delegate
  2857. {
  2858. RequestAssetDelegate assetProvider = _parent_scene.RequestAssetMethod;
  2859. if (assetProvider != null)
  2860. assetProvider(_pbs.SculptTexture, MeshAssetReceived);
  2861. });
  2862. }
  2863. }
  2864. private void MeshAssetReceived(AssetBase asset)
  2865. {
  2866. if (asset != null && asset.Data != null && asset.Data.Length > 0)
  2867. {
  2868. if (!_pbs.SculptEntry)
  2869. return;
  2870. if (_pbs.SculptTexture.ToString() != asset.ID)
  2871. return;
  2872. _pbs.SculptData = new byte[asset.Data.Length];
  2873. asset.Data.CopyTo(_pbs.SculptData, 0);
  2874. // m_assetFailed = false;
  2875. m_taintshape = true;
  2876. _parent_scene.AddPhysicsActorTaint(this);
  2877. }
  2878. else
  2879. {
  2880. m_log.WarnFormat(
  2881. "[ODE PRIM]: Could not get mesh/sculpt asset {0} for {1} at {2} in {3}",
  2882. _pbs.SculptTexture, Name, _position, _parent_scene.Name);
  2883. }
  2884. }
  2885. }
  2886. }