1
0

ODEPrim.cs 121 KB

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