1
0

ODEPrim.cs 121 KB

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