OdePlugin.cs 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877
  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. //#define USE_DRAWSTUFF
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Runtime.InteropServices;
  32. using System.Threading;
  33. using System.IO;
  34. using System.Diagnostics;
  35. using log4net;
  36. using Nini.Config;
  37. using Ode.NET;
  38. #if USE_DRAWSTUFF
  39. using Drawstuff.NET;
  40. #endif
  41. using OpenSim.Framework;
  42. using OpenSim.Region.Physics.Manager;
  43. using OpenMetaverse;
  44. //using OpenSim.Region.Physics.OdePlugin.Meshing;
  45. namespace OpenSim.Region.Physics.OdePlugin
  46. {
  47. /// <summary>
  48. /// ODE plugin
  49. /// </summary>
  50. public class OdePlugin : IPhysicsPlugin
  51. {
  52. //private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  53. private CollisionLocker ode;
  54. private OdeScene _mScene;
  55. public OdePlugin()
  56. {
  57. ode = new CollisionLocker();
  58. }
  59. public bool Init()
  60. {
  61. return true;
  62. }
  63. public PhysicsScene GetScene(String sceneIdentifier)
  64. {
  65. if (_mScene == null)
  66. {
  67. // Initializing ODE only when a scene is created allows alternative ODE plugins to co-habit (according to
  68. // http://opensimulator.org/mantis/view.php?id=2750).
  69. d.InitODE();
  70. _mScene = new OdeScene(ode, sceneIdentifier);
  71. }
  72. return (_mScene);
  73. }
  74. public string GetName()
  75. {
  76. return ("OpenDynamicsEngine");
  77. }
  78. public void Dispose()
  79. {
  80. }
  81. }
  82. public enum StatusIndicators : int
  83. {
  84. Generic = 0,
  85. Start = 1,
  86. End = 2
  87. }
  88. public struct sCollisionData
  89. {
  90. public uint ColliderLocalId;
  91. public uint CollidedWithLocalId;
  92. public int NumberOfCollisions;
  93. public int CollisionType;
  94. public int StatusIndicator;
  95. public int lastframe;
  96. }
  97. [Flags]
  98. public enum CollisionCategories : int
  99. {
  100. Disabled = 0,
  101. Geom = 0x00000001,
  102. Body = 0x00000002,
  103. Space = 0x00000004,
  104. Character = 0x00000008,
  105. Land = 0x00000010,
  106. Water = 0x00000020,
  107. Wind = 0x00000040,
  108. Sensor = 0x00000080,
  109. Selected = 0x00000100
  110. }
  111. /// <summary>
  112. /// Material type for a primitive
  113. /// </summary>
  114. public enum Material : int
  115. {
  116. /// <summary></summary>
  117. Stone = 0,
  118. /// <summary></summary>
  119. Metal = 1,
  120. /// <summary></summary>
  121. Glass = 2,
  122. /// <summary></summary>
  123. Wood = 3,
  124. /// <summary></summary>
  125. Flesh = 4,
  126. /// <summary></summary>
  127. Plastic = 5,
  128. /// <summary></summary>
  129. Rubber = 6
  130. }
  131. public sealed class OdeScene : PhysicsScene
  132. {
  133. private readonly ILog m_log;
  134. // private Dictionary<string, sCollisionData> m_storedCollisions = new Dictionary<string, sCollisionData>();
  135. CollisionLocker ode;
  136. private Random fluidRandomizer = new Random(Environment.TickCount);
  137. private const uint m_regionWidth = Constants.RegionSize;
  138. private const uint m_regionHeight = Constants.RegionSize;
  139. private float ODE_STEPSIZE = 0.020f;
  140. private float metersInSpace = 29.9f;
  141. private float m_timeDilation = 1.0f;
  142. public float gravityx = 0f;
  143. public float gravityy = 0f;
  144. public float gravityz = -9.8f;
  145. private float contactsurfacelayer = 0.001f;
  146. private int worldHashspaceLow = -4;
  147. private int worldHashspaceHigh = 128;
  148. private int smallHashspaceLow = -4;
  149. private int smallHashspaceHigh = 66;
  150. private float waterlevel = 0f;
  151. private int framecount = 0;
  152. //private int m_returncollisions = 10;
  153. private readonly IntPtr contactgroup;
  154. internal IntPtr LandGeom;
  155. internal IntPtr WaterGeom;
  156. private float nmTerrainContactFriction = 255.0f;
  157. private float nmTerrainContactBounce = 0.1f;
  158. private float nmTerrainContactERP = 0.1025f;
  159. private float mTerrainContactFriction = 75f;
  160. private float mTerrainContactBounce = 0.1f;
  161. private float mTerrainContactERP = 0.05025f;
  162. private float nmAvatarObjectContactFriction = 250f;
  163. private float nmAvatarObjectContactBounce = 0.1f;
  164. private float mAvatarObjectContactFriction = 75f;
  165. private float mAvatarObjectContactBounce = 0.1f;
  166. private float avPIDD = 3200f;
  167. private float avPIDP = 1400f;
  168. private float avCapRadius = 0.37f;
  169. private float avStandupTensor = 2000000f;
  170. private bool avCapsuleTilted = true; // true = old compatibility mode with leaning capsule; false = new corrected mode
  171. public bool IsAvCapsuleTilted { get { return avCapsuleTilted; } set { avCapsuleTilted = value; } }
  172. private float avDensity = 80f;
  173. private float avHeightFudgeFactor = 0.52f;
  174. private float avMovementDivisorWalk = 1.3f;
  175. private float avMovementDivisorRun = 0.8f;
  176. private float minimumGroundFlightOffset = 3f;
  177. public float maximumMassObject = 10000.01f;
  178. public bool meshSculptedPrim = true;
  179. public bool forceSimplePrimMeshing = false;
  180. public float meshSculptLOD = 32;
  181. public float MeshSculptphysicalLOD = 16;
  182. public float geomDefaultDensity = 10.000006836f;
  183. public int geomContactPointsStartthrottle = 3;
  184. public int geomUpdatesPerThrottledUpdate = 15;
  185. public float bodyPIDD = 35f;
  186. public float bodyPIDG = 25;
  187. public int geomCrossingFailuresBeforeOutofbounds = 5;
  188. public float bodyMotorJointMaxforceTensor = 2;
  189. public int bodyFramesAutoDisable = 20;
  190. private float[] _watermap;
  191. private bool m_filterCollisions = true;
  192. private d.NearCallback nearCallback;
  193. public d.TriCallback triCallback;
  194. public d.TriArrayCallback triArrayCallback;
  195. private readonly HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  196. private readonly HashSet<OdePrim> _prims = new HashSet<OdePrim>();
  197. private readonly HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  198. private readonly HashSet<OdePrim> _taintedPrimH = new HashSet<OdePrim>();
  199. private readonly Object _taintedPrimLock = new Object();
  200. private readonly List<OdePrim> _taintedPrimL = new List<OdePrim>();
  201. private readonly HashSet<OdeCharacter> _taintedActors = new HashSet<OdeCharacter>();
  202. private readonly List<d.ContactGeom> _perloopContact = new List<d.ContactGeom>();
  203. private readonly List<PhysicsActor> _collisionEventPrim = new List<PhysicsActor>();
  204. private readonly HashSet<OdeCharacter> _badCharacter = new HashSet<OdeCharacter>();
  205. public Dictionary<IntPtr, String> geom_name_map = new Dictionary<IntPtr, String>();
  206. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  207. private bool m_NINJA_physics_joints_enabled = false;
  208. //private Dictionary<String, IntPtr> jointpart_name_map = new Dictionary<String,IntPtr>();
  209. private readonly Dictionary<String, List<PhysicsJoint>> joints_connecting_actor = new Dictionary<String, List<PhysicsJoint>>();
  210. private d.ContactGeom[] contacts;
  211. private readonly List<PhysicsJoint> requestedJointsToBeCreated = new List<PhysicsJoint>(); // lock only briefly. accessed by external code (to request new joints) and by OdeScene.Simulate() to move those joints into pending/active
  212. private readonly List<PhysicsJoint> pendingJoints = new List<PhysicsJoint>(); // can lock for longer. accessed only by OdeScene.
  213. private readonly List<PhysicsJoint> activeJoints = new List<PhysicsJoint>(); // can lock for longer. accessed only by OdeScene.
  214. private readonly List<string> requestedJointsToBeDeleted = new List<string>(); // lock only briefly. accessed by external code (to request deletion of joints) and by OdeScene.Simulate() to move those joints out of pending/active
  215. private Object externalJointRequestsLock = new Object();
  216. private readonly Dictionary<String, PhysicsJoint> SOPName_to_activeJoint = new Dictionary<String, PhysicsJoint>();
  217. private readonly Dictionary<String, PhysicsJoint> SOPName_to_pendingJoint = new Dictionary<String, PhysicsJoint>();
  218. private readonly DoubleDictionary<Vector3, IntPtr, IntPtr> RegionTerrain = new DoubleDictionary<Vector3, IntPtr, IntPtr>();
  219. private readonly Dictionary<IntPtr,float[]> TerrainHeightFieldHeights = new Dictionary<IntPtr, float[]>();
  220. private d.Contact contact;
  221. private d.Contact TerrainContact;
  222. private d.Contact AvatarMovementprimContact;
  223. private d.Contact AvatarMovementTerrainContact;
  224. private d.Contact WaterContact;
  225. private d.Contact[,] m_materialContacts;
  226. //Ckrinke: Comment out until used. We declare it, initialize it, but do not use it
  227. //Ckrinke private int m_randomizeWater = 200;
  228. private int m_physicsiterations = 10;
  229. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  230. private readonly PhysicsActor PANull = new NullPhysicsActor();
  231. private float step_time = 0.0f;
  232. //Ckrinke: Comment out until used. We declare it, initialize it, but do not use it
  233. //Ckrinke private int ms = 0;
  234. public IntPtr world;
  235. //private bool returncollisions = false;
  236. // private uint obj1LocalID = 0;
  237. private uint obj2LocalID = 0;
  238. //private int ctype = 0;
  239. private OdeCharacter cc1;
  240. private OdePrim cp1;
  241. private OdeCharacter cc2;
  242. private OdePrim cp2;
  243. //private int cStartStop = 0;
  244. //private string cDictKey = "";
  245. public IntPtr space;
  246. //private IntPtr tmpSpace;
  247. // split static geometry collision handling into spaces of 30 meters
  248. public IntPtr[,] staticPrimspace;
  249. public Object OdeLock;
  250. public IMesher mesher;
  251. private IConfigSource m_config;
  252. public bool physics_logging = false;
  253. public int physics_logging_interval = 0;
  254. public bool physics_logging_append_existing_logfile = false;
  255. public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f);
  256. public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f);
  257. // TODO: unused: private uint heightmapWidth = m_regionWidth + 1;
  258. // TODO: unused: private uint heightmapHeight = m_regionHeight + 1;
  259. // TODO: unused: private uint heightmapWidthSamples;
  260. // TODO: unused: private uint heightmapHeightSamples;
  261. private volatile int m_global_contactcount = 0;
  262. private Vector3 m_worldOffset = Vector3.Zero;
  263. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  264. private PhysicsScene m_parentScene = null;
  265. private ODERayCastRequestManager m_rayCastManager;
  266. /// <summary>
  267. /// Initiailizes the scene
  268. /// Sets many properties that ODE requires to be stable
  269. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  270. /// </summary>
  271. public OdeScene(CollisionLocker dode, string sceneIdentifier)
  272. {
  273. m_log
  274. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.ToString() + "." + sceneIdentifier);
  275. OdeLock = new Object();
  276. ode = dode;
  277. nearCallback = near;
  278. triCallback = TriCallback;
  279. triArrayCallback = TriArrayCallback;
  280. m_rayCastManager = new ODERayCastRequestManager(this);
  281. lock (OdeLock)
  282. {
  283. // Create the world and the first space
  284. world = d.WorldCreate();
  285. space = d.HashSpaceCreate(IntPtr.Zero);
  286. contactgroup = d.JointGroupCreate(0);
  287. //contactgroup
  288. d.WorldSetAutoDisableFlag(world, false);
  289. #if USE_DRAWSTUFF
  290. Thread viewthread = new Thread(new ParameterizedThreadStart(startvisualization));
  291. viewthread.Start();
  292. #endif
  293. }
  294. _watermap = new float[258 * 258];
  295. // Zero out the prim spaces array (we split our space into smaller spaces so
  296. // we can hit test less.
  297. }
  298. #if USE_DRAWSTUFF
  299. public void startvisualization(object o)
  300. {
  301. ds.Functions fn;
  302. fn.version = ds.VERSION;
  303. fn.start = new ds.CallbackFunction(start);
  304. fn.step = new ds.CallbackFunction(step);
  305. fn.command = new ds.CallbackFunction(command);
  306. fn.stop = null;
  307. fn.path_to_textures = "./textures";
  308. string[] args = new string[0];
  309. ds.SimulationLoop(args.Length, args, 352, 288, ref fn);
  310. }
  311. #endif
  312. // Initialize the mesh plugin
  313. public override void Initialise(IMesher meshmerizer, IConfigSource config)
  314. {
  315. mesher = meshmerizer;
  316. m_config = config;
  317. // Defaults
  318. if (Environment.OSVersion.Platform == PlatformID.Unix)
  319. {
  320. avPIDD = 3200.0f;
  321. avPIDP = 1400.0f;
  322. avStandupTensor = 2000000f;
  323. }
  324. else
  325. {
  326. avPIDD = 2200.0f;
  327. avPIDP = 900.0f;
  328. avStandupTensor = 550000f;
  329. }
  330. int contactsPerCollision = 80;
  331. if (m_config != null)
  332. {
  333. IConfig physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  334. if (physicsconfig != null)
  335. {
  336. gravityx = physicsconfig.GetFloat("world_gravityx", 0f);
  337. gravityy = physicsconfig.GetFloat("world_gravityy", 0f);
  338. gravityz = physicsconfig.GetFloat("world_gravityz", -9.8f);
  339. worldHashspaceLow = physicsconfig.GetInt("world_hashspace_size_low", -4);
  340. worldHashspaceHigh = physicsconfig.GetInt("world_hashspace_size_high", 128);
  341. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", 29.9f);
  342. smallHashspaceLow = physicsconfig.GetInt("small_hashspace_size_low", -4);
  343. smallHashspaceHigh = physicsconfig.GetInt("small_hashspace_size_high", 66);
  344. contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", 0.001f);
  345. nmTerrainContactFriction = physicsconfig.GetFloat("nm_terraincontact_friction", 255.0f);
  346. nmTerrainContactBounce = physicsconfig.GetFloat("nm_terraincontact_bounce", 0.1f);
  347. nmTerrainContactERP = physicsconfig.GetFloat("nm_terraincontact_erp", 0.1025f);
  348. mTerrainContactFriction = physicsconfig.GetFloat("m_terraincontact_friction", 75f);
  349. mTerrainContactBounce = physicsconfig.GetFloat("m_terraincontact_bounce", 0.05f);
  350. mTerrainContactERP = physicsconfig.GetFloat("m_terraincontact_erp", 0.05025f);
  351. nmAvatarObjectContactFriction = physicsconfig.GetFloat("objectcontact_friction", 250f);
  352. nmAvatarObjectContactBounce = physicsconfig.GetFloat("objectcontact_bounce", 0.2f);
  353. mAvatarObjectContactFriction = physicsconfig.GetFloat("m_avatarobjectcontact_friction", 75f);
  354. mAvatarObjectContactBounce = physicsconfig.GetFloat("m_avatarobjectcontact_bounce", 0.1f);
  355. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", 0.020f);
  356. m_physicsiterations = physicsconfig.GetInt("world_internal_steps_without_collisions", 10);
  357. avDensity = physicsconfig.GetFloat("av_density", 80f);
  358. avHeightFudgeFactor = physicsconfig.GetFloat("av_height_fudge_factor", 0.52f);
  359. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f);
  360. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f);
  361. avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f);
  362. avCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false);
  363. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80);
  364. geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 3);
  365. geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15);
  366. geomCrossingFailuresBeforeOutofbounds = physicsconfig.GetInt("geom_crossing_failures_before_outofbounds", 5);
  367. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", 10.000006836f);
  368. bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", 20);
  369. bodyPIDD = physicsconfig.GetFloat("body_pid_derivative", 35f);
  370. bodyPIDG = physicsconfig.GetFloat("body_pid_gain", 25f);
  371. forceSimplePrimMeshing = physicsconfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
  372. meshSculptedPrim = physicsconfig.GetBoolean("mesh_sculpted_prim", true);
  373. meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f);
  374. MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f);
  375. m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false);
  376. if (Environment.OSVersion.Platform == PlatformID.Unix)
  377. {
  378. avPIDD = physicsconfig.GetFloat("av_pid_derivative_linux", 2200.0f);
  379. avPIDP = physicsconfig.GetFloat("av_pid_proportional_linux", 900.0f);
  380. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor_linux", 550000f);
  381. bodyMotorJointMaxforceTensor = physicsconfig.GetFloat("body_motor_joint_maxforce_tensor_linux", 5f);
  382. }
  383. else
  384. {
  385. avPIDD = physicsconfig.GetFloat("av_pid_derivative_win", 2200.0f);
  386. avPIDP = physicsconfig.GetFloat("av_pid_proportional_win", 900.0f);
  387. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor_win", 550000f);
  388. bodyMotorJointMaxforceTensor = physicsconfig.GetFloat("body_motor_joint_maxforce_tensor_win", 5f);
  389. }
  390. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  391. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  392. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  393. m_NINJA_physics_joints_enabled = physicsconfig.GetBoolean("use_NINJA_physics_joints", false);
  394. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", 3f);
  395. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", 10000.01f);
  396. }
  397. }
  398. contacts = new d.ContactGeom[contactsPerCollision];
  399. staticPrimspace = new IntPtr[(int)(300 / metersInSpace), (int)(300 / metersInSpace)];
  400. // Centeral contact friction and bounce
  401. // ckrinke 11/10/08 Enabling soft_erp but not soft_cfm until I figure out why
  402. // an avatar falls through in Z but not in X or Y when walking on a prim.
  403. contact.surface.mode |= d.ContactFlags.SoftERP;
  404. contact.surface.mu = nmAvatarObjectContactFriction;
  405. contact.surface.bounce = nmAvatarObjectContactBounce;
  406. contact.surface.soft_cfm = 0.010f;
  407. contact.surface.soft_erp = 0.010f;
  408. // Terrain contact friction and Bounce
  409. // This is the *non* moving version. Use this when an avatar
  410. // isn't moving to keep it in place better
  411. TerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  412. TerrainContact.surface.mu = nmTerrainContactFriction;
  413. TerrainContact.surface.bounce = nmTerrainContactBounce;
  414. TerrainContact.surface.soft_erp = nmTerrainContactERP;
  415. WaterContact.surface.mode |= (d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM);
  416. WaterContact.surface.mu = 0f; // No friction
  417. WaterContact.surface.bounce = 0.0f; // No bounce
  418. WaterContact.surface.soft_cfm = 0.010f;
  419. WaterContact.surface.soft_erp = 0.010f;
  420. // Prim contact friction and bounce
  421. // THis is the *non* moving version of friction and bounce
  422. // Use this when an avatar comes in contact with a prim
  423. // and is moving
  424. AvatarMovementprimContact.surface.mu = mAvatarObjectContactFriction;
  425. AvatarMovementprimContact.surface.bounce = mAvatarObjectContactBounce;
  426. // Terrain contact friction bounce and various error correcting calculations
  427. // Use this when an avatar is in contact with the terrain and moving.
  428. AvatarMovementTerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  429. AvatarMovementTerrainContact.surface.mu = mTerrainContactFriction;
  430. AvatarMovementTerrainContact.surface.bounce = mTerrainContactBounce;
  431. AvatarMovementTerrainContact.surface.soft_erp = mTerrainContactERP;
  432. /*
  433. <summary></summary>
  434. Stone = 0,
  435. /// <summary></summary>
  436. Metal = 1,
  437. /// <summary></summary>
  438. Glass = 2,
  439. /// <summary></summary>
  440. Wood = 3,
  441. /// <summary></summary>
  442. Flesh = 4,
  443. /// <summary></summary>
  444. Plastic = 5,
  445. /// <summary></summary>
  446. Rubber = 6
  447. */
  448. m_materialContacts = new d.Contact[7,2];
  449. m_materialContacts[(int)Material.Stone, 0] = new d.Contact();
  450. m_materialContacts[(int)Material.Stone, 0].surface.mode |= d.ContactFlags.SoftERP;
  451. m_materialContacts[(int)Material.Stone, 0].surface.mu = nmAvatarObjectContactFriction;
  452. m_materialContacts[(int)Material.Stone, 0].surface.bounce = nmAvatarObjectContactBounce;
  453. m_materialContacts[(int)Material.Stone, 0].surface.soft_cfm = 0.010f;
  454. m_materialContacts[(int)Material.Stone, 0].surface.soft_erp = 0.010f;
  455. m_materialContacts[(int)Material.Stone, 1] = new d.Contact();
  456. m_materialContacts[(int)Material.Stone, 1].surface.mode |= d.ContactFlags.SoftERP;
  457. m_materialContacts[(int)Material.Stone, 1].surface.mu = mAvatarObjectContactFriction;
  458. m_materialContacts[(int)Material.Stone, 1].surface.bounce = mAvatarObjectContactBounce;
  459. m_materialContacts[(int)Material.Stone, 1].surface.soft_cfm = 0.010f;
  460. m_materialContacts[(int)Material.Stone, 1].surface.soft_erp = 0.010f;
  461. m_materialContacts[(int)Material.Metal, 0] = new d.Contact();
  462. m_materialContacts[(int)Material.Metal, 0].surface.mode |= d.ContactFlags.SoftERP;
  463. m_materialContacts[(int)Material.Metal, 0].surface.mu = nmAvatarObjectContactFriction;
  464. m_materialContacts[(int)Material.Metal, 0].surface.bounce = nmAvatarObjectContactBounce;
  465. m_materialContacts[(int)Material.Metal, 0].surface.soft_cfm = 0.010f;
  466. m_materialContacts[(int)Material.Metal, 0].surface.soft_erp = 0.010f;
  467. m_materialContacts[(int)Material.Metal, 1] = new d.Contact();
  468. m_materialContacts[(int)Material.Metal, 1].surface.mode |= d.ContactFlags.SoftERP;
  469. m_materialContacts[(int)Material.Metal, 1].surface.mu = mAvatarObjectContactFriction;
  470. m_materialContacts[(int)Material.Metal, 1].surface.bounce = mAvatarObjectContactBounce;
  471. m_materialContacts[(int)Material.Metal, 1].surface.soft_cfm = 0.010f;
  472. m_materialContacts[(int)Material.Metal, 1].surface.soft_erp = 0.010f;
  473. m_materialContacts[(int)Material.Glass, 0] = new d.Contact();
  474. m_materialContacts[(int)Material.Glass, 0].surface.mode |= d.ContactFlags.SoftERP;
  475. m_materialContacts[(int)Material.Glass, 0].surface.mu = 1f;
  476. m_materialContacts[(int)Material.Glass, 0].surface.bounce = 0.5f;
  477. m_materialContacts[(int)Material.Glass, 0].surface.soft_cfm = 0.010f;
  478. m_materialContacts[(int)Material.Glass, 0].surface.soft_erp = 0.010f;
  479. /*
  480. private float nmAvatarObjectContactFriction = 250f;
  481. private float nmAvatarObjectContactBounce = 0.1f;
  482. private float mAvatarObjectContactFriction = 75f;
  483. private float mAvatarObjectContactBounce = 0.1f;
  484. */
  485. m_materialContacts[(int)Material.Glass, 1] = new d.Contact();
  486. m_materialContacts[(int)Material.Glass, 1].surface.mode |= d.ContactFlags.SoftERP;
  487. m_materialContacts[(int)Material.Glass, 1].surface.mu = 1f;
  488. m_materialContacts[(int)Material.Glass, 1].surface.bounce = 0.5f;
  489. m_materialContacts[(int)Material.Glass, 1].surface.soft_cfm = 0.010f;
  490. m_materialContacts[(int)Material.Glass, 1].surface.soft_erp = 0.010f;
  491. m_materialContacts[(int)Material.Wood, 0] = new d.Contact();
  492. m_materialContacts[(int)Material.Wood, 0].surface.mode |= d.ContactFlags.SoftERP;
  493. m_materialContacts[(int)Material.Wood, 0].surface.mu = nmAvatarObjectContactFriction;
  494. m_materialContacts[(int)Material.Wood, 0].surface.bounce = nmAvatarObjectContactBounce;
  495. m_materialContacts[(int)Material.Wood, 0].surface.soft_cfm = 0.010f;
  496. m_materialContacts[(int)Material.Wood, 0].surface.soft_erp = 0.010f;
  497. m_materialContacts[(int)Material.Wood, 1] = new d.Contact();
  498. m_materialContacts[(int)Material.Wood, 1].surface.mode |= d.ContactFlags.SoftERP;
  499. m_materialContacts[(int)Material.Wood, 1].surface.mu = mAvatarObjectContactFriction;
  500. m_materialContacts[(int)Material.Wood, 1].surface.bounce = mAvatarObjectContactBounce;
  501. m_materialContacts[(int)Material.Wood, 1].surface.soft_cfm = 0.010f;
  502. m_materialContacts[(int)Material.Wood, 1].surface.soft_erp = 0.010f;
  503. m_materialContacts[(int)Material.Flesh, 0] = new d.Contact();
  504. m_materialContacts[(int)Material.Flesh, 0].surface.mode |= d.ContactFlags.SoftERP;
  505. m_materialContacts[(int)Material.Flesh, 0].surface.mu = nmAvatarObjectContactFriction;
  506. m_materialContacts[(int)Material.Flesh, 0].surface.bounce = nmAvatarObjectContactBounce;
  507. m_materialContacts[(int)Material.Flesh, 0].surface.soft_cfm = 0.010f;
  508. m_materialContacts[(int)Material.Flesh, 0].surface.soft_erp = 0.010f;
  509. m_materialContacts[(int)Material.Flesh, 1] = new d.Contact();
  510. m_materialContacts[(int)Material.Flesh, 1].surface.mode |= d.ContactFlags.SoftERP;
  511. m_materialContacts[(int)Material.Flesh, 1].surface.mu = mAvatarObjectContactFriction;
  512. m_materialContacts[(int)Material.Flesh, 1].surface.bounce = mAvatarObjectContactBounce;
  513. m_materialContacts[(int)Material.Flesh, 1].surface.soft_cfm = 0.010f;
  514. m_materialContacts[(int)Material.Flesh, 1].surface.soft_erp = 0.010f;
  515. m_materialContacts[(int)Material.Plastic, 0] = new d.Contact();
  516. m_materialContacts[(int)Material.Plastic, 0].surface.mode |= d.ContactFlags.SoftERP;
  517. m_materialContacts[(int)Material.Plastic, 0].surface.mu = nmAvatarObjectContactFriction;
  518. m_materialContacts[(int)Material.Plastic, 0].surface.bounce = nmAvatarObjectContactBounce;
  519. m_materialContacts[(int)Material.Plastic, 0].surface.soft_cfm = 0.010f;
  520. m_materialContacts[(int)Material.Plastic, 0].surface.soft_erp = 0.010f;
  521. m_materialContacts[(int)Material.Plastic, 1] = new d.Contact();
  522. m_materialContacts[(int)Material.Plastic, 1].surface.mode |= d.ContactFlags.SoftERP;
  523. m_materialContacts[(int)Material.Plastic, 1].surface.mu = mAvatarObjectContactFriction;
  524. m_materialContacts[(int)Material.Plastic, 1].surface.bounce = mAvatarObjectContactBounce;
  525. m_materialContacts[(int)Material.Plastic, 1].surface.soft_cfm = 0.010f;
  526. m_materialContacts[(int)Material.Plastic, 1].surface.soft_erp = 0.010f;
  527. m_materialContacts[(int)Material.Rubber, 0] = new d.Contact();
  528. m_materialContacts[(int)Material.Rubber, 0].surface.mode |= d.ContactFlags.SoftERP;
  529. m_materialContacts[(int)Material.Rubber, 0].surface.mu = nmAvatarObjectContactFriction;
  530. m_materialContacts[(int)Material.Rubber, 0].surface.bounce = nmAvatarObjectContactBounce;
  531. m_materialContacts[(int)Material.Rubber, 0].surface.soft_cfm = 0.010f;
  532. m_materialContacts[(int)Material.Rubber, 0].surface.soft_erp = 0.010f;
  533. m_materialContacts[(int)Material.Rubber, 1] = new d.Contact();
  534. m_materialContacts[(int)Material.Rubber, 1].surface.mode |= d.ContactFlags.SoftERP;
  535. m_materialContacts[(int)Material.Rubber, 1].surface.mu = mAvatarObjectContactFriction;
  536. m_materialContacts[(int)Material.Rubber, 1].surface.bounce = mAvatarObjectContactBounce;
  537. m_materialContacts[(int)Material.Rubber, 1].surface.soft_cfm = 0.010f;
  538. m_materialContacts[(int)Material.Rubber, 1].surface.soft_erp = 0.010f;
  539. d.HashSpaceSetLevels(space, worldHashspaceLow, worldHashspaceHigh);
  540. // Set the gravity,, don't disable things automatically (we set it explicitly on some things)
  541. d.WorldSetGravity(world, gravityx, gravityy, gravityz);
  542. d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  543. d.WorldSetLinearDamping(world, 256f);
  544. d.WorldSetAngularDamping(world, 256f);
  545. d.WorldSetAngularDampingThreshold(world, 256f);
  546. d.WorldSetLinearDampingThreshold(world, 256f);
  547. d.WorldSetMaxAngularSpeed(world, 256f);
  548. // Set how many steps we go without running collision testing
  549. // This is in addition to the step size.
  550. // Essentially Steps * m_physicsiterations
  551. d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  552. //d.WorldSetContactMaxCorrectingVel(world, 1000.0f);
  553. for (int i = 0; i < staticPrimspace.GetLength(0); i++)
  554. {
  555. for (int j = 0; j < staticPrimspace.GetLength(1); j++)
  556. {
  557. staticPrimspace[i, j] = IntPtr.Zero;
  558. }
  559. }
  560. }
  561. internal void waitForSpaceUnlock(IntPtr space)
  562. {
  563. //if (space != IntPtr.Zero)
  564. //while (d.SpaceLockQuery(space)) { } // Wait and do nothing
  565. }
  566. /// <summary>
  567. /// Debug space message for printing the space that a prim/avatar is in.
  568. /// </summary>
  569. /// <param name="pos"></param>
  570. /// <returns>Returns which split up space the given position is in.</returns>
  571. public string whichspaceamIin(Vector3 pos)
  572. {
  573. return calculateSpaceForGeom(pos).ToString();
  574. }
  575. #region Collision Detection
  576. /// <summary>
  577. /// This is our near callback. A geometry is near a body
  578. /// </summary>
  579. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  580. /// <param name="g1">a geometry or space</param>
  581. /// <param name="g2">another geometry or space</param>
  582. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  583. {
  584. // no lock here! It's invoked from within Simulate(), which is thread-locked
  585. // Test if we're colliding a geom with a space.
  586. // If so we have to drill down into the space recursively
  587. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  588. {
  589. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  590. return;
  591. // Separating static prim geometry spaces.
  592. // We'll be calling near recursivly if one
  593. // of them is a space to find all of the
  594. // contact points in the space
  595. try
  596. {
  597. d.SpaceCollide2(g1, g2, IntPtr.Zero, nearCallback);
  598. }
  599. catch (AccessViolationException)
  600. {
  601. m_log.Warn("[PHYSICS]: Unable to collide test a space");
  602. return;
  603. }
  604. //Colliding a space or a geom with a space or a geom. so drill down
  605. //Collide all geoms in each space..
  606. //if (d.GeomIsSpace(g1)) d.SpaceCollide(g1, IntPtr.Zero, nearCallback);
  607. //if (d.GeomIsSpace(g2)) d.SpaceCollide(g2, IntPtr.Zero, nearCallback);
  608. return;
  609. }
  610. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  611. return;
  612. IntPtr b1 = d.GeomGetBody(g1);
  613. IntPtr b2 = d.GeomGetBody(g2);
  614. // d.GeomClassID id = d.GeomGetClass(g1);
  615. String name1 = null;
  616. String name2 = null;
  617. if (!geom_name_map.TryGetValue(g1, out name1))
  618. {
  619. name1 = "null";
  620. }
  621. if (!geom_name_map.TryGetValue(g2, out name2))
  622. {
  623. name2 = "null";
  624. }
  625. //if (id == d.GeomClassId.TriMeshClass)
  626. //{
  627. // m_log.InfoFormat("near: A collision was detected between {1} and {2}", 0, name1, name2);
  628. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  629. //}
  630. // Figure out how many contact points we have
  631. int count = 0;
  632. try
  633. {
  634. // Colliding Geom To Geom
  635. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  636. if (g1 == g2)
  637. return; // Can't collide with yourself
  638. if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
  639. return;
  640. lock (contacts)
  641. {
  642. count = d.Collide(g1, g2, contacts.Length, contacts, d.ContactGeom.SizeOf);
  643. if (count > contacts.Length)
  644. m_log.Error("[PHYSICS]: Got " + count + " contacts when we asked for a maximum of " + contacts.Length);
  645. }
  646. }
  647. catch (SEHException)
  648. {
  649. m_log.Error("[PHYSICS]: The Operating system shut down ODE because of corrupt memory. This could be a result of really irregular terrain. If this repeats continuously, restart using Basic Physics and terrain fill your terrain. Restarting the sim.");
  650. ode.drelease(world);
  651. base.TriggerPhysicsBasedRestart();
  652. }
  653. catch (Exception e)
  654. {
  655. m_log.WarnFormat("[PHYSICS]: Unable to collide test an object: {0}", e.Message);
  656. return;
  657. }
  658. PhysicsActor p1;
  659. PhysicsActor p2;
  660. if (!actor_name_map.TryGetValue(g1, out p1))
  661. {
  662. p1 = PANull;
  663. }
  664. if (!actor_name_map.TryGetValue(g2, out p2))
  665. {
  666. p2 = PANull;
  667. }
  668. ContactPoint maxDepthContact = new ContactPoint();
  669. if (p1.CollisionScore + count >= float.MaxValue)
  670. p1.CollisionScore = 0;
  671. p1.CollisionScore += count;
  672. if (p2.CollisionScore + count >= float.MaxValue)
  673. p2.CollisionScore = 0;
  674. p2.CollisionScore += count;
  675. for (int i = 0; i < count; i++)
  676. {
  677. d.ContactGeom curContact = contacts[i];
  678. if (curContact.depth > maxDepthContact.PenetrationDepth)
  679. {
  680. maxDepthContact = new ContactPoint(
  681. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  682. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  683. curContact.depth
  684. );
  685. }
  686. //m_log.Warn("[CCOUNT]: " + count);
  687. IntPtr joint;
  688. // If we're colliding with terrain, use 'TerrainContact' instead of contact.
  689. // allows us to have different settings
  690. // We only need to test p2 for 'jump crouch purposes'
  691. if (p2 is OdeCharacter && p1.PhysicsActorType == (int)ActorTypes.Prim)
  692. {
  693. // Testing if the collision is at the feet of the avatar
  694. //m_log.DebugFormat("[PHYSICS]: {0} - {1} - {2} - {3}", curContact.pos.Z, p2.Position.Z, (p2.Position.Z - curContact.pos.Z), (p2.Size.Z * 0.6f));
  695. if ((p2.Position.Z - curContact.pos.Z) > (p2.Size.Z * 0.6f))
  696. p2.IsColliding = true;
  697. }
  698. else
  699. {
  700. p2.IsColliding = true;
  701. }
  702. //if ((framecount % m_returncollisions) == 0)
  703. switch (p1.PhysicsActorType)
  704. {
  705. case (int)ActorTypes.Agent:
  706. p2.CollidingObj = true;
  707. break;
  708. case (int)ActorTypes.Prim:
  709. if (p2.Velocity.LengthSquared() > 0.0f)
  710. p2.CollidingObj = true;
  711. break;
  712. case (int)ActorTypes.Unknown:
  713. p2.CollidingGround = true;
  714. break;
  715. default:
  716. p2.CollidingGround = true;
  717. break;
  718. }
  719. // we don't want prim or avatar to explode
  720. #region InterPenetration Handling - Unintended physics explosions
  721. # region disabled code1
  722. if (curContact.depth >= 0.08f)
  723. {
  724. //This is disabled at the moment only because it needs more tweaking
  725. //It will eventually be uncommented
  726. /*
  727. if (contact.depth >= 1.00f)
  728. {
  729. //m_log.Debug("[PHYSICS]: " + contact.depth.ToString());
  730. }
  731. //If you interpenetrate a prim with an agent
  732. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  733. p1.PhysicsActorType == (int) ActorTypes.Prim) ||
  734. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  735. p2.PhysicsActorType == (int) ActorTypes.Prim))
  736. {
  737. //contact.depth = contact.depth * 4.15f;
  738. /*
  739. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  740. {
  741. p2.CollidingObj = true;
  742. contact.depth = 0.003f;
  743. p2.Velocity = p2.Velocity + new PhysicsVector(0, 0, 2.5f);
  744. OdeCharacter character = (OdeCharacter) p2;
  745. character.SetPidStatus(true);
  746. contact.pos = new d.Vector3(contact.pos.X + (p1.Size.X / 2), contact.pos.Y + (p1.Size.Y / 2), contact.pos.Z + (p1.Size.Z / 2));
  747. }
  748. else
  749. {
  750. //contact.depth = 0.0000000f;
  751. }
  752. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  753. {
  754. p1.CollidingObj = true;
  755. contact.depth = 0.003f;
  756. p1.Velocity = p1.Velocity + new PhysicsVector(0, 0, 2.5f);
  757. contact.pos = new d.Vector3(contact.pos.X + (p2.Size.X / 2), contact.pos.Y + (p2.Size.Y / 2), contact.pos.Z + (p2.Size.Z / 2));
  758. OdeCharacter character = (OdeCharacter)p1;
  759. character.SetPidStatus(true);
  760. }
  761. else
  762. {
  763. //contact.depth = 0.0000000f;
  764. }
  765. }
  766. */
  767. // If you interpenetrate a prim with another prim
  768. /*
  769. if (p1.PhysicsActorType == (int) ActorTypes.Prim && p2.PhysicsActorType == (int) ActorTypes.Prim)
  770. {
  771. #region disabledcode2
  772. //OdePrim op1 = (OdePrim)p1;
  773. //OdePrim op2 = (OdePrim)p2;
  774. //op1.m_collisionscore++;
  775. //op2.m_collisionscore++;
  776. //if (op1.m_collisionscore > 8000 || op2.m_collisionscore > 8000)
  777. //{
  778. //op1.m_taintdisable = true;
  779. //AddPhysicsActorTaint(p1);
  780. //op2.m_taintdisable = true;
  781. //AddPhysicsActorTaint(p2);
  782. //}
  783. //if (contact.depth >= 0.25f)
  784. //{
  785. // Don't collide, one or both prim will expld.
  786. //op1.m_interpenetrationcount++;
  787. //op2.m_interpenetrationcount++;
  788. //interpenetrations_before_disable = 200;
  789. //if (op1.m_interpenetrationcount >= interpenetrations_before_disable)
  790. //{
  791. //op1.m_taintdisable = true;
  792. //AddPhysicsActorTaint(p1);
  793. //}
  794. //if (op2.m_interpenetrationcount >= interpenetrations_before_disable)
  795. //{
  796. // op2.m_taintdisable = true;
  797. //AddPhysicsActorTaint(p2);
  798. //}
  799. //contact.depth = contact.depth / 8f;
  800. //contact.normal = new d.Vector3(0, 0, 1);
  801. //}
  802. //if (op1.m_disabled || op2.m_disabled)
  803. //{
  804. //Manually disabled objects stay disabled
  805. //contact.depth = 0f;
  806. //}
  807. #endregion
  808. }
  809. */
  810. #endregion
  811. if (curContact.depth >= 1.00f)
  812. {
  813. //m_log.Info("[P]: " + contact.depth.ToString());
  814. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  815. p1.PhysicsActorType == (int) ActorTypes.Unknown) ||
  816. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  817. p2.PhysicsActorType == (int) ActorTypes.Unknown))
  818. {
  819. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  820. {
  821. if (p2 is OdeCharacter)
  822. {
  823. OdeCharacter character = (OdeCharacter) p2;
  824. //p2.CollidingObj = true;
  825. curContact.depth = 0.00000003f;
  826. p2.Velocity = p2.Velocity + new Vector3(0f, 0f, 0.5f);
  827. curContact.pos =
  828. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  829. curContact.pos.Y + (p1.Size.Y/2),
  830. curContact.pos.Z + (p1.Size.Z/2));
  831. character.SetPidStatus(true);
  832. }
  833. }
  834. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  835. {
  836. if (p1 is OdeCharacter)
  837. {
  838. OdeCharacter character = (OdeCharacter) p1;
  839. //p2.CollidingObj = true;
  840. curContact.depth = 0.00000003f;
  841. p1.Velocity = p1.Velocity + new Vector3(0f, 0f, 0.5f);
  842. curContact.pos =
  843. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  844. curContact.pos.Y + (p1.Size.Y/2),
  845. curContact.pos.Z + (p1.Size.Z/2));
  846. character.SetPidStatus(true);
  847. }
  848. }
  849. }
  850. }
  851. }
  852. #endregion
  853. // Logic for collision handling
  854. // Note, that if *all* contacts are skipped (VolumeDetect)
  855. // The prim still detects (and forwards) collision events but
  856. // appears to be phantom for the world
  857. Boolean skipThisContact = false;
  858. if ((p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect))
  859. skipThisContact = true; // No collision on volume detect prims
  860. if (!skipThisContact && (p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect))
  861. skipThisContact = true; // No collision on volume detect prims
  862. if (!skipThisContact && curContact.depth < 0f)
  863. skipThisContact = true;
  864. if (!skipThisContact && checkDupe(curContact, p2.PhysicsActorType))
  865. skipThisContact = true;
  866. const int maxContactsbeforedeath = 4000;
  867. joint = IntPtr.Zero;
  868. if (!skipThisContact)
  869. {
  870. // If we're colliding against terrain
  871. if (name1 == "Terrain" || name2 == "Terrain")
  872. {
  873. // If we're moving
  874. if ((p2.PhysicsActorType == (int) ActorTypes.Agent) &&
  875. (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  876. {
  877. // Use the movement terrain contact
  878. AvatarMovementTerrainContact.geom = curContact;
  879. _perloopContact.Add(curContact);
  880. if (m_global_contactcount < maxContactsbeforedeath)
  881. {
  882. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementTerrainContact);
  883. m_global_contactcount++;
  884. }
  885. }
  886. else
  887. {
  888. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  889. {
  890. // Use the non moving terrain contact
  891. TerrainContact.geom = curContact;
  892. _perloopContact.Add(curContact);
  893. if (m_global_contactcount < maxContactsbeforedeath)
  894. {
  895. joint = d.JointCreateContact(world, contactgroup, ref TerrainContact);
  896. m_global_contactcount++;
  897. }
  898. }
  899. else
  900. {
  901. if (p2.PhysicsActorType == (int)ActorTypes.Prim && p1.PhysicsActorType == (int)ActorTypes.Prim)
  902. {
  903. // prim prim contact
  904. // int pj294950 = 0;
  905. int movintYN = 0;
  906. int material = (int) Material.Wood;
  907. // prim terrain contact
  908. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  909. {
  910. movintYN = 1;
  911. }
  912. if (p2 is OdePrim)
  913. material = ((OdePrim)p2).m_material;
  914. //m_log.DebugFormat("Material: {0}", material);
  915. m_materialContacts[material, movintYN].geom = curContact;
  916. _perloopContact.Add(curContact);
  917. if (m_global_contactcount < maxContactsbeforedeath)
  918. {
  919. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  920. m_global_contactcount++;
  921. }
  922. }
  923. else
  924. {
  925. int movintYN = 0;
  926. // prim terrain contact
  927. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  928. {
  929. movintYN = 1;
  930. }
  931. int material = (int)Material.Wood;
  932. if (p2 is OdePrim)
  933. material = ((OdePrim)p2).m_material;
  934. //m_log.DebugFormat("Material: {0}", material);
  935. m_materialContacts[material, movintYN].geom = curContact;
  936. _perloopContact.Add(curContact);
  937. if (m_global_contactcount < maxContactsbeforedeath)
  938. {
  939. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  940. m_global_contactcount++;
  941. }
  942. }
  943. }
  944. }
  945. //if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  946. //{
  947. //m_log.Debug("[PHYSICS]: prim contacting with ground");
  948. //}
  949. }
  950. else if (name1 == "Water" || name2 == "Water")
  951. {
  952. /*
  953. if ((p2.PhysicsActorType == (int) ActorTypes.Prim))
  954. {
  955. }
  956. else
  957. {
  958. }
  959. */
  960. //WaterContact.surface.soft_cfm = 0.0000f;
  961. //WaterContact.surface.soft_erp = 0.00000f;
  962. if (curContact.depth > 0.1f)
  963. {
  964. curContact.depth *= 52;
  965. //contact.normal = new d.Vector3(0, 0, 1);
  966. //contact.pos = new d.Vector3(0, 0, contact.pos.Z - 5f);
  967. }
  968. WaterContact.geom = curContact;
  969. _perloopContact.Add(curContact);
  970. if (m_global_contactcount < maxContactsbeforedeath)
  971. {
  972. joint = d.JointCreateContact(world, contactgroup, ref WaterContact);
  973. m_global_contactcount++;
  974. }
  975. //m_log.Info("[PHYSICS]: Prim Water Contact" + contact.depth);
  976. }
  977. else
  978. {
  979. // we're colliding with prim or avatar
  980. // check if we're moving
  981. if ((p2.PhysicsActorType == (int)ActorTypes.Agent))
  982. {
  983. if ((Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  984. {
  985. // Use the Movement prim contact
  986. AvatarMovementprimContact.geom = curContact;
  987. _perloopContact.Add(curContact);
  988. if (m_global_contactcount < maxContactsbeforedeath)
  989. {
  990. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementprimContact);
  991. m_global_contactcount++;
  992. }
  993. }
  994. else
  995. {
  996. // Use the non movement contact
  997. contact.geom = curContact;
  998. _perloopContact.Add(curContact);
  999. if (m_global_contactcount < maxContactsbeforedeath)
  1000. {
  1001. joint = d.JointCreateContact(world, contactgroup, ref contact);
  1002. m_global_contactcount++;
  1003. }
  1004. }
  1005. }
  1006. else if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1007. {
  1008. //p1.PhysicsActorType
  1009. int material = (int)Material.Wood;
  1010. if (p2 is OdePrim)
  1011. material = ((OdePrim)p2).m_material;
  1012. //m_log.DebugFormat("Material: {0}", material);
  1013. m_materialContacts[material, 0].geom = curContact;
  1014. _perloopContact.Add(curContact);
  1015. if (m_global_contactcount < maxContactsbeforedeath)
  1016. {
  1017. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, 0]);
  1018. m_global_contactcount++;
  1019. }
  1020. }
  1021. }
  1022. if (m_global_contactcount < maxContactsbeforedeath && joint != IntPtr.Zero) // stack collide!
  1023. {
  1024. d.JointAttach(joint, b1, b2);
  1025. m_global_contactcount++;
  1026. }
  1027. }
  1028. collision_accounting_events(p1, p2, maxDepthContact);
  1029. if (count > geomContactPointsStartthrottle)
  1030. {
  1031. // If there are more then 3 contact points, it's likely
  1032. // that we've got a pile of objects, so ...
  1033. // We don't want to send out hundreds of terse updates over and over again
  1034. // so lets throttle them and send them again after it's somewhat sorted out.
  1035. p2.ThrottleUpdates = true;
  1036. }
  1037. //m_log.Debug(count.ToString());
  1038. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  1039. }
  1040. }
  1041. private bool checkDupe(d.ContactGeom contactGeom, int atype)
  1042. {
  1043. bool result = false;
  1044. //return result;
  1045. if (!m_filterCollisions)
  1046. return false;
  1047. ActorTypes at = (ActorTypes)atype;
  1048. lock (_perloopContact)
  1049. {
  1050. foreach (d.ContactGeom contact in _perloopContact)
  1051. {
  1052. //if ((contact.g1 == contactGeom.g1 && contact.g2 == contactGeom.g2))
  1053. //{
  1054. // || (contact.g2 == contactGeom.g1 && contact.g1 == contactGeom.g2)
  1055. if (at == ActorTypes.Agent)
  1056. {
  1057. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f) && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f) && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)) && contactGeom.g1 != LandGeom && contactGeom.g2 != LandGeom)
  1058. {
  1059. if (Math.Abs(contact.depth - contactGeom.depth) < 0.052f)
  1060. {
  1061. //contactGeom.depth *= .00005f;
  1062. //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1063. // m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1064. result = true;
  1065. break;
  1066. }
  1067. else
  1068. {
  1069. //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1070. }
  1071. }
  1072. else
  1073. {
  1074. //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1075. //int i = 0;
  1076. }
  1077. }
  1078. else if (at == ActorTypes.Prim)
  1079. {
  1080. //d.AABB aabb1 = new d.AABB();
  1081. //d.AABB aabb2 = new d.AABB();
  1082. //d.GeomGetAABB(contactGeom.g2, out aabb2);
  1083. //d.GeomGetAABB(contactGeom.g1, out aabb1);
  1084. //aabb1.
  1085. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f) && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f) && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)) && contactGeom.g1 != LandGeom && contactGeom.g2 != LandGeom)
  1086. {
  1087. if (contactGeom.normal.X == contact.normal.X && contactGeom.normal.Y == contact.normal.Y && contactGeom.normal.Z == contact.normal.Z)
  1088. {
  1089. if (Math.Abs(contact.depth - contactGeom.depth) < 0.272f)
  1090. {
  1091. result = true;
  1092. break;
  1093. }
  1094. }
  1095. //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1096. //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1097. }
  1098. }
  1099. //}
  1100. }
  1101. }
  1102. return result;
  1103. }
  1104. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  1105. {
  1106. // obj1LocalID = 0;
  1107. //returncollisions = false;
  1108. obj2LocalID = 0;
  1109. //ctype = 0;
  1110. //cStartStop = 0;
  1111. if (!p2.SubscribedEvents() && !p1.SubscribedEvents())
  1112. return;
  1113. switch ((ActorTypes)p2.PhysicsActorType)
  1114. {
  1115. case ActorTypes.Agent:
  1116. cc2 = (OdeCharacter)p2;
  1117. // obj1LocalID = cc2.m_localID;
  1118. switch ((ActorTypes)p1.PhysicsActorType)
  1119. {
  1120. case ActorTypes.Agent:
  1121. cc1 = (OdeCharacter)p1;
  1122. obj2LocalID = cc1.m_localID;
  1123. cc1.AddCollisionEvent(cc2.m_localID, contact);
  1124. //ctype = (int)CollisionCategories.Character;
  1125. //if (cc1.CollidingObj)
  1126. //cStartStop = (int)StatusIndicators.Generic;
  1127. //else
  1128. //cStartStop = (int)StatusIndicators.Start;
  1129. //returncollisions = true;
  1130. break;
  1131. case ActorTypes.Prim:
  1132. if (p1 is OdePrim)
  1133. {
  1134. cp1 = (OdePrim) p1;
  1135. obj2LocalID = cp1.m_localID;
  1136. cp1.AddCollisionEvent(cc2.m_localID, contact);
  1137. }
  1138. //ctype = (int)CollisionCategories.Geom;
  1139. //if (cp1.CollidingObj)
  1140. //cStartStop = (int)StatusIndicators.Generic;
  1141. //else
  1142. //cStartStop = (int)StatusIndicators.Start;
  1143. //returncollisions = true;
  1144. break;
  1145. case ActorTypes.Ground:
  1146. case ActorTypes.Unknown:
  1147. obj2LocalID = 0;
  1148. //ctype = (int)CollisionCategories.Land;
  1149. //returncollisions = true;
  1150. break;
  1151. }
  1152. cc2.AddCollisionEvent(obj2LocalID, contact);
  1153. break;
  1154. case ActorTypes.Prim:
  1155. if (p2 is OdePrim)
  1156. {
  1157. cp2 = (OdePrim) p2;
  1158. // obj1LocalID = cp2.m_localID;
  1159. switch ((ActorTypes) p1.PhysicsActorType)
  1160. {
  1161. case ActorTypes.Agent:
  1162. if (p1 is OdeCharacter)
  1163. {
  1164. cc1 = (OdeCharacter) p1;
  1165. obj2LocalID = cc1.m_localID;
  1166. cc1.AddCollisionEvent(cp2.m_localID, contact);
  1167. //ctype = (int)CollisionCategories.Character;
  1168. //if (cc1.CollidingObj)
  1169. //cStartStop = (int)StatusIndicators.Generic;
  1170. //else
  1171. //cStartStop = (int)StatusIndicators.Start;
  1172. //returncollisions = true;
  1173. }
  1174. break;
  1175. case ActorTypes.Prim:
  1176. if (p1 is OdePrim)
  1177. {
  1178. cp1 = (OdePrim) p1;
  1179. obj2LocalID = cp1.m_localID;
  1180. cp1.AddCollisionEvent(cp2.m_localID, contact);
  1181. //ctype = (int)CollisionCategories.Geom;
  1182. //if (cp1.CollidingObj)
  1183. //cStartStop = (int)StatusIndicators.Generic;
  1184. //else
  1185. //cStartStop = (int)StatusIndicators.Start;
  1186. //returncollisions = true;
  1187. }
  1188. break;
  1189. case ActorTypes.Ground:
  1190. case ActorTypes.Unknown:
  1191. obj2LocalID = 0;
  1192. //ctype = (int)CollisionCategories.Land;
  1193. //returncollisions = true;
  1194. break;
  1195. }
  1196. cp2.AddCollisionEvent(obj2LocalID, contact);
  1197. }
  1198. break;
  1199. }
  1200. //if (returncollisions)
  1201. //{
  1202. //lock (m_storedCollisions)
  1203. //{
  1204. //cDictKey = obj1LocalID.ToString() + obj2LocalID.ToString() + cStartStop.ToString() + ctype.ToString();
  1205. //if (m_storedCollisions.ContainsKey(cDictKey))
  1206. //{
  1207. //sCollisionData objd = m_storedCollisions[cDictKey];
  1208. //objd.NumberOfCollisions += 1;
  1209. //objd.lastframe = framecount;
  1210. //m_storedCollisions[cDictKey] = objd;
  1211. //}
  1212. //else
  1213. //{
  1214. //sCollisionData objd = new sCollisionData();
  1215. //objd.ColliderLocalId = obj1LocalID;
  1216. //objd.CollidedWithLocalId = obj2LocalID;
  1217. //objd.CollisionType = ctype;
  1218. //objd.NumberOfCollisions = 1;
  1219. //objd.lastframe = framecount;
  1220. //objd.StatusIndicator = cStartStop;
  1221. //m_storedCollisions.Add(cDictKey, objd);
  1222. //}
  1223. //}
  1224. // }
  1225. }
  1226. public int TriArrayCallback(IntPtr trimesh, IntPtr refObject, int[] triangleIndex, int triCount)
  1227. {
  1228. /* String name1 = null;
  1229. String name2 = null;
  1230. if (!geom_name_map.TryGetValue(trimesh, out name1))
  1231. {
  1232. name1 = "null";
  1233. }
  1234. if (!geom_name_map.TryGetValue(refObject, out name2))
  1235. {
  1236. name2 = "null";
  1237. }
  1238. m_log.InfoFormat("TriArrayCallback: A collision was detected between {1} and {2}", 0, name1, name2);
  1239. */
  1240. return 1;
  1241. }
  1242. public int TriCallback(IntPtr trimesh, IntPtr refObject, int triangleIndex)
  1243. {
  1244. String name1 = null;
  1245. String name2 = null;
  1246. if (!geom_name_map.TryGetValue(trimesh, out name1))
  1247. {
  1248. name1 = "null";
  1249. }
  1250. if (!geom_name_map.TryGetValue(refObject, out name2))
  1251. {
  1252. name2 = "null";
  1253. }
  1254. // m_log.InfoFormat("TriCallback: A collision was detected between {1} and {2}. Index was {3}", 0, name1, name2, triangleIndex);
  1255. d.Vector3 v0 = new d.Vector3();
  1256. d.Vector3 v1 = new d.Vector3();
  1257. d.Vector3 v2 = new d.Vector3();
  1258. d.GeomTriMeshGetTriangle(trimesh, 0, ref v0, ref v1, ref v2);
  1259. // m_log.DebugFormat("Triangle {0} is <{1},{2},{3}>, <{4},{5},{6}>, <{7},{8},{9}>", triangleIndex, v0.X, v0.Y, v0.Z, v1.X, v1.Y, v1.Z, v2.X, v2.Y, v2.Z);
  1260. return 1;
  1261. }
  1262. /// <summary>
  1263. /// This is our collision testing routine in ODE
  1264. /// </summary>
  1265. /// <param name="timeStep"></param>
  1266. private void collision_optimized(float timeStep)
  1267. {
  1268. _perloopContact.Clear();
  1269. lock (_characters)
  1270. {
  1271. foreach (OdeCharacter chr in _characters)
  1272. {
  1273. // Reset the collision values to false
  1274. // since we don't know if we're colliding yet
  1275. // For some reason this can happen. Don't ask...
  1276. //
  1277. if (chr == null)
  1278. continue;
  1279. if (chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero)
  1280. continue;
  1281. chr.IsColliding = false;
  1282. chr.CollidingGround = false;
  1283. chr.CollidingObj = false;
  1284. // test the avatar's geometry for collision with the space
  1285. // This will return near and the space that they are the closest to
  1286. // And we'll run this again against the avatar and the space segment
  1287. // This will return with a bunch of possible objects in the space segment
  1288. // and we'll run it again on all of them.
  1289. try
  1290. {
  1291. d.SpaceCollide2(space, chr.Shell, IntPtr.Zero, nearCallback);
  1292. }
  1293. catch (AccessViolationException)
  1294. {
  1295. m_log.Warn("[PHYSICS]: Unable to space collide");
  1296. }
  1297. //float terrainheight = GetTerrainHeightAtXY(chr.Position.X, chr.Position.Y);
  1298. //if (chr.Position.Z + (chr.Velocity.Z * timeStep) < terrainheight + 10)
  1299. //{
  1300. //chr.Position.Z = terrainheight + 10.0f;
  1301. //forcedZ = true;
  1302. //}
  1303. }
  1304. }
  1305. lock (_activeprims)
  1306. {
  1307. List<OdePrim> removeprims = null;
  1308. foreach (OdePrim chr in _activeprims)
  1309. {
  1310. if (chr.Body != IntPtr.Zero && d.BodyIsEnabled(chr.Body) && (!chr.m_disabled))
  1311. {
  1312. try
  1313. {
  1314. lock (chr)
  1315. {
  1316. if (space != IntPtr.Zero && chr.prim_geom != IntPtr.Zero && chr.m_taintremove == false)
  1317. {
  1318. d.SpaceCollide2(space, chr.prim_geom, IntPtr.Zero, nearCallback);
  1319. }
  1320. else
  1321. {
  1322. if (removeprims == null)
  1323. {
  1324. removeprims = new List<OdePrim>();
  1325. }
  1326. removeprims.Add(chr);
  1327. m_log.Debug("[PHYSICS]: unable to collide test active prim against space. The space was zero, the geom was zero or it was in the process of being removed. Removed it from the active prim list. This needs to be fixed!");
  1328. }
  1329. }
  1330. }
  1331. catch (AccessViolationException)
  1332. {
  1333. m_log.Warn("[PHYSICS]: Unable to space collide");
  1334. }
  1335. }
  1336. }
  1337. if (removeprims != null)
  1338. {
  1339. foreach (OdePrim chr in removeprims)
  1340. {
  1341. _activeprims.Remove(chr);
  1342. }
  1343. }
  1344. }
  1345. _perloopContact.Clear();
  1346. }
  1347. #endregion
  1348. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  1349. {
  1350. m_worldOffset = offset;
  1351. WorldExtents = new Vector2(extents.X, extents.Y);
  1352. m_parentScene = pScene;
  1353. }
  1354. // Recovered for use by fly height. Kitto Flora
  1355. public float GetTerrainHeightAtXY(float x, float y)
  1356. {
  1357. int offsetX = ((int)(x / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
  1358. int offsetY = ((int)(y / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
  1359. IntPtr heightFieldGeom = IntPtr.Zero;
  1360. if (RegionTerrain.TryGetValue(new Vector3(offsetX,offsetY,0), out heightFieldGeom))
  1361. {
  1362. if (heightFieldGeom != IntPtr.Zero)
  1363. {
  1364. if (TerrainHeightFieldHeights.ContainsKey(heightFieldGeom))
  1365. {
  1366. int index;
  1367. if ((int)x > WorldExtents.X || (int)y > WorldExtents.Y ||
  1368. (int)x < 0.001f || (int)y < 0.001f)
  1369. return 0;
  1370. x = x - offsetX;
  1371. y = y - offsetY;
  1372. index = (int)((int)x * ((int)Constants.RegionSize + 2) + (int)y);
  1373. if (index < TerrainHeightFieldHeights[heightFieldGeom].Length)
  1374. {
  1375. //m_log.DebugFormat("x{0} y{1} = {2}", x, y, (float)TerrainHeightFieldHeights[heightFieldGeom][index]);
  1376. return (float)TerrainHeightFieldHeights[heightFieldGeom][index];
  1377. }
  1378. else
  1379. return 0f;
  1380. }
  1381. else
  1382. {
  1383. return 0f;
  1384. }
  1385. }
  1386. else
  1387. {
  1388. return 0f;
  1389. }
  1390. }
  1391. else
  1392. {
  1393. return 0f;
  1394. }
  1395. }
  1396. // End recovered. Kitto Flora
  1397. public void addCollisionEventReporting(PhysicsActor obj)
  1398. {
  1399. lock (_collisionEventPrim)
  1400. {
  1401. if (!_collisionEventPrim.Contains(obj))
  1402. _collisionEventPrim.Add(obj);
  1403. }
  1404. }
  1405. public void remCollisionEventReporting(PhysicsActor obj)
  1406. {
  1407. lock (_collisionEventPrim)
  1408. {
  1409. if (!_collisionEventPrim.Contains(obj))
  1410. _collisionEventPrim.Remove(obj);
  1411. }
  1412. }
  1413. #region Add/Remove Entities
  1414. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
  1415. {
  1416. Vector3 pos;
  1417. pos.X = position.X;
  1418. pos.Y = position.Y;
  1419. pos.Z = position.Z;
  1420. OdeCharacter newAv = new OdeCharacter(avName, this, pos, ode, size, avPIDD, avPIDP, avCapRadius, avStandupTensor, avDensity, avHeightFudgeFactor, avMovementDivisorWalk, avMovementDivisorRun);
  1421. newAv.Flying = isFlying;
  1422. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1423. return newAv;
  1424. }
  1425. public void AddCharacter(OdeCharacter chr)
  1426. {
  1427. lock (_characters)
  1428. {
  1429. if (!_characters.Contains(chr))
  1430. {
  1431. _characters.Add(chr);
  1432. if (chr.bad)
  1433. m_log.DebugFormat("[PHYSICS] Added BAD actor {0} to characters list", chr.m_uuid);
  1434. }
  1435. }
  1436. }
  1437. public void RemoveCharacter(OdeCharacter chr)
  1438. {
  1439. lock (_characters)
  1440. {
  1441. if (_characters.Contains(chr))
  1442. {
  1443. _characters.Remove(chr);
  1444. }
  1445. }
  1446. }
  1447. public void BadCharacter(OdeCharacter chr)
  1448. {
  1449. lock (_badCharacter)
  1450. {
  1451. if (!_badCharacter.Contains(chr))
  1452. _badCharacter.Add(chr);
  1453. }
  1454. }
  1455. public override void RemoveAvatar(PhysicsActor actor)
  1456. {
  1457. //m_log.Debug("[PHYSICS]:ODELOCK");
  1458. ((OdeCharacter) actor).Destroy();
  1459. }
  1460. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1461. IMesh mesh, PrimitiveBaseShape pbs, bool isphysical)
  1462. {
  1463. Vector3 pos = position;
  1464. Vector3 siz = size;
  1465. Quaternion rot = rotation;
  1466. OdePrim newPrim;
  1467. lock (OdeLock)
  1468. {
  1469. newPrim = new OdePrim(name, this, pos, siz, rot, mesh, pbs, isphysical, ode);
  1470. lock (_prims)
  1471. _prims.Add(newPrim);
  1472. }
  1473. return newPrim;
  1474. }
  1475. public void addActivePrim(OdePrim activatePrim)
  1476. {
  1477. // adds active prim.. (ones that should be iterated over in collisions_optimized
  1478. lock (_activeprims)
  1479. {
  1480. if (!_activeprims.Contains(activatePrim))
  1481. _activeprims.Add(activatePrim);
  1482. //else
  1483. // m_log.Warn("[PHYSICS]: Double Entry in _activeprims detected, potential crash immenent");
  1484. }
  1485. }
  1486. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1487. Vector3 size, Quaternion rotation) //To be removed
  1488. {
  1489. return AddPrimShape(primName, pbs, position, size, rotation, false);
  1490. }
  1491. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1492. Vector3 size, Quaternion rotation, bool isPhysical)
  1493. {
  1494. PhysicsActor result;
  1495. IMesh mesh = null;
  1496. if (needsMeshing(pbs))
  1497. {
  1498. try
  1499. {
  1500. mesh = mesher.CreateMesh(primName, pbs, size, 32f, isPhysical);
  1501. }
  1502. catch(Exception e)
  1503. {
  1504. m_log.ErrorFormat("[PHYSICS]: Exception while meshing prim {0}.", primName);
  1505. m_log.Debug(e.ToString());
  1506. mesh = null;
  1507. return null;
  1508. }
  1509. }
  1510. result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical);
  1511. return result;
  1512. }
  1513. public override float TimeDilation
  1514. {
  1515. get { return m_timeDilation; }
  1516. }
  1517. public override bool SupportsNINJAJoints
  1518. {
  1519. get { return m_NINJA_physics_joints_enabled; }
  1520. }
  1521. // internal utility function: must be called within a lock (OdeLock)
  1522. private void InternalAddActiveJoint(PhysicsJoint joint)
  1523. {
  1524. activeJoints.Add(joint);
  1525. SOPName_to_activeJoint.Add(joint.ObjectNameInScene, joint);
  1526. }
  1527. // internal utility function: must be called within a lock (OdeLock)
  1528. private void InternalAddPendingJoint(OdePhysicsJoint joint)
  1529. {
  1530. pendingJoints.Add(joint);
  1531. SOPName_to_pendingJoint.Add(joint.ObjectNameInScene, joint);
  1532. }
  1533. // internal utility function: must be called within a lock (OdeLock)
  1534. private void InternalRemovePendingJoint(PhysicsJoint joint)
  1535. {
  1536. pendingJoints.Remove(joint);
  1537. SOPName_to_pendingJoint.Remove(joint.ObjectNameInScene);
  1538. }
  1539. // internal utility function: must be called within a lock (OdeLock)
  1540. private void InternalRemoveActiveJoint(PhysicsJoint joint)
  1541. {
  1542. activeJoints.Remove(joint);
  1543. SOPName_to_activeJoint.Remove(joint.ObjectNameInScene);
  1544. }
  1545. public override void DumpJointInfo()
  1546. {
  1547. string hdr = "[NINJA] JOINTINFO: ";
  1548. foreach (PhysicsJoint j in pendingJoints)
  1549. {
  1550. m_log.Debug(hdr + " pending joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1551. }
  1552. m_log.Debug(hdr + pendingJoints.Count + " total pending joints");
  1553. foreach (string jointName in SOPName_to_pendingJoint.Keys)
  1554. {
  1555. m_log.Debug(hdr + " pending joints dict contains Name: " + jointName);
  1556. }
  1557. m_log.Debug(hdr + SOPName_to_pendingJoint.Keys.Count + " total pending joints dict entries");
  1558. foreach (PhysicsJoint j in activeJoints)
  1559. {
  1560. m_log.Debug(hdr + " active joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1561. }
  1562. m_log.Debug(hdr + activeJoints.Count + " total active joints");
  1563. foreach (string jointName in SOPName_to_activeJoint.Keys)
  1564. {
  1565. m_log.Debug(hdr + " active joints dict contains Name: " + jointName);
  1566. }
  1567. m_log.Debug(hdr + SOPName_to_activeJoint.Keys.Count + " total active joints dict entries");
  1568. m_log.Debug(hdr + " Per-body joint connectivity information follows.");
  1569. m_log.Debug(hdr + joints_connecting_actor.Keys.Count + " bodies are connected by joints.");
  1570. foreach (string actorName in joints_connecting_actor.Keys)
  1571. {
  1572. m_log.Debug(hdr + " Actor " + actorName + " has the following joints connecting it");
  1573. foreach (PhysicsJoint j in joints_connecting_actor[actorName])
  1574. {
  1575. m_log.Debug(hdr + " * joint Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1576. }
  1577. m_log.Debug(hdr + joints_connecting_actor[actorName].Count + " connecting joints total for this actor");
  1578. }
  1579. }
  1580. public override void RequestJointDeletion(string ObjectNameInScene)
  1581. {
  1582. lock (externalJointRequestsLock)
  1583. {
  1584. if (!requestedJointsToBeDeleted.Contains(ObjectNameInScene)) // forbid same deletion request from entering twice to prevent spurious deletions processed asynchronously
  1585. {
  1586. requestedJointsToBeDeleted.Add(ObjectNameInScene);
  1587. }
  1588. }
  1589. }
  1590. private void DeleteRequestedJoints()
  1591. {
  1592. List<string> myRequestedJointsToBeDeleted;
  1593. lock (externalJointRequestsLock)
  1594. {
  1595. // make a local copy of the shared list for processing (threading issues)
  1596. myRequestedJointsToBeDeleted = new List<string>(requestedJointsToBeDeleted);
  1597. }
  1598. foreach (string jointName in myRequestedJointsToBeDeleted)
  1599. {
  1600. lock (OdeLock)
  1601. {
  1602. //m_log.Debug("[NINJA] trying to deleting requested joint " + jointName);
  1603. if (SOPName_to_activeJoint.ContainsKey(jointName) || SOPName_to_pendingJoint.ContainsKey(jointName))
  1604. {
  1605. OdePhysicsJoint joint = null;
  1606. if (SOPName_to_activeJoint.ContainsKey(jointName))
  1607. {
  1608. joint = SOPName_to_activeJoint[jointName] as OdePhysicsJoint;
  1609. InternalRemoveActiveJoint(joint);
  1610. }
  1611. else if (SOPName_to_pendingJoint.ContainsKey(jointName))
  1612. {
  1613. joint = SOPName_to_pendingJoint[jointName] as OdePhysicsJoint;
  1614. InternalRemovePendingJoint(joint);
  1615. }
  1616. if (joint != null)
  1617. {
  1618. //m_log.Debug("joint.BodyNames.Count is " + joint.BodyNames.Count + " and contents " + joint.BodyNames);
  1619. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1620. {
  1621. string bodyName = joint.BodyNames[iBodyName];
  1622. if (bodyName != "NULL")
  1623. {
  1624. joints_connecting_actor[bodyName].Remove(joint);
  1625. if (joints_connecting_actor[bodyName].Count == 0)
  1626. {
  1627. joints_connecting_actor.Remove(bodyName);
  1628. }
  1629. }
  1630. }
  1631. DoJointDeactivated(joint);
  1632. if (joint.jointID != IntPtr.Zero)
  1633. {
  1634. d.JointDestroy(joint.jointID);
  1635. joint.jointID = IntPtr.Zero;
  1636. //DoJointErrorMessage(joint, "successfully destroyed joint " + jointName);
  1637. }
  1638. else
  1639. {
  1640. //m_log.Warn("[NINJA] Ignoring re-request to destroy joint " + jointName);
  1641. }
  1642. }
  1643. else
  1644. {
  1645. // DoJointErrorMessage(joint, "coult not find joint to destroy based on name " + jointName);
  1646. }
  1647. }
  1648. else
  1649. {
  1650. // DoJointErrorMessage(joint, "WARNING - joint removal failed, joint " + jointName);
  1651. }
  1652. }
  1653. }
  1654. // remove processed joints from the shared list
  1655. lock (externalJointRequestsLock)
  1656. {
  1657. foreach (string jointName in myRequestedJointsToBeDeleted)
  1658. {
  1659. requestedJointsToBeDeleted.Remove(jointName);
  1660. }
  1661. }
  1662. }
  1663. // for pending joints we don't know if their associated bodies exist yet or not.
  1664. // the joint is actually created during processing of the taints
  1665. private void CreateRequestedJoints()
  1666. {
  1667. List<PhysicsJoint> myRequestedJointsToBeCreated;
  1668. lock (externalJointRequestsLock)
  1669. {
  1670. // make a local copy of the shared list for processing (threading issues)
  1671. myRequestedJointsToBeCreated = new List<PhysicsJoint>(requestedJointsToBeCreated);
  1672. }
  1673. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1674. {
  1675. lock (OdeLock)
  1676. {
  1677. if (SOPName_to_pendingJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_pendingJoint[joint.ObjectNameInScene] != null)
  1678. {
  1679. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already pending joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  1680. continue;
  1681. }
  1682. if (SOPName_to_activeJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_activeJoint[joint.ObjectNameInScene] != null)
  1683. {
  1684. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already active joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  1685. continue;
  1686. }
  1687. InternalAddPendingJoint(joint as OdePhysicsJoint);
  1688. if (joint.BodyNames.Count >= 2)
  1689. {
  1690. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1691. {
  1692. string bodyName = joint.BodyNames[iBodyName];
  1693. if (bodyName != "NULL")
  1694. {
  1695. if (!joints_connecting_actor.ContainsKey(bodyName))
  1696. {
  1697. joints_connecting_actor.Add(bodyName, new List<PhysicsJoint>());
  1698. }
  1699. joints_connecting_actor[bodyName].Add(joint);
  1700. }
  1701. }
  1702. }
  1703. }
  1704. }
  1705. // remove processed joints from shared list
  1706. lock (externalJointRequestsLock)
  1707. {
  1708. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1709. {
  1710. requestedJointsToBeCreated.Remove(joint);
  1711. }
  1712. }
  1713. }
  1714. // public function to add an request for joint creation
  1715. // this joint will just be added to a waiting list that is NOT processed during the main
  1716. // Simulate() loop (to avoid deadlocks). After Simulate() is finished, we handle unprocessed joint requests.
  1717. public override PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, Vector3 position,
  1718. Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation)
  1719. {
  1720. OdePhysicsJoint joint = new OdePhysicsJoint();
  1721. joint.ObjectNameInScene = objectNameInScene;
  1722. joint.Type = jointType;
  1723. joint.Position = position;
  1724. joint.Rotation = rotation;
  1725. joint.RawParams = parms;
  1726. joint.BodyNames = new List<string>(bodyNames);
  1727. joint.TrackedBodyName = trackedBodyName;
  1728. joint.LocalRotation = localRotation;
  1729. joint.jointID = IntPtr.Zero;
  1730. joint.ErrorMessageCount = 0;
  1731. lock (externalJointRequestsLock)
  1732. {
  1733. if (!requestedJointsToBeCreated.Contains(joint)) // forbid same creation request from entering twice
  1734. {
  1735. requestedJointsToBeCreated.Add(joint);
  1736. }
  1737. }
  1738. return joint;
  1739. }
  1740. private void RemoveAllJointsConnectedToActor(PhysicsActor actor)
  1741. {
  1742. //m_log.Debug("RemoveAllJointsConnectedToActor: start");
  1743. if (actor.SOPName != null && joints_connecting_actor.ContainsKey(actor.SOPName) && joints_connecting_actor[actor.SOPName] != null)
  1744. {
  1745. List<PhysicsJoint> jointsToRemove = new List<PhysicsJoint>();
  1746. //TODO: merge these 2 loops (originally it was needed to avoid altering a list being iterated over, but it is no longer needed due to the joint request queue mechanism)
  1747. foreach (PhysicsJoint j in joints_connecting_actor[actor.SOPName])
  1748. {
  1749. jointsToRemove.Add(j);
  1750. }
  1751. foreach (PhysicsJoint j in jointsToRemove)
  1752. {
  1753. //m_log.Debug("RemoveAllJointsConnectedToActor: about to request deletion of " + j.ObjectNameInScene);
  1754. RequestJointDeletion(j.ObjectNameInScene);
  1755. //m_log.Debug("RemoveAllJointsConnectedToActor: done request deletion of " + j.ObjectNameInScene);
  1756. j.TrackedBodyName = null; // *IMMEDIATELY* prevent any further movement of this joint (else a deleted actor might cause spurious tracking motion of the joint for a few frames, leading to the joint proxy object disappearing)
  1757. }
  1758. }
  1759. }
  1760. public override void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor)
  1761. {
  1762. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: start");
  1763. lock (OdeLock)
  1764. {
  1765. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: got lock");
  1766. RemoveAllJointsConnectedToActor(actor);
  1767. }
  1768. }
  1769. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  1770. public override Vector3 GetJointAnchor(PhysicsJoint joint)
  1771. {
  1772. Debug.Assert(joint.IsInPhysicsEngine);
  1773. d.Vector3 pos = new d.Vector3();
  1774. if (!(joint is OdePhysicsJoint))
  1775. {
  1776. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  1777. }
  1778. else
  1779. {
  1780. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  1781. switch (odeJoint.Type)
  1782. {
  1783. case PhysicsJointType.Ball:
  1784. d.JointGetBallAnchor(odeJoint.jointID, out pos);
  1785. break;
  1786. case PhysicsJointType.Hinge:
  1787. d.JointGetHingeAnchor(odeJoint.jointID, out pos);
  1788. break;
  1789. }
  1790. }
  1791. return new Vector3(pos.X, pos.Y, pos.Z);
  1792. }
  1793. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  1794. // WARNING: ODE sometimes returns <0,0,0> as the joint axis! Therefore this function
  1795. // appears to be unreliable. Fortunately we can compute the joint axis ourselves by
  1796. // keeping track of the joint's original orientation relative to one of the involved bodies.
  1797. public override Vector3 GetJointAxis(PhysicsJoint joint)
  1798. {
  1799. Debug.Assert(joint.IsInPhysicsEngine);
  1800. d.Vector3 axis = new d.Vector3();
  1801. if (!(joint is OdePhysicsJoint))
  1802. {
  1803. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  1804. }
  1805. else
  1806. {
  1807. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  1808. switch (odeJoint.Type)
  1809. {
  1810. case PhysicsJointType.Ball:
  1811. DoJointErrorMessage(joint, "warning - axis requested for ball joint: " + joint.ObjectNameInScene);
  1812. break;
  1813. case PhysicsJointType.Hinge:
  1814. d.JointGetHingeAxis(odeJoint.jointID, out axis);
  1815. break;
  1816. }
  1817. }
  1818. return new Vector3(axis.X, axis.Y, axis.Z);
  1819. }
  1820. public void remActivePrim(OdePrim deactivatePrim)
  1821. {
  1822. lock (_activeprims)
  1823. {
  1824. _activeprims.Remove(deactivatePrim);
  1825. }
  1826. }
  1827. public override void RemovePrim(PhysicsActor prim)
  1828. {
  1829. if (prim is OdePrim)
  1830. {
  1831. lock (OdeLock)
  1832. {
  1833. OdePrim p = (OdePrim) prim;
  1834. p.setPrimForRemoval();
  1835. AddPhysicsActorTaint(prim);
  1836. //RemovePrimThreadLocked(p);
  1837. }
  1838. }
  1839. }
  1840. /// <summary>
  1841. /// This is called from within simulate but outside the locked portion
  1842. /// We need to do our own locking here
  1843. /// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
  1844. ///
  1845. /// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
  1846. /// that the space was using.
  1847. /// </summary>
  1848. /// <param name="prim"></param>
  1849. public void RemovePrimThreadLocked(OdePrim prim)
  1850. {
  1851. //Console.WriteLine("RemovePrimThreadLocked " + prim.m_primName);
  1852. lock (prim)
  1853. {
  1854. remCollisionEventReporting(prim);
  1855. lock (ode)
  1856. {
  1857. if (prim.prim_geom != IntPtr.Zero)
  1858. {
  1859. prim.ResetTaints();
  1860. if (prim.IsPhysical)
  1861. {
  1862. prim.disableBody();
  1863. if (prim.childPrim)
  1864. {
  1865. prim.childPrim = false;
  1866. prim.Body = IntPtr.Zero;
  1867. prim.m_disabled = true;
  1868. prim.IsPhysical = false;
  1869. }
  1870. }
  1871. // we don't want to remove the main space
  1872. // If the geometry is in the targetspace, remove it from the target space
  1873. //m_log.Warn(prim.m_targetSpace);
  1874. //if (prim.m_targetSpace != IntPtr.Zero)
  1875. //{
  1876. //if (d.SpaceQuery(prim.m_targetSpace, prim.prim_geom))
  1877. //{
  1878. //if (d.GeomIsSpace(prim.m_targetSpace))
  1879. //{
  1880. //waitForSpaceUnlock(prim.m_targetSpace);
  1881. //d.SpaceRemove(prim.m_targetSpace, prim.prim_geom);
  1882. prim.m_targetSpace = IntPtr.Zero;
  1883. //}
  1884. //else
  1885. //{
  1886. // m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  1887. //((OdePrim)prim).m_targetSpace.ToString());
  1888. //}
  1889. //}
  1890. //}
  1891. //m_log.Warn(prim.prim_geom);
  1892. try
  1893. {
  1894. if (prim.prim_geom != IntPtr.Zero)
  1895. {
  1896. d.GeomDestroy(prim.prim_geom);
  1897. prim.prim_geom = IntPtr.Zero;
  1898. }
  1899. else
  1900. {
  1901. m_log.Warn("[PHYSICS]: Unable to remove prim from physics scene");
  1902. }
  1903. }
  1904. catch (AccessViolationException)
  1905. {
  1906. m_log.Info("[PHYSICS]: Couldn't remove prim from physics scene, it was already be removed.");
  1907. }
  1908. lock (_prims)
  1909. _prims.Remove(prim);
  1910. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  1911. //if (d.SpaceGetNumGeoms(prim.m_targetSpace) == 0)
  1912. //{
  1913. //if (prim.m_targetSpace != null)
  1914. //{
  1915. //if (d.GeomIsSpace(prim.m_targetSpace))
  1916. //{
  1917. //waitForSpaceUnlock(prim.m_targetSpace);
  1918. //d.SpaceRemove(space, prim.m_targetSpace);
  1919. // free up memory used by the space.
  1920. //d.SpaceDestroy(prim.m_targetSpace);
  1921. //int[] xyspace = calculateSpaceArrayItemFromPos(prim.Position);
  1922. //resetSpaceArrayItemToZero(xyspace[0], xyspace[1]);
  1923. //}
  1924. //else
  1925. //{
  1926. //m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  1927. //((OdePrim) prim).m_targetSpace.ToString());
  1928. //}
  1929. //}
  1930. //}
  1931. if (SupportsNINJAJoints)
  1932. {
  1933. RemoveAllJointsConnectedToActorThreadLocked(prim);
  1934. }
  1935. }
  1936. }
  1937. }
  1938. }
  1939. #endregion
  1940. #region Space Separation Calculation
  1941. /// <summary>
  1942. /// Takes a space pointer and zeros out the array we're using to hold the spaces
  1943. /// </summary>
  1944. /// <param name="pSpace"></param>
  1945. public void resetSpaceArrayItemToZero(IntPtr pSpace)
  1946. {
  1947. for (int x = 0; x < staticPrimspace.GetLength(0); x++)
  1948. {
  1949. for (int y = 0; y < staticPrimspace.GetLength(1); y++)
  1950. {
  1951. if (staticPrimspace[x, y] == pSpace)
  1952. staticPrimspace[x, y] = IntPtr.Zero;
  1953. }
  1954. }
  1955. }
  1956. public void resetSpaceArrayItemToZero(int arrayitemX, int arrayitemY)
  1957. {
  1958. staticPrimspace[arrayitemX, arrayitemY] = IntPtr.Zero;
  1959. }
  1960. /// <summary>
  1961. /// Called when a static prim moves. Allocates a space for the prim based on its position
  1962. /// </summary>
  1963. /// <param name="geom">the pointer to the geom that moved</param>
  1964. /// <param name="pos">the position that the geom moved to</param>
  1965. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1966. /// <returns>a pointer to the new space it's in</returns>
  1967. public IntPtr recalculateSpaceForGeom(IntPtr geom, Vector3 pos, IntPtr currentspace)
  1968. {
  1969. // Called from setting the Position and Size of an ODEPrim so
  1970. // it's already in locked space.
  1971. // we don't want to remove the main space
  1972. // we don't need to test physical here because this function should
  1973. // never be called if the prim is physical(active)
  1974. // All physical prim end up in the root space
  1975. //Thread.Sleep(20);
  1976. if (currentspace != space)
  1977. {
  1978. //m_log.Info("[SPACE]: C:" + currentspace.ToString() + " g:" + geom.ToString());
  1979. //if (currentspace == IntPtr.Zero)
  1980. //{
  1981. //int adfadf = 0;
  1982. //}
  1983. if (d.SpaceQuery(currentspace, geom) && currentspace != IntPtr.Zero)
  1984. {
  1985. if (d.GeomIsSpace(currentspace))
  1986. {
  1987. waitForSpaceUnlock(currentspace);
  1988. d.SpaceRemove(currentspace, geom);
  1989. }
  1990. else
  1991. {
  1992. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" + currentspace +
  1993. " Geom:" + geom);
  1994. }
  1995. }
  1996. else
  1997. {
  1998. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  1999. if (sGeomIsIn != IntPtr.Zero)
  2000. {
  2001. if (d.GeomIsSpace(currentspace))
  2002. {
  2003. waitForSpaceUnlock(sGeomIsIn);
  2004. d.SpaceRemove(sGeomIsIn, geom);
  2005. }
  2006. else
  2007. {
  2008. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2009. sGeomIsIn + " Geom:" + geom);
  2010. }
  2011. }
  2012. }
  2013. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  2014. if (d.SpaceGetNumGeoms(currentspace) == 0)
  2015. {
  2016. if (currentspace != IntPtr.Zero)
  2017. {
  2018. if (d.GeomIsSpace(currentspace))
  2019. {
  2020. waitForSpaceUnlock(currentspace);
  2021. waitForSpaceUnlock(space);
  2022. d.SpaceRemove(space, currentspace);
  2023. // free up memory used by the space.
  2024. //d.SpaceDestroy(currentspace);
  2025. resetSpaceArrayItemToZero(currentspace);
  2026. }
  2027. else
  2028. {
  2029. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2030. currentspace + " Geom:" + geom);
  2031. }
  2032. }
  2033. }
  2034. }
  2035. else
  2036. {
  2037. // this is a physical object that got disabled. ;.;
  2038. if (currentspace != IntPtr.Zero && geom != IntPtr.Zero)
  2039. {
  2040. if (d.SpaceQuery(currentspace, geom))
  2041. {
  2042. if (d.GeomIsSpace(currentspace))
  2043. {
  2044. waitForSpaceUnlock(currentspace);
  2045. d.SpaceRemove(currentspace, geom);
  2046. }
  2047. else
  2048. {
  2049. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2050. currentspace + " Geom:" + geom);
  2051. }
  2052. }
  2053. else
  2054. {
  2055. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2056. if (sGeomIsIn != IntPtr.Zero)
  2057. {
  2058. if (d.GeomIsSpace(sGeomIsIn))
  2059. {
  2060. waitForSpaceUnlock(sGeomIsIn);
  2061. d.SpaceRemove(sGeomIsIn, geom);
  2062. }
  2063. else
  2064. {
  2065. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2066. sGeomIsIn + " Geom:" + geom);
  2067. }
  2068. }
  2069. }
  2070. }
  2071. }
  2072. // The routines in the Position and Size sections do the 'inserting' into the space,
  2073. // so all we have to do is make sure that the space that we're putting the prim into
  2074. // is in the 'main' space.
  2075. int[] iprimspaceArrItem = calculateSpaceArrayItemFromPos(pos);
  2076. IntPtr newspace = calculateSpaceForGeom(pos);
  2077. if (newspace == IntPtr.Zero)
  2078. {
  2079. newspace = createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  2080. d.HashSpaceSetLevels(newspace, smallHashspaceLow, smallHashspaceHigh);
  2081. }
  2082. return newspace;
  2083. }
  2084. /// <summary>
  2085. /// Creates a new space at X Y
  2086. /// </summary>
  2087. /// <param name="iprimspaceArrItemX"></param>
  2088. /// <param name="iprimspaceArrItemY"></param>
  2089. /// <returns>A pointer to the created space</returns>
  2090. public IntPtr createprimspace(int iprimspaceArrItemX, int iprimspaceArrItemY)
  2091. {
  2092. // creating a new space for prim and inserting it into main space.
  2093. staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY] = d.HashSpaceCreate(IntPtr.Zero);
  2094. d.GeomSetCategoryBits(staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY], (int)CollisionCategories.Space);
  2095. waitForSpaceUnlock(space);
  2096. d.SpaceSetSublevel(space, 1);
  2097. d.SpaceAdd(space, staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY]);
  2098. return staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY];
  2099. }
  2100. /// <summary>
  2101. /// Calculates the space the prim should be in by its position
  2102. /// </summary>
  2103. /// <param name="pos"></param>
  2104. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  2105. public IntPtr calculateSpaceForGeom(Vector3 pos)
  2106. {
  2107. int[] xyspace = calculateSpaceArrayItemFromPos(pos);
  2108. //m_log.Info("[Physics]: Attempting to use arrayItem: " + xyspace[0].ToString() + "," + xyspace[1].ToString());
  2109. return staticPrimspace[xyspace[0], xyspace[1]];
  2110. }
  2111. /// <summary>
  2112. /// Holds the space allocation logic
  2113. /// </summary>
  2114. /// <param name="pos"></param>
  2115. /// <returns>an array item based on the position</returns>
  2116. public int[] calculateSpaceArrayItemFromPos(Vector3 pos)
  2117. {
  2118. int[] returnint = new int[2];
  2119. returnint[0] = (int) (pos.X/metersInSpace);
  2120. if (returnint[0] > ((int) (259f/metersInSpace)))
  2121. returnint[0] = ((int) (259f/metersInSpace));
  2122. if (returnint[0] < 0)
  2123. returnint[0] = 0;
  2124. returnint[1] = (int) (pos.Y/metersInSpace);
  2125. if (returnint[1] > ((int) (259f/metersInSpace)))
  2126. returnint[1] = ((int) (259f/metersInSpace));
  2127. if (returnint[1] < 0)
  2128. returnint[1] = 0;
  2129. return returnint;
  2130. }
  2131. #endregion
  2132. /// <summary>
  2133. /// Routine to figure out if we need to mesh this prim with our mesher
  2134. /// </summary>
  2135. /// <param name="pbs"></param>
  2136. /// <returns></returns>
  2137. public bool needsMeshing(PrimitiveBaseShape pbs)
  2138. {
  2139. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  2140. // but we still need to check for sculptie meshing being enabled so this is the most
  2141. // convenient place to do it for now...
  2142. // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
  2143. // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
  2144. int iPropertiesNotSupportedDefault = 0;
  2145. if (pbs.SculptEntry && !meshSculptedPrim)
  2146. {
  2147. #if SPAM
  2148. m_log.Warn("NonMesh");
  2149. #endif
  2150. return false;
  2151. }
  2152. // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim
  2153. if (!forceSimplePrimMeshing)
  2154. {
  2155. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  2156. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  2157. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  2158. {
  2159. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  2160. && pbs.ProfileHollow == 0
  2161. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  2162. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  2163. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  2164. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  2165. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  2166. {
  2167. #if SPAM
  2168. m_log.Warn("NonMesh");
  2169. #endif
  2170. return false;
  2171. }
  2172. }
  2173. }
  2174. if (pbs.ProfileHollow != 0)
  2175. iPropertiesNotSupportedDefault++;
  2176. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  2177. iPropertiesNotSupportedDefault++;
  2178. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  2179. iPropertiesNotSupportedDefault++;
  2180. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  2181. iPropertiesNotSupportedDefault++;
  2182. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  2183. iPropertiesNotSupportedDefault++;
  2184. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  2185. iPropertiesNotSupportedDefault++;
  2186. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
  2187. iPropertiesNotSupportedDefault++;
  2188. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  2189. iPropertiesNotSupportedDefault++;
  2190. // test for torus
  2191. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  2192. {
  2193. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2194. {
  2195. iPropertiesNotSupportedDefault++;
  2196. }
  2197. }
  2198. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  2199. {
  2200. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2201. {
  2202. iPropertiesNotSupportedDefault++;
  2203. }
  2204. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  2205. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2206. {
  2207. iPropertiesNotSupportedDefault++;
  2208. }
  2209. }
  2210. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  2211. {
  2212. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  2213. {
  2214. iPropertiesNotSupportedDefault++;
  2215. }
  2216. }
  2217. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  2218. {
  2219. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2220. {
  2221. iPropertiesNotSupportedDefault++;
  2222. }
  2223. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2224. {
  2225. iPropertiesNotSupportedDefault++;
  2226. }
  2227. }
  2228. if (iPropertiesNotSupportedDefault == 0)
  2229. {
  2230. #if SPAM
  2231. m_log.Warn("NonMesh");
  2232. #endif
  2233. return false;
  2234. }
  2235. #if SPAM
  2236. m_log.Debug("Mesh");
  2237. #endif
  2238. return true;
  2239. }
  2240. /// <summary>
  2241. /// Called after our prim properties are set Scale, position etc.
  2242. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  2243. /// This assures us that we have no race conditions
  2244. /// </summary>
  2245. /// <param name="prim"></param>
  2246. public override void AddPhysicsActorTaint(PhysicsActor prim)
  2247. {
  2248. if (prim is OdePrim)
  2249. {
  2250. OdePrim taintedprim = ((OdePrim) prim);
  2251. lock (_taintedPrimLock)
  2252. {
  2253. if (!(_taintedPrimH.Contains(taintedprim)))
  2254. {
  2255. //Console.WriteLine("AddPhysicsActorTaint to " + taintedprim.m_primName);
  2256. _taintedPrimH.Add(taintedprim); // HashSet for searching
  2257. _taintedPrimL.Add(taintedprim); // List for ordered readout
  2258. }
  2259. }
  2260. return;
  2261. }
  2262. else if (prim is OdeCharacter)
  2263. {
  2264. OdeCharacter taintedchar = ((OdeCharacter)prim);
  2265. lock (_taintedActors)
  2266. {
  2267. if (!(_taintedActors.Contains(taintedchar)))
  2268. {
  2269. _taintedActors.Add(taintedchar);
  2270. if (taintedchar.bad)
  2271. m_log.DebugFormat("[PHYSICS]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
  2272. }
  2273. }
  2274. }
  2275. }
  2276. /// <summary>
  2277. /// This is our main simulate loop
  2278. /// It's thread locked by a Mutex in the scene.
  2279. /// It holds Collisions, it instructs ODE to step through the physical reactions
  2280. /// It moves the objects around in memory
  2281. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  2282. /// </summary>
  2283. /// <param name="timeStep"></param>
  2284. /// <returns></returns>
  2285. public override float Simulate(float timeStep)
  2286. {
  2287. if (framecount >= int.MaxValue)
  2288. framecount = 0;
  2289. //if (m_worldOffset != Vector3.Zero)
  2290. // return 0;
  2291. framecount++;
  2292. float fps = 0;
  2293. //m_log.Info(timeStep.ToString());
  2294. step_time += timeStep;
  2295. // If We're loaded down by something else,
  2296. // or debugging with the Visual Studio project on pause
  2297. // skip a few frames to catch up gracefully.
  2298. // without shooting the physicsactors all over the place
  2299. if (step_time >= m_SkipFramesAtms)
  2300. {
  2301. // Instead of trying to catch up, it'll do 5 physics frames only
  2302. step_time = ODE_STEPSIZE;
  2303. m_physicsiterations = 5;
  2304. }
  2305. else
  2306. {
  2307. m_physicsiterations = 10;
  2308. }
  2309. if (SupportsNINJAJoints)
  2310. {
  2311. DeleteRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2312. CreateRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2313. }
  2314. lock (OdeLock)
  2315. {
  2316. // Process 10 frames if the sim is running normal..
  2317. // process 5 frames if the sim is running slow
  2318. //try
  2319. //{
  2320. //d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  2321. //}
  2322. //catch (StackOverflowException)
  2323. //{
  2324. // m_log.Error("[PHYSICS]: The operating system wasn't able to allocate enough memory for the simulation. Restarting the sim.");
  2325. // ode.drelease(world);
  2326. //base.TriggerPhysicsBasedRestart();
  2327. //}
  2328. int i = 0;
  2329. // Figure out the Frames Per Second we're going at.
  2330. //(step_time == 0.004f, there's 250 of those per second. Times the step time/step size
  2331. fps = (step_time / ODE_STEPSIZE) * 1000;
  2332. // HACK: Using a time dilation of 1.0 to debug rubberbanding issues
  2333. //m_timeDilation = Math.Min((step_time / ODE_STEPSIZE) / (0.09375f / ODE_STEPSIZE), 1.0f);
  2334. step_time = 0.09375f;
  2335. while (step_time > 0.0f)
  2336. {
  2337. //lock (ode)
  2338. //{
  2339. //if (!ode.lockquery())
  2340. //{
  2341. // ode.dlock(world);
  2342. try
  2343. {
  2344. // Insert, remove Characters
  2345. bool processedtaints = false;
  2346. lock (_taintedActors)
  2347. {
  2348. if (_taintedActors.Count > 0)
  2349. {
  2350. foreach (OdeCharacter character in _taintedActors)
  2351. {
  2352. character.ProcessTaints(timeStep);
  2353. processedtaints = true;
  2354. //character.m_collisionscore = 0;
  2355. }
  2356. if (processedtaints)
  2357. _taintedActors.Clear();
  2358. }
  2359. }
  2360. // Modify other objects in the scene.
  2361. processedtaints = false;
  2362. lock (_taintedPrimLock)
  2363. {
  2364. foreach (OdePrim prim in _taintedPrimL)
  2365. {
  2366. if (prim.m_taintremove)
  2367. {
  2368. //Console.WriteLine("Simulate calls RemovePrimThreadLocked");
  2369. RemovePrimThreadLocked(prim);
  2370. }
  2371. else
  2372. {
  2373. //Console.WriteLine("Simulate calls ProcessTaints");
  2374. prim.ProcessTaints(timeStep);
  2375. }
  2376. processedtaints = true;
  2377. prim.m_collisionscore = 0;
  2378. // This loop can block up the Heartbeat for a very long time on large regions.
  2379. // We need to let the Watchdog know that the Heartbeat is not dead
  2380. // NOTE: This is currently commented out, but if things like OAR loading are
  2381. // timing the heartbeat out we will need to uncomment it
  2382. //Watchdog.UpdateThread();
  2383. }
  2384. if (SupportsNINJAJoints)
  2385. {
  2386. // Create pending joints, if possible
  2387. // joints can only be processed after ALL bodies are processed (and exist in ODE), since creating
  2388. // a joint requires specifying the body id of both involved bodies
  2389. if (pendingJoints.Count > 0)
  2390. {
  2391. List<PhysicsJoint> successfullyProcessedPendingJoints = new List<PhysicsJoint>();
  2392. //DoJointErrorMessage(joints_connecting_actor, "taint: " + pendingJoints.Count + " pending joints");
  2393. foreach (PhysicsJoint joint in pendingJoints)
  2394. {
  2395. //DoJointErrorMessage(joint, "taint: time to create joint with parms: " + joint.RawParams);
  2396. string[] jointParams = joint.RawParams.Split(" ".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
  2397. List<IntPtr> jointBodies = new List<IntPtr>();
  2398. bool allJointBodiesAreReady = true;
  2399. foreach (string jointParam in jointParams)
  2400. {
  2401. if (jointParam == "NULL")
  2402. {
  2403. //DoJointErrorMessage(joint, "attaching NULL joint to world");
  2404. jointBodies.Add(IntPtr.Zero);
  2405. }
  2406. else
  2407. {
  2408. //DoJointErrorMessage(joint, "looking for prim name: " + jointParam);
  2409. bool foundPrim = false;
  2410. lock (_prims)
  2411. {
  2412. foreach (OdePrim prim in _prims) // FIXME: inefficient
  2413. {
  2414. if (prim.SOPName == jointParam)
  2415. {
  2416. //DoJointErrorMessage(joint, "found for prim name: " + jointParam);
  2417. if (prim.IsPhysical && prim.Body != IntPtr.Zero)
  2418. {
  2419. jointBodies.Add(prim.Body);
  2420. foundPrim = true;
  2421. break;
  2422. }
  2423. else
  2424. {
  2425. DoJointErrorMessage(joint, "prim name " + jointParam +
  2426. " exists but is not (yet) physical; deferring joint creation. " +
  2427. "IsPhysical property is " + prim.IsPhysical +
  2428. " and body is " + prim.Body);
  2429. foundPrim = false;
  2430. break;
  2431. }
  2432. }
  2433. }
  2434. }
  2435. if (foundPrim)
  2436. {
  2437. // all is fine
  2438. }
  2439. else
  2440. {
  2441. allJointBodiesAreReady = false;
  2442. break;
  2443. }
  2444. }
  2445. }
  2446. if (allJointBodiesAreReady)
  2447. {
  2448. //DoJointErrorMessage(joint, "allJointBodiesAreReady for " + joint.ObjectNameInScene + " with parms " + joint.RawParams);
  2449. if (jointBodies[0] == jointBodies[1])
  2450. {
  2451. DoJointErrorMessage(joint, "ERROR: joint cannot be created; the joint bodies are the same, body1==body2. Raw body is " + jointBodies[0] + ". raw parms: " + joint.RawParams);
  2452. }
  2453. else
  2454. {
  2455. switch (joint.Type)
  2456. {
  2457. case PhysicsJointType.Ball:
  2458. {
  2459. IntPtr odeJoint;
  2460. //DoJointErrorMessage(joint, "ODE creating ball joint ");
  2461. odeJoint = d.JointCreateBall(world, IntPtr.Zero);
  2462. //DoJointErrorMessage(joint, "ODE attaching ball joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2463. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2464. //DoJointErrorMessage(joint, "ODE setting ball anchor: " + odeJoint + " to vec:" + joint.Position);
  2465. d.JointSetBallAnchor(odeJoint,
  2466. joint.Position.X,
  2467. joint.Position.Y,
  2468. joint.Position.Z);
  2469. //DoJointErrorMessage(joint, "ODE joint setting OK");
  2470. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b0: ");
  2471. //DoJointErrorMessage(joint, "" + (jointBodies[0] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[0]) : "fixed environment"));
  2472. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b1: ");
  2473. //DoJointErrorMessage(joint, "" + (jointBodies[1] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[1]) : "fixed environment"));
  2474. if (joint is OdePhysicsJoint)
  2475. {
  2476. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2477. }
  2478. else
  2479. {
  2480. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2481. }
  2482. }
  2483. break;
  2484. case PhysicsJointType.Hinge:
  2485. {
  2486. IntPtr odeJoint;
  2487. //DoJointErrorMessage(joint, "ODE creating hinge joint ");
  2488. odeJoint = d.JointCreateHinge(world, IntPtr.Zero);
  2489. //DoJointErrorMessage(joint, "ODE attaching hinge joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2490. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2491. //DoJointErrorMessage(joint, "ODE setting hinge anchor: " + odeJoint + " to vec:" + joint.Position);
  2492. d.JointSetHingeAnchor(odeJoint,
  2493. joint.Position.X,
  2494. joint.Position.Y,
  2495. joint.Position.Z);
  2496. // We use the orientation of the x-axis of the joint's coordinate frame
  2497. // as the axis for the hinge.
  2498. // Therefore, we must get the joint's coordinate frame based on the
  2499. // joint.Rotation field, which originates from the orientation of the
  2500. // joint's proxy object in the scene.
  2501. // The joint's coordinate frame is defined as the transformation matrix
  2502. // that converts a vector from joint-local coordinates into world coordinates.
  2503. // World coordinates are defined as the XYZ coordinate system of the sim,
  2504. // as shown in the top status-bar of the viewer.
  2505. // Once we have the joint's coordinate frame, we extract its X axis (AtAxis)
  2506. // and use that as the hinge axis.
  2507. //joint.Rotation.Normalize();
  2508. Matrix4 proxyFrame = Matrix4.CreateFromQuaternion(joint.Rotation);
  2509. // Now extract the X axis of the joint's coordinate frame.
  2510. // Do not try to use proxyFrame.AtAxis or you will become mired in the
  2511. // tar pit of transposed, inverted, and generally messed-up orientations.
  2512. // (In other words, Matrix4.AtAxis() is borked.)
  2513. // Vector3 jointAxis = proxyFrame.AtAxis; <--- this path leadeth to madness
  2514. // Instead, compute the X axis of the coordinate frame by transforming
  2515. // the (1,0,0) vector. At least that works.
  2516. //m_log.Debug("PHY: making axis: complete matrix is " + proxyFrame);
  2517. Vector3 jointAxis = Vector3.Transform(Vector3.UnitX, proxyFrame);
  2518. //m_log.Debug("PHY: making axis: hinge joint axis is " + jointAxis);
  2519. //DoJointErrorMessage(joint, "ODE setting hinge axis: " + odeJoint + " to vec:" + jointAxis);
  2520. d.JointSetHingeAxis(odeJoint,
  2521. jointAxis.X,
  2522. jointAxis.Y,
  2523. jointAxis.Z);
  2524. //d.JointSetHingeParam(odeJoint, (int)dParam.CFM, 0.1f);
  2525. if (joint is OdePhysicsJoint)
  2526. {
  2527. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2528. }
  2529. else
  2530. {
  2531. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2532. }
  2533. }
  2534. break;
  2535. }
  2536. successfullyProcessedPendingJoints.Add(joint);
  2537. }
  2538. }
  2539. else
  2540. {
  2541. DoJointErrorMessage(joint, "joint could not yet be created; still pending");
  2542. }
  2543. }
  2544. foreach (PhysicsJoint successfullyProcessedJoint in successfullyProcessedPendingJoints)
  2545. {
  2546. //DoJointErrorMessage(successfullyProcessedJoint, "finalizing succesfully procsssed joint " + successfullyProcessedJoint.ObjectNameInScene + " parms " + successfullyProcessedJoint.RawParams);
  2547. //DoJointErrorMessage(successfullyProcessedJoint, "removing from pending");
  2548. InternalRemovePendingJoint(successfullyProcessedJoint);
  2549. //DoJointErrorMessage(successfullyProcessedJoint, "adding to active");
  2550. InternalAddActiveJoint(successfullyProcessedJoint);
  2551. //DoJointErrorMessage(successfullyProcessedJoint, "done");
  2552. }
  2553. }
  2554. }
  2555. if (processedtaints)
  2556. //Console.WriteLine("Simulate calls Clear of _taintedPrim list");
  2557. _taintedPrimH.Clear();
  2558. _taintedPrimL.Clear();
  2559. }
  2560. // Move characters
  2561. lock (_characters)
  2562. {
  2563. List<OdeCharacter> defects = new List<OdeCharacter>();
  2564. foreach (OdeCharacter actor in _characters)
  2565. {
  2566. if (actor != null)
  2567. actor.Move(timeStep, defects);
  2568. }
  2569. if (0 != defects.Count)
  2570. {
  2571. foreach (OdeCharacter defect in defects)
  2572. {
  2573. RemoveCharacter(defect);
  2574. }
  2575. }
  2576. }
  2577. // Move other active objects
  2578. lock (_activeprims)
  2579. {
  2580. foreach (OdePrim prim in _activeprims)
  2581. {
  2582. prim.m_collisionscore = 0;
  2583. prim.Move(timeStep);
  2584. }
  2585. }
  2586. //if ((framecount % m_randomizeWater) == 0)
  2587. // randomizeWater(waterlevel);
  2588. //int RayCastTimeMS = m_rayCastManager.ProcessQueuedRequests();
  2589. m_rayCastManager.ProcessQueuedRequests();
  2590. collision_optimized(timeStep);
  2591. lock (_collisionEventPrim)
  2592. {
  2593. foreach (PhysicsActor obj in _collisionEventPrim)
  2594. {
  2595. if (obj == null)
  2596. continue;
  2597. switch ((ActorTypes)obj.PhysicsActorType)
  2598. {
  2599. case ActorTypes.Agent:
  2600. OdeCharacter cobj = (OdeCharacter)obj;
  2601. cobj.AddCollisionFrameTime(100);
  2602. cobj.SendCollisions();
  2603. break;
  2604. case ActorTypes.Prim:
  2605. OdePrim pobj = (OdePrim)obj;
  2606. pobj.SendCollisions();
  2607. break;
  2608. }
  2609. }
  2610. }
  2611. //if (m_global_contactcount > 5)
  2612. //{
  2613. // m_log.DebugFormat("[PHYSICS]: Contacts:{0}", m_global_contactcount);
  2614. //}
  2615. m_global_contactcount = 0;
  2616. d.WorldQuickStep(world, ODE_STEPSIZE);
  2617. d.JointGroupEmpty(contactgroup);
  2618. //ode.dunlock(world);
  2619. }
  2620. catch (Exception e)
  2621. {
  2622. m_log.ErrorFormat("[PHYSICS]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  2623. ode.dunlock(world);
  2624. }
  2625. step_time -= ODE_STEPSIZE;
  2626. i++;
  2627. //}
  2628. //else
  2629. //{
  2630. //fps = 0;
  2631. //}
  2632. //}
  2633. }
  2634. lock (_characters)
  2635. {
  2636. foreach (OdeCharacter actor in _characters)
  2637. {
  2638. if (actor != null)
  2639. {
  2640. if (actor.bad)
  2641. m_log.WarnFormat("[PHYSICS]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  2642. actor.UpdatePositionAndVelocity();
  2643. }
  2644. }
  2645. }
  2646. lock (_badCharacter)
  2647. {
  2648. if (_badCharacter.Count > 0)
  2649. {
  2650. foreach (OdeCharacter chr in _badCharacter)
  2651. {
  2652. RemoveCharacter(chr);
  2653. }
  2654. _badCharacter.Clear();
  2655. }
  2656. }
  2657. lock (_activeprims)
  2658. {
  2659. //if (timeStep < 0.2f)
  2660. {
  2661. foreach (OdePrim actor in _activeprims)
  2662. {
  2663. if (actor.IsPhysical && (d.BodyIsEnabled(actor.Body) || !actor._zeroFlag))
  2664. {
  2665. actor.UpdatePositionAndVelocity();
  2666. if (SupportsNINJAJoints)
  2667. {
  2668. // If an actor moved, move its joint proxy objects as well.
  2669. // There seems to be an event PhysicsActor.OnPositionUpdate that could be used
  2670. // for this purpose but it is never called! So we just do the joint
  2671. // movement code here.
  2672. if (actor.SOPName != null &&
  2673. joints_connecting_actor.ContainsKey(actor.SOPName) &&
  2674. joints_connecting_actor[actor.SOPName] != null &&
  2675. joints_connecting_actor[actor.SOPName].Count > 0)
  2676. {
  2677. foreach (PhysicsJoint affectedJoint in joints_connecting_actor[actor.SOPName])
  2678. {
  2679. if (affectedJoint.IsInPhysicsEngine)
  2680. {
  2681. DoJointMoved(affectedJoint);
  2682. }
  2683. else
  2684. {
  2685. DoJointErrorMessage(affectedJoint, "a body connected to a joint was moved, but the joint doesn't exist yet! this will lead to joint error. joint was: " + affectedJoint.ObjectNameInScene + " parms:" + affectedJoint.RawParams);
  2686. }
  2687. }
  2688. }
  2689. }
  2690. }
  2691. }
  2692. }
  2693. }
  2694. //DumpJointInfo();
  2695. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  2696. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  2697. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  2698. if (physics_logging && (physics_logging_interval>0) && (framecount % physics_logging_interval == 0))
  2699. {
  2700. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  2701. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  2702. if (physics_logging_append_existing_logfile)
  2703. {
  2704. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  2705. TextWriter fwriter = File.AppendText(fname);
  2706. fwriter.WriteLine(header);
  2707. fwriter.Close();
  2708. }
  2709. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  2710. }
  2711. }
  2712. return fps;
  2713. }
  2714. public override void GetResults()
  2715. {
  2716. }
  2717. public override bool IsThreaded
  2718. {
  2719. // for now we won't be multithreaded
  2720. get { return (false); }
  2721. }
  2722. #region ODE Specific Terrain Fixes
  2723. public float[] ResizeTerrain512NearestNeighbour(float[] heightMap)
  2724. {
  2725. float[] returnarr = new float[262144];
  2726. float[,] resultarr = new float[(int)WorldExtents.X, (int)WorldExtents.Y];
  2727. // Filling out the array into its multi-dimensional components
  2728. for (int y = 0; y < WorldExtents.Y; y++)
  2729. {
  2730. for (int x = 0; x < WorldExtents.X; x++)
  2731. {
  2732. resultarr[y, x] = heightMap[y * (int)WorldExtents.Y + x];
  2733. }
  2734. }
  2735. // Resize using Nearest Neighbour
  2736. // This particular way is quick but it only works on a multiple of the original
  2737. // The idea behind this method can be described with the following diagrams
  2738. // second pass and third pass happen in the same loop really.. just separated
  2739. // them to show what this does.
  2740. // First Pass
  2741. // ResultArr:
  2742. // 1,1,1,1,1,1
  2743. // 1,1,1,1,1,1
  2744. // 1,1,1,1,1,1
  2745. // 1,1,1,1,1,1
  2746. // 1,1,1,1,1,1
  2747. // 1,1,1,1,1,1
  2748. // Second Pass
  2749. // ResultArr2:
  2750. // 1,,1,,1,,1,,1,,1,
  2751. // ,,,,,,,,,,
  2752. // 1,,1,,1,,1,,1,,1,
  2753. // ,,,,,,,,,,
  2754. // 1,,1,,1,,1,,1,,1,
  2755. // ,,,,,,,,,,
  2756. // 1,,1,,1,,1,,1,,1,
  2757. // ,,,,,,,,,,
  2758. // 1,,1,,1,,1,,1,,1,
  2759. // ,,,,,,,,,,
  2760. // 1,,1,,1,,1,,1,,1,
  2761. // Third pass fills in the blanks
  2762. // ResultArr2:
  2763. // 1,1,1,1,1,1,1,1,1,1,1,1
  2764. // 1,1,1,1,1,1,1,1,1,1,1,1
  2765. // 1,1,1,1,1,1,1,1,1,1,1,1
  2766. // 1,1,1,1,1,1,1,1,1,1,1,1
  2767. // 1,1,1,1,1,1,1,1,1,1,1,1
  2768. // 1,1,1,1,1,1,1,1,1,1,1,1
  2769. // 1,1,1,1,1,1,1,1,1,1,1,1
  2770. // 1,1,1,1,1,1,1,1,1,1,1,1
  2771. // 1,1,1,1,1,1,1,1,1,1,1,1
  2772. // 1,1,1,1,1,1,1,1,1,1,1,1
  2773. // 1,1,1,1,1,1,1,1,1,1,1,1
  2774. // X,Y = .
  2775. // X+1,y = ^
  2776. // X,Y+1 = *
  2777. // X+1,Y+1 = #
  2778. // Filling in like this;
  2779. // .*
  2780. // ^#
  2781. // 1st .
  2782. // 2nd *
  2783. // 3rd ^
  2784. // 4th #
  2785. // on single loop.
  2786. float[,] resultarr2 = new float[512, 512];
  2787. for (int y = 0; y < WorldExtents.Y; y++)
  2788. {
  2789. for (int x = 0; x < WorldExtents.X; x++)
  2790. {
  2791. resultarr2[y * 2, x * 2] = resultarr[y, x];
  2792. if (y < WorldExtents.Y)
  2793. {
  2794. resultarr2[(y * 2) + 1, x * 2] = resultarr[y, x];
  2795. }
  2796. if (x < WorldExtents.X)
  2797. {
  2798. resultarr2[y * 2, (x * 2) + 1] = resultarr[y, x];
  2799. }
  2800. if (x < WorldExtents.X && y < WorldExtents.Y)
  2801. {
  2802. resultarr2[(y * 2) + 1, (x * 2) + 1] = resultarr[y, x];
  2803. }
  2804. }
  2805. }
  2806. //Flatten out the array
  2807. int i = 0;
  2808. for (int y = 0; y < 512; y++)
  2809. {
  2810. for (int x = 0; x < 512; x++)
  2811. {
  2812. if (resultarr2[y, x] <= 0)
  2813. returnarr[i] = 0.0000001f;
  2814. else
  2815. returnarr[i] = resultarr2[y, x];
  2816. i++;
  2817. }
  2818. }
  2819. return returnarr;
  2820. }
  2821. public float[] ResizeTerrain512Interpolation(float[] heightMap)
  2822. {
  2823. float[] returnarr = new float[262144];
  2824. float[,] resultarr = new float[512,512];
  2825. // Filling out the array into its multi-dimensional components
  2826. for (int y = 0; y < 256; y++)
  2827. {
  2828. for (int x = 0; x < 256; x++)
  2829. {
  2830. resultarr[y, x] = heightMap[y * 256 + x];
  2831. }
  2832. }
  2833. // Resize using interpolation
  2834. // This particular way is quick but it only works on a multiple of the original
  2835. // The idea behind this method can be described with the following diagrams
  2836. // second pass and third pass happen in the same loop really.. just separated
  2837. // them to show what this does.
  2838. // First Pass
  2839. // ResultArr:
  2840. // 1,1,1,1,1,1
  2841. // 1,1,1,1,1,1
  2842. // 1,1,1,1,1,1
  2843. // 1,1,1,1,1,1
  2844. // 1,1,1,1,1,1
  2845. // 1,1,1,1,1,1
  2846. // Second Pass
  2847. // ResultArr2:
  2848. // 1,,1,,1,,1,,1,,1,
  2849. // ,,,,,,,,,,
  2850. // 1,,1,,1,,1,,1,,1,
  2851. // ,,,,,,,,,,
  2852. // 1,,1,,1,,1,,1,,1,
  2853. // ,,,,,,,,,,
  2854. // 1,,1,,1,,1,,1,,1,
  2855. // ,,,,,,,,,,
  2856. // 1,,1,,1,,1,,1,,1,
  2857. // ,,,,,,,,,,
  2858. // 1,,1,,1,,1,,1,,1,
  2859. // Third pass fills in the blanks
  2860. // ResultArr2:
  2861. // 1,1,1,1,1,1,1,1,1,1,1,1
  2862. // 1,1,1,1,1,1,1,1,1,1,1,1
  2863. // 1,1,1,1,1,1,1,1,1,1,1,1
  2864. // 1,1,1,1,1,1,1,1,1,1,1,1
  2865. // 1,1,1,1,1,1,1,1,1,1,1,1
  2866. // 1,1,1,1,1,1,1,1,1,1,1,1
  2867. // 1,1,1,1,1,1,1,1,1,1,1,1
  2868. // 1,1,1,1,1,1,1,1,1,1,1,1
  2869. // 1,1,1,1,1,1,1,1,1,1,1,1
  2870. // 1,1,1,1,1,1,1,1,1,1,1,1
  2871. // 1,1,1,1,1,1,1,1,1,1,1,1
  2872. // X,Y = .
  2873. // X+1,y = ^
  2874. // X,Y+1 = *
  2875. // X+1,Y+1 = #
  2876. // Filling in like this;
  2877. // .*
  2878. // ^#
  2879. // 1st .
  2880. // 2nd *
  2881. // 3rd ^
  2882. // 4th #
  2883. // on single loop.
  2884. float[,] resultarr2 = new float[512,512];
  2885. for (int y = 0; y < (int)Constants.RegionSize; y++)
  2886. {
  2887. for (int x = 0; x < (int)Constants.RegionSize; x++)
  2888. {
  2889. resultarr2[y*2, x*2] = resultarr[y, x];
  2890. if (y < (int)Constants.RegionSize)
  2891. {
  2892. if (y + 1 < (int)Constants.RegionSize)
  2893. {
  2894. if (x + 1 < (int)Constants.RegionSize)
  2895. {
  2896. resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x] +
  2897. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  2898. }
  2899. else
  2900. {
  2901. resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x])/2);
  2902. }
  2903. }
  2904. else
  2905. {
  2906. resultarr2[(y*2) + 1, x*2] = resultarr[y, x];
  2907. }
  2908. }
  2909. if (x < (int)Constants.RegionSize)
  2910. {
  2911. if (x + 1 < (int)Constants.RegionSize)
  2912. {
  2913. if (y + 1 < (int)Constants.RegionSize)
  2914. {
  2915. resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
  2916. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  2917. }
  2918. else
  2919. {
  2920. resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y, x + 1])/2);
  2921. }
  2922. }
  2923. else
  2924. {
  2925. resultarr2[y*2, (x*2) + 1] = resultarr[y, x];
  2926. }
  2927. }
  2928. if (x < (int)Constants.RegionSize && y < (int)Constants.RegionSize)
  2929. {
  2930. if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize))
  2931. {
  2932. resultarr2[(y*2) + 1, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
  2933. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  2934. }
  2935. else
  2936. {
  2937. resultarr2[(y*2) + 1, (x*2) + 1] = resultarr[y, x];
  2938. }
  2939. }
  2940. }
  2941. }
  2942. //Flatten out the array
  2943. int i = 0;
  2944. for (int y = 0; y < 512; y++)
  2945. {
  2946. for (int x = 0; x < 512; x++)
  2947. {
  2948. if (Single.IsNaN(resultarr2[y, x]) || Single.IsInfinity(resultarr2[y, x]))
  2949. {
  2950. m_log.Warn("[PHYSICS]: Non finite heightfield element detected. Setting it to 0");
  2951. resultarr2[y, x] = 0;
  2952. }
  2953. returnarr[i] = resultarr2[y, x];
  2954. i++;
  2955. }
  2956. }
  2957. return returnarr;
  2958. }
  2959. #endregion
  2960. public override void SetTerrain(float[] heightMap)
  2961. {
  2962. if (m_worldOffset != Vector3.Zero && m_parentScene != null)
  2963. {
  2964. if (m_parentScene is OdeScene)
  2965. {
  2966. ((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
  2967. }
  2968. }
  2969. else
  2970. {
  2971. SetTerrain(heightMap, m_worldOffset);
  2972. }
  2973. }
  2974. public void SetTerrain(float[] heightMap, Vector3 pOffset)
  2975. {
  2976. // this._heightmap[i] = (double)heightMap[i];
  2977. // dbm (danx0r) -- creating a buffer zone of one extra sample all around
  2978. //_origheightmap = heightMap;
  2979. float[] _heightmap;
  2980. // zero out a heightmap array float array (single dimension [flattened]))
  2981. //if ((int)Constants.RegionSize == 256)
  2982. // _heightmap = new float[514 * 514];
  2983. //else
  2984. _heightmap = new float[(((int)Constants.RegionSize + 2) * ((int)Constants.RegionSize + 2))];
  2985. uint heightmapWidth = Constants.RegionSize + 1;
  2986. uint heightmapHeight = Constants.RegionSize + 1;
  2987. uint heightmapWidthSamples;
  2988. uint heightmapHeightSamples;
  2989. //if (((int)Constants.RegionSize) == 256)
  2990. //{
  2991. // heightmapWidthSamples = 2 * (uint)Constants.RegionSize + 2;
  2992. // heightmapHeightSamples = 2 * (uint)Constants.RegionSize + 2;
  2993. // heightmapWidth++;
  2994. // heightmapHeight++;
  2995. //}
  2996. //else
  2997. //{
  2998. heightmapWidthSamples = (uint)Constants.RegionSize + 1;
  2999. heightmapHeightSamples = (uint)Constants.RegionSize + 1;
  3000. //}
  3001. const float scale = 1.0f;
  3002. const float offset = 0.0f;
  3003. const float thickness = 0.2f;
  3004. const int wrap = 0;
  3005. int regionsize = (int) Constants.RegionSize + 2;
  3006. //Double resolution
  3007. //if (((int)Constants.RegionSize) == 256)
  3008. // heightMap = ResizeTerrain512Interpolation(heightMap);
  3009. // if (((int)Constants.RegionSize) == 256 && (int)Constants.RegionSize == 256)
  3010. // regionsize = 512;
  3011. float hfmin = 2000;
  3012. float hfmax = -2000;
  3013. for (int x = 0; x < heightmapWidthSamples; x++)
  3014. {
  3015. for (int y = 0; y < heightmapHeightSamples; y++)
  3016. {
  3017. int xx = Util.Clip(x - 1, 0, regionsize - 1);
  3018. int yy = Util.Clip(y - 1, 0, regionsize - 1);
  3019. float val= heightMap[yy * (int)Constants.RegionSize + xx];
  3020. _heightmap[x * ((int)Constants.RegionSize + 2) + y] = val;
  3021. hfmin = (val < hfmin) ? val : hfmin;
  3022. hfmax = (val > hfmax) ? val : hfmax;
  3023. }
  3024. }
  3025. lock (OdeLock)
  3026. {
  3027. IntPtr GroundGeom = IntPtr.Zero;
  3028. if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
  3029. {
  3030. RegionTerrain.Remove(pOffset);
  3031. if (GroundGeom != IntPtr.Zero)
  3032. {
  3033. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  3034. {
  3035. TerrainHeightFieldHeights.Remove(GroundGeom);
  3036. }
  3037. d.SpaceRemove(space, GroundGeom);
  3038. d.GeomDestroy(GroundGeom);
  3039. }
  3040. }
  3041. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3042. d.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmap, 0, heightmapWidth + 1, heightmapHeight + 1,
  3043. (int)heightmapWidthSamples + 1, (int)heightmapHeightSamples + 1, scale,
  3044. offset, thickness, wrap);
  3045. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  3046. GroundGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3047. if (GroundGeom != IntPtr.Zero)
  3048. {
  3049. d.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
  3050. d.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
  3051. }
  3052. geom_name_map[GroundGeom] = "Terrain";
  3053. d.Matrix3 R = new d.Matrix3();
  3054. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3055. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3056. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3057. q1 = q1 * q2;
  3058. //q1 = q1 * q3;
  3059. Vector3 v3;
  3060. float angle;
  3061. q1.GetAxisAngle(out v3, out angle);
  3062. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3063. d.GeomSetRotation(GroundGeom, ref R);
  3064. d.GeomSetPosition(GroundGeom, (pOffset.X + ((int)Constants.RegionSize * 0.5f)) - 1, (pOffset.Y + ((int)Constants.RegionSize * 0.5f)) - 1, 0);
  3065. IntPtr testGround = IntPtr.Zero;
  3066. if (RegionTerrain.TryGetValue(pOffset, out testGround))
  3067. {
  3068. RegionTerrain.Remove(pOffset);
  3069. }
  3070. RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
  3071. TerrainHeightFieldHeights.Add(GroundGeom,_heightmap);
  3072. }
  3073. }
  3074. public override void DeleteTerrain()
  3075. {
  3076. }
  3077. public float GetWaterLevel()
  3078. {
  3079. return waterlevel;
  3080. }
  3081. public override bool SupportsCombining()
  3082. {
  3083. return true;
  3084. }
  3085. public override void UnCombine(PhysicsScene pScene)
  3086. {
  3087. IntPtr localGround = IntPtr.Zero;
  3088. // float[] localHeightfield;
  3089. bool proceed = false;
  3090. List<IntPtr> geomDestroyList = new List<IntPtr>();
  3091. lock (OdeLock)
  3092. {
  3093. if (RegionTerrain.TryGetValue(Vector3.Zero, out localGround))
  3094. {
  3095. foreach (IntPtr geom in TerrainHeightFieldHeights.Keys)
  3096. {
  3097. if (geom == localGround)
  3098. {
  3099. // localHeightfield = TerrainHeightFieldHeights[geom];
  3100. proceed = true;
  3101. }
  3102. else
  3103. {
  3104. geomDestroyList.Add(geom);
  3105. }
  3106. }
  3107. if (proceed)
  3108. {
  3109. m_worldOffset = Vector3.Zero;
  3110. WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  3111. m_parentScene = null;
  3112. foreach (IntPtr g in geomDestroyList)
  3113. {
  3114. // removingHeightField needs to be done or the garbage collector will
  3115. // collect the terrain data before we tell ODE to destroy it causing
  3116. // memory corruption
  3117. if (TerrainHeightFieldHeights.ContainsKey(g))
  3118. {
  3119. // float[] removingHeightField = TerrainHeightFieldHeights[g];
  3120. TerrainHeightFieldHeights.Remove(g);
  3121. if (RegionTerrain.ContainsKey(g))
  3122. {
  3123. RegionTerrain.Remove(g);
  3124. }
  3125. d.GeomDestroy(g);
  3126. //removingHeightField = new float[0];
  3127. }
  3128. }
  3129. }
  3130. else
  3131. {
  3132. m_log.Warn("[PHYSICS]: Couldn't proceed with UnCombine. Region has inconsistant data.");
  3133. }
  3134. }
  3135. }
  3136. }
  3137. public override void SetWaterLevel(float baseheight)
  3138. {
  3139. waterlevel = baseheight;
  3140. randomizeWater(waterlevel);
  3141. }
  3142. public void randomizeWater(float baseheight)
  3143. {
  3144. const uint heightmapWidth = m_regionWidth + 2;
  3145. const uint heightmapHeight = m_regionHeight + 2;
  3146. const uint heightmapWidthSamples = m_regionWidth + 2;
  3147. const uint heightmapHeightSamples = m_regionHeight + 2;
  3148. const float scale = 1.0f;
  3149. const float offset = 0.0f;
  3150. const float thickness = 2.9f;
  3151. const int wrap = 0;
  3152. for (int i = 0; i < (258 * 258); i++)
  3153. {
  3154. _watermap[i] = (baseheight-0.1f) + ((float)fluidRandomizer.Next(1,9) / 10f);
  3155. // m_log.Info((baseheight - 0.1f) + ((float)fluidRandomizer.Next(1, 9) / 10f));
  3156. }
  3157. lock (OdeLock)
  3158. {
  3159. if (WaterGeom != IntPtr.Zero)
  3160. {
  3161. d.SpaceRemove(space, WaterGeom);
  3162. }
  3163. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3164. d.GeomHeightfieldDataBuildSingle(HeightmapData, _watermap, 0, heightmapWidth, heightmapHeight,
  3165. (int)heightmapWidthSamples, (int)heightmapHeightSamples, scale,
  3166. offset, thickness, wrap);
  3167. d.GeomHeightfieldDataSetBounds(HeightmapData, m_regionWidth, m_regionHeight);
  3168. WaterGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3169. if (WaterGeom != IntPtr.Zero)
  3170. {
  3171. d.GeomSetCategoryBits(WaterGeom, (int)(CollisionCategories.Water));
  3172. d.GeomSetCollideBits(WaterGeom, (int)(CollisionCategories.Space));
  3173. }
  3174. geom_name_map[WaterGeom] = "Water";
  3175. d.Matrix3 R = new d.Matrix3();
  3176. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3177. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3178. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3179. q1 = q1 * q2;
  3180. //q1 = q1 * q3;
  3181. Vector3 v3;
  3182. float angle;
  3183. q1.GetAxisAngle(out v3, out angle);
  3184. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3185. d.GeomSetRotation(WaterGeom, ref R);
  3186. d.GeomSetPosition(WaterGeom, 128, 128, 0);
  3187. }
  3188. }
  3189. public override void Dispose()
  3190. {
  3191. m_rayCastManager.Dispose();
  3192. m_rayCastManager = null;
  3193. lock (OdeLock)
  3194. {
  3195. lock (_prims)
  3196. {
  3197. foreach (OdePrim prm in _prims)
  3198. {
  3199. RemovePrim(prm);
  3200. }
  3201. }
  3202. //foreach (OdeCharacter act in _characters)
  3203. //{
  3204. //RemoveAvatar(act);
  3205. //}
  3206. d.WorldDestroy(world);
  3207. //d.CloseODE();
  3208. }
  3209. }
  3210. public override Dictionary<uint, float> GetTopColliders()
  3211. {
  3212. Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
  3213. int cnt = 0;
  3214. lock (_prims)
  3215. {
  3216. foreach (OdePrim prm in _prims)
  3217. {
  3218. if (prm.CollisionScore > 0)
  3219. {
  3220. returncolliders.Add(prm.m_localID, prm.CollisionScore);
  3221. cnt++;
  3222. prm.CollisionScore = 0f;
  3223. if (cnt > 25)
  3224. {
  3225. break;
  3226. }
  3227. }
  3228. }
  3229. }
  3230. return returncolliders;
  3231. }
  3232. public override bool SupportsRayCast()
  3233. {
  3234. return true;
  3235. }
  3236. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  3237. {
  3238. if (retMethod != null)
  3239. {
  3240. m_rayCastManager.QueueRequest(position, direction, length, retMethod);
  3241. }
  3242. }
  3243. #if USE_DRAWSTUFF
  3244. // Keyboard callback
  3245. public void command(int cmd)
  3246. {
  3247. IntPtr geom;
  3248. d.Mass mass;
  3249. d.Vector3 sides = new d.Vector3(d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f);
  3250. Char ch = Char.ToLower((Char)cmd);
  3251. switch ((Char)ch)
  3252. {
  3253. case 'w':
  3254. try
  3255. {
  3256. Vector3 rotate = (new Vector3(1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
  3257. xyz.X += rotate.X; xyz.Y += rotate.Y; xyz.Z += rotate.Z;
  3258. ds.SetViewpoint(ref xyz, ref hpr);
  3259. }
  3260. catch (ArgumentException)
  3261. { hpr.X = 0; }
  3262. break;
  3263. case 'a':
  3264. hpr.X++;
  3265. ds.SetViewpoint(ref xyz, ref hpr);
  3266. break;
  3267. case 's':
  3268. try
  3269. {
  3270. Vector3 rotate2 = (new Vector3(-1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
  3271. xyz.X += rotate2.X; xyz.Y += rotate2.Y; xyz.Z += rotate2.Z;
  3272. ds.SetViewpoint(ref xyz, ref hpr);
  3273. }
  3274. catch (ArgumentException)
  3275. { hpr.X = 0; }
  3276. break;
  3277. case 'd':
  3278. hpr.X--;
  3279. ds.SetViewpoint(ref xyz, ref hpr);
  3280. break;
  3281. case 'r':
  3282. xyz.Z++;
  3283. ds.SetViewpoint(ref xyz, ref hpr);
  3284. break;
  3285. case 'f':
  3286. xyz.Z--;
  3287. ds.SetViewpoint(ref xyz, ref hpr);
  3288. break;
  3289. case 'e':
  3290. xyz.Y++;
  3291. ds.SetViewpoint(ref xyz, ref hpr);
  3292. break;
  3293. case 'q':
  3294. xyz.Y--;
  3295. ds.SetViewpoint(ref xyz, ref hpr);
  3296. break;
  3297. }
  3298. }
  3299. public void step(int pause)
  3300. {
  3301. ds.SetColor(1.0f, 1.0f, 0.0f);
  3302. ds.SetTexture(ds.Texture.Wood);
  3303. lock (_prims)
  3304. {
  3305. foreach (OdePrim prm in _prims)
  3306. {
  3307. //IntPtr body = d.GeomGetBody(prm.prim_geom);
  3308. if (prm.prim_geom != IntPtr.Zero)
  3309. {
  3310. d.Vector3 pos;
  3311. d.GeomCopyPosition(prm.prim_geom, out pos);
  3312. //d.BodyCopyPosition(body, out pos);
  3313. d.Matrix3 R;
  3314. d.GeomCopyRotation(prm.prim_geom, out R);
  3315. //d.BodyCopyRotation(body, out R);
  3316. d.Vector3 sides = new d.Vector3();
  3317. sides.X = prm.Size.X;
  3318. sides.Y = prm.Size.Y;
  3319. sides.Z = prm.Size.Z;
  3320. ds.DrawBox(ref pos, ref R, ref sides);
  3321. }
  3322. }
  3323. }
  3324. ds.SetColor(1.0f, 0.0f, 0.0f);
  3325. lock (_characters)
  3326. {
  3327. foreach (OdeCharacter chr in _characters)
  3328. {
  3329. if (chr.Shell != IntPtr.Zero)
  3330. {
  3331. IntPtr body = d.GeomGetBody(chr.Shell);
  3332. d.Vector3 pos;
  3333. d.GeomCopyPosition(chr.Shell, out pos);
  3334. //d.BodyCopyPosition(body, out pos);
  3335. d.Matrix3 R;
  3336. d.GeomCopyRotation(chr.Shell, out R);
  3337. //d.BodyCopyRotation(body, out R);
  3338. ds.DrawCapsule(ref pos, ref R, chr.Size.Z, 0.35f);
  3339. d.Vector3 sides = new d.Vector3();
  3340. sides.X = 0.5f;
  3341. sides.Y = 0.5f;
  3342. sides.Z = 0.5f;
  3343. ds.DrawBox(ref pos, ref R, ref sides);
  3344. }
  3345. }
  3346. }
  3347. }
  3348. public void start(int unused)
  3349. {
  3350. ds.SetViewpoint(ref xyz, ref hpr);
  3351. }
  3352. #endif
  3353. }
  3354. }