OdePlugin.cs 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865
  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. mesh = mesher.CreateMesh(primName, pbs, size, 32f, isPhysical);
  1498. result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical);
  1499. return result;
  1500. }
  1501. public override float TimeDilation
  1502. {
  1503. get { return m_timeDilation; }
  1504. }
  1505. public override bool SupportsNINJAJoints
  1506. {
  1507. get { return m_NINJA_physics_joints_enabled; }
  1508. }
  1509. // internal utility function: must be called within a lock (OdeLock)
  1510. private void InternalAddActiveJoint(PhysicsJoint joint)
  1511. {
  1512. activeJoints.Add(joint);
  1513. SOPName_to_activeJoint.Add(joint.ObjectNameInScene, joint);
  1514. }
  1515. // internal utility function: must be called within a lock (OdeLock)
  1516. private void InternalAddPendingJoint(OdePhysicsJoint joint)
  1517. {
  1518. pendingJoints.Add(joint);
  1519. SOPName_to_pendingJoint.Add(joint.ObjectNameInScene, joint);
  1520. }
  1521. // internal utility function: must be called within a lock (OdeLock)
  1522. private void InternalRemovePendingJoint(PhysicsJoint joint)
  1523. {
  1524. pendingJoints.Remove(joint);
  1525. SOPName_to_pendingJoint.Remove(joint.ObjectNameInScene);
  1526. }
  1527. // internal utility function: must be called within a lock (OdeLock)
  1528. private void InternalRemoveActiveJoint(PhysicsJoint joint)
  1529. {
  1530. activeJoints.Remove(joint);
  1531. SOPName_to_activeJoint.Remove(joint.ObjectNameInScene);
  1532. }
  1533. public override void DumpJointInfo()
  1534. {
  1535. string hdr = "[NINJA] JOINTINFO: ";
  1536. foreach (PhysicsJoint j in pendingJoints)
  1537. {
  1538. m_log.Debug(hdr + " pending joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1539. }
  1540. m_log.Debug(hdr + pendingJoints.Count + " total pending joints");
  1541. foreach (string jointName in SOPName_to_pendingJoint.Keys)
  1542. {
  1543. m_log.Debug(hdr + " pending joints dict contains Name: " + jointName);
  1544. }
  1545. m_log.Debug(hdr + SOPName_to_pendingJoint.Keys.Count + " total pending joints dict entries");
  1546. foreach (PhysicsJoint j in activeJoints)
  1547. {
  1548. m_log.Debug(hdr + " active joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1549. }
  1550. m_log.Debug(hdr + activeJoints.Count + " total active joints");
  1551. foreach (string jointName in SOPName_to_activeJoint.Keys)
  1552. {
  1553. m_log.Debug(hdr + " active joints dict contains Name: " + jointName);
  1554. }
  1555. m_log.Debug(hdr + SOPName_to_activeJoint.Keys.Count + " total active joints dict entries");
  1556. m_log.Debug(hdr + " Per-body joint connectivity information follows.");
  1557. m_log.Debug(hdr + joints_connecting_actor.Keys.Count + " bodies are connected by joints.");
  1558. foreach (string actorName in joints_connecting_actor.Keys)
  1559. {
  1560. m_log.Debug(hdr + " Actor " + actorName + " has the following joints connecting it");
  1561. foreach (PhysicsJoint j in joints_connecting_actor[actorName])
  1562. {
  1563. m_log.Debug(hdr + " * joint Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1564. }
  1565. m_log.Debug(hdr + joints_connecting_actor[actorName].Count + " connecting joints total for this actor");
  1566. }
  1567. }
  1568. public override void RequestJointDeletion(string ObjectNameInScene)
  1569. {
  1570. lock (externalJointRequestsLock)
  1571. {
  1572. if (!requestedJointsToBeDeleted.Contains(ObjectNameInScene)) // forbid same deletion request from entering twice to prevent spurious deletions processed asynchronously
  1573. {
  1574. requestedJointsToBeDeleted.Add(ObjectNameInScene);
  1575. }
  1576. }
  1577. }
  1578. private void DeleteRequestedJoints()
  1579. {
  1580. List<string> myRequestedJointsToBeDeleted;
  1581. lock (externalJointRequestsLock)
  1582. {
  1583. // make a local copy of the shared list for processing (threading issues)
  1584. myRequestedJointsToBeDeleted = new List<string>(requestedJointsToBeDeleted);
  1585. }
  1586. foreach (string jointName in myRequestedJointsToBeDeleted)
  1587. {
  1588. lock (OdeLock)
  1589. {
  1590. //m_log.Debug("[NINJA] trying to deleting requested joint " + jointName);
  1591. if (SOPName_to_activeJoint.ContainsKey(jointName) || SOPName_to_pendingJoint.ContainsKey(jointName))
  1592. {
  1593. OdePhysicsJoint joint = null;
  1594. if (SOPName_to_activeJoint.ContainsKey(jointName))
  1595. {
  1596. joint = SOPName_to_activeJoint[jointName] as OdePhysicsJoint;
  1597. InternalRemoveActiveJoint(joint);
  1598. }
  1599. else if (SOPName_to_pendingJoint.ContainsKey(jointName))
  1600. {
  1601. joint = SOPName_to_pendingJoint[jointName] as OdePhysicsJoint;
  1602. InternalRemovePendingJoint(joint);
  1603. }
  1604. if (joint != null)
  1605. {
  1606. //m_log.Debug("joint.BodyNames.Count is " + joint.BodyNames.Count + " and contents " + joint.BodyNames);
  1607. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1608. {
  1609. string bodyName = joint.BodyNames[iBodyName];
  1610. if (bodyName != "NULL")
  1611. {
  1612. joints_connecting_actor[bodyName].Remove(joint);
  1613. if (joints_connecting_actor[bodyName].Count == 0)
  1614. {
  1615. joints_connecting_actor.Remove(bodyName);
  1616. }
  1617. }
  1618. }
  1619. DoJointDeactivated(joint);
  1620. if (joint.jointID != IntPtr.Zero)
  1621. {
  1622. d.JointDestroy(joint.jointID);
  1623. joint.jointID = IntPtr.Zero;
  1624. //DoJointErrorMessage(joint, "successfully destroyed joint " + jointName);
  1625. }
  1626. else
  1627. {
  1628. //m_log.Warn("[NINJA] Ignoring re-request to destroy joint " + jointName);
  1629. }
  1630. }
  1631. else
  1632. {
  1633. // DoJointErrorMessage(joint, "coult not find joint to destroy based on name " + jointName);
  1634. }
  1635. }
  1636. else
  1637. {
  1638. // DoJointErrorMessage(joint, "WARNING - joint removal failed, joint " + jointName);
  1639. }
  1640. }
  1641. }
  1642. // remove processed joints from the shared list
  1643. lock (externalJointRequestsLock)
  1644. {
  1645. foreach (string jointName in myRequestedJointsToBeDeleted)
  1646. {
  1647. requestedJointsToBeDeleted.Remove(jointName);
  1648. }
  1649. }
  1650. }
  1651. // for pending joints we don't know if their associated bodies exist yet or not.
  1652. // the joint is actually created during processing of the taints
  1653. private void CreateRequestedJoints()
  1654. {
  1655. List<PhysicsJoint> myRequestedJointsToBeCreated;
  1656. lock (externalJointRequestsLock)
  1657. {
  1658. // make a local copy of the shared list for processing (threading issues)
  1659. myRequestedJointsToBeCreated = new List<PhysicsJoint>(requestedJointsToBeCreated);
  1660. }
  1661. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1662. {
  1663. lock (OdeLock)
  1664. {
  1665. if (SOPName_to_pendingJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_pendingJoint[joint.ObjectNameInScene] != null)
  1666. {
  1667. 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);
  1668. continue;
  1669. }
  1670. if (SOPName_to_activeJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_activeJoint[joint.ObjectNameInScene] != null)
  1671. {
  1672. 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);
  1673. continue;
  1674. }
  1675. InternalAddPendingJoint(joint as OdePhysicsJoint);
  1676. if (joint.BodyNames.Count >= 2)
  1677. {
  1678. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1679. {
  1680. string bodyName = joint.BodyNames[iBodyName];
  1681. if (bodyName != "NULL")
  1682. {
  1683. if (!joints_connecting_actor.ContainsKey(bodyName))
  1684. {
  1685. joints_connecting_actor.Add(bodyName, new List<PhysicsJoint>());
  1686. }
  1687. joints_connecting_actor[bodyName].Add(joint);
  1688. }
  1689. }
  1690. }
  1691. }
  1692. }
  1693. // remove processed joints from shared list
  1694. lock (externalJointRequestsLock)
  1695. {
  1696. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1697. {
  1698. requestedJointsToBeCreated.Remove(joint);
  1699. }
  1700. }
  1701. }
  1702. // public function to add an request for joint creation
  1703. // this joint will just be added to a waiting list that is NOT processed during the main
  1704. // Simulate() loop (to avoid deadlocks). After Simulate() is finished, we handle unprocessed joint requests.
  1705. public override PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, Vector3 position,
  1706. Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation)
  1707. {
  1708. OdePhysicsJoint joint = new OdePhysicsJoint();
  1709. joint.ObjectNameInScene = objectNameInScene;
  1710. joint.Type = jointType;
  1711. joint.Position = position;
  1712. joint.Rotation = rotation;
  1713. joint.RawParams = parms;
  1714. joint.BodyNames = new List<string>(bodyNames);
  1715. joint.TrackedBodyName = trackedBodyName;
  1716. joint.LocalRotation = localRotation;
  1717. joint.jointID = IntPtr.Zero;
  1718. joint.ErrorMessageCount = 0;
  1719. lock (externalJointRequestsLock)
  1720. {
  1721. if (!requestedJointsToBeCreated.Contains(joint)) // forbid same creation request from entering twice
  1722. {
  1723. requestedJointsToBeCreated.Add(joint);
  1724. }
  1725. }
  1726. return joint;
  1727. }
  1728. private void RemoveAllJointsConnectedToActor(PhysicsActor actor)
  1729. {
  1730. //m_log.Debug("RemoveAllJointsConnectedToActor: start");
  1731. if (actor.SOPName != null && joints_connecting_actor.ContainsKey(actor.SOPName) && joints_connecting_actor[actor.SOPName] != null)
  1732. {
  1733. List<PhysicsJoint> jointsToRemove = new List<PhysicsJoint>();
  1734. //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)
  1735. foreach (PhysicsJoint j in joints_connecting_actor[actor.SOPName])
  1736. {
  1737. jointsToRemove.Add(j);
  1738. }
  1739. foreach (PhysicsJoint j in jointsToRemove)
  1740. {
  1741. //m_log.Debug("RemoveAllJointsConnectedToActor: about to request deletion of " + j.ObjectNameInScene);
  1742. RequestJointDeletion(j.ObjectNameInScene);
  1743. //m_log.Debug("RemoveAllJointsConnectedToActor: done request deletion of " + j.ObjectNameInScene);
  1744. 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)
  1745. }
  1746. }
  1747. }
  1748. public override void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor)
  1749. {
  1750. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: start");
  1751. lock (OdeLock)
  1752. {
  1753. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: got lock");
  1754. RemoveAllJointsConnectedToActor(actor);
  1755. }
  1756. }
  1757. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  1758. public override Vector3 GetJointAnchor(PhysicsJoint joint)
  1759. {
  1760. Debug.Assert(joint.IsInPhysicsEngine);
  1761. d.Vector3 pos = new d.Vector3();
  1762. if (!(joint is OdePhysicsJoint))
  1763. {
  1764. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  1765. }
  1766. else
  1767. {
  1768. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  1769. switch (odeJoint.Type)
  1770. {
  1771. case PhysicsJointType.Ball:
  1772. d.JointGetBallAnchor(odeJoint.jointID, out pos);
  1773. break;
  1774. case PhysicsJointType.Hinge:
  1775. d.JointGetHingeAnchor(odeJoint.jointID, out pos);
  1776. break;
  1777. }
  1778. }
  1779. return new Vector3(pos.X, pos.Y, pos.Z);
  1780. }
  1781. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  1782. // WARNING: ODE sometimes returns <0,0,0> as the joint axis! Therefore this function
  1783. // appears to be unreliable. Fortunately we can compute the joint axis ourselves by
  1784. // keeping track of the joint's original orientation relative to one of the involved bodies.
  1785. public override Vector3 GetJointAxis(PhysicsJoint joint)
  1786. {
  1787. Debug.Assert(joint.IsInPhysicsEngine);
  1788. d.Vector3 axis = new d.Vector3();
  1789. if (!(joint is OdePhysicsJoint))
  1790. {
  1791. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  1792. }
  1793. else
  1794. {
  1795. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  1796. switch (odeJoint.Type)
  1797. {
  1798. case PhysicsJointType.Ball:
  1799. DoJointErrorMessage(joint, "warning - axis requested for ball joint: " + joint.ObjectNameInScene);
  1800. break;
  1801. case PhysicsJointType.Hinge:
  1802. d.JointGetHingeAxis(odeJoint.jointID, out axis);
  1803. break;
  1804. }
  1805. }
  1806. return new Vector3(axis.X, axis.Y, axis.Z);
  1807. }
  1808. public void remActivePrim(OdePrim deactivatePrim)
  1809. {
  1810. lock (_activeprims)
  1811. {
  1812. _activeprims.Remove(deactivatePrim);
  1813. }
  1814. }
  1815. public override void RemovePrim(PhysicsActor prim)
  1816. {
  1817. if (prim is OdePrim)
  1818. {
  1819. lock (OdeLock)
  1820. {
  1821. OdePrim p = (OdePrim) prim;
  1822. p.setPrimForRemoval();
  1823. AddPhysicsActorTaint(prim);
  1824. //RemovePrimThreadLocked(p);
  1825. }
  1826. }
  1827. }
  1828. /// <summary>
  1829. /// This is called from within simulate but outside the locked portion
  1830. /// We need to do our own locking here
  1831. /// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
  1832. ///
  1833. /// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
  1834. /// that the space was using.
  1835. /// </summary>
  1836. /// <param name="prim"></param>
  1837. public void RemovePrimThreadLocked(OdePrim prim)
  1838. {
  1839. //Console.WriteLine("RemovePrimThreadLocked " + prim.m_primName);
  1840. lock (prim)
  1841. {
  1842. remCollisionEventReporting(prim);
  1843. lock (ode)
  1844. {
  1845. if (prim.prim_geom != IntPtr.Zero)
  1846. {
  1847. prim.ResetTaints();
  1848. if (prim.IsPhysical)
  1849. {
  1850. prim.disableBody();
  1851. if (prim.childPrim)
  1852. {
  1853. prim.childPrim = false;
  1854. prim.Body = IntPtr.Zero;
  1855. prim.m_disabled = true;
  1856. prim.IsPhysical = false;
  1857. }
  1858. }
  1859. // we don't want to remove the main space
  1860. // If the geometry is in the targetspace, remove it from the target space
  1861. //m_log.Warn(prim.m_targetSpace);
  1862. //if (prim.m_targetSpace != IntPtr.Zero)
  1863. //{
  1864. //if (d.SpaceQuery(prim.m_targetSpace, prim.prim_geom))
  1865. //{
  1866. //if (d.GeomIsSpace(prim.m_targetSpace))
  1867. //{
  1868. //waitForSpaceUnlock(prim.m_targetSpace);
  1869. //d.SpaceRemove(prim.m_targetSpace, prim.prim_geom);
  1870. prim.m_targetSpace = IntPtr.Zero;
  1871. //}
  1872. //else
  1873. //{
  1874. // m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  1875. //((OdePrim)prim).m_targetSpace.ToString());
  1876. //}
  1877. //}
  1878. //}
  1879. //m_log.Warn(prim.prim_geom);
  1880. try
  1881. {
  1882. if (prim.prim_geom != IntPtr.Zero)
  1883. {
  1884. d.GeomDestroy(prim.prim_geom);
  1885. prim.prim_geom = IntPtr.Zero;
  1886. }
  1887. else
  1888. {
  1889. m_log.Warn("[PHYSICS]: Unable to remove prim from physics scene");
  1890. }
  1891. }
  1892. catch (AccessViolationException)
  1893. {
  1894. m_log.Info("[PHYSICS]: Couldn't remove prim from physics scene, it was already be removed.");
  1895. }
  1896. lock (_prims)
  1897. _prims.Remove(prim);
  1898. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  1899. //if (d.SpaceGetNumGeoms(prim.m_targetSpace) == 0)
  1900. //{
  1901. //if (prim.m_targetSpace != null)
  1902. //{
  1903. //if (d.GeomIsSpace(prim.m_targetSpace))
  1904. //{
  1905. //waitForSpaceUnlock(prim.m_targetSpace);
  1906. //d.SpaceRemove(space, prim.m_targetSpace);
  1907. // free up memory used by the space.
  1908. //d.SpaceDestroy(prim.m_targetSpace);
  1909. //int[] xyspace = calculateSpaceArrayItemFromPos(prim.Position);
  1910. //resetSpaceArrayItemToZero(xyspace[0], xyspace[1]);
  1911. //}
  1912. //else
  1913. //{
  1914. //m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  1915. //((OdePrim) prim).m_targetSpace.ToString());
  1916. //}
  1917. //}
  1918. //}
  1919. if (SupportsNINJAJoints)
  1920. {
  1921. RemoveAllJointsConnectedToActorThreadLocked(prim);
  1922. }
  1923. }
  1924. }
  1925. }
  1926. }
  1927. #endregion
  1928. #region Space Separation Calculation
  1929. /// <summary>
  1930. /// Takes a space pointer and zeros out the array we're using to hold the spaces
  1931. /// </summary>
  1932. /// <param name="pSpace"></param>
  1933. public void resetSpaceArrayItemToZero(IntPtr pSpace)
  1934. {
  1935. for (int x = 0; x < staticPrimspace.GetLength(0); x++)
  1936. {
  1937. for (int y = 0; y < staticPrimspace.GetLength(1); y++)
  1938. {
  1939. if (staticPrimspace[x, y] == pSpace)
  1940. staticPrimspace[x, y] = IntPtr.Zero;
  1941. }
  1942. }
  1943. }
  1944. public void resetSpaceArrayItemToZero(int arrayitemX, int arrayitemY)
  1945. {
  1946. staticPrimspace[arrayitemX, arrayitemY] = IntPtr.Zero;
  1947. }
  1948. /// <summary>
  1949. /// Called when a static prim moves. Allocates a space for the prim based on its position
  1950. /// </summary>
  1951. /// <param name="geom">the pointer to the geom that moved</param>
  1952. /// <param name="pos">the position that the geom moved to</param>
  1953. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1954. /// <returns>a pointer to the new space it's in</returns>
  1955. public IntPtr recalculateSpaceForGeom(IntPtr geom, Vector3 pos, IntPtr currentspace)
  1956. {
  1957. // Called from setting the Position and Size of an ODEPrim so
  1958. // it's already in locked space.
  1959. // we don't want to remove the main space
  1960. // we don't need to test physical here because this function should
  1961. // never be called if the prim is physical(active)
  1962. // All physical prim end up in the root space
  1963. //Thread.Sleep(20);
  1964. if (currentspace != space)
  1965. {
  1966. //m_log.Info("[SPACE]: C:" + currentspace.ToString() + " g:" + geom.ToString());
  1967. //if (currentspace == IntPtr.Zero)
  1968. //{
  1969. //int adfadf = 0;
  1970. //}
  1971. if (d.SpaceQuery(currentspace, geom) && currentspace != IntPtr.Zero)
  1972. {
  1973. if (d.GeomIsSpace(currentspace))
  1974. {
  1975. waitForSpaceUnlock(currentspace);
  1976. d.SpaceRemove(currentspace, geom);
  1977. }
  1978. else
  1979. {
  1980. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" + currentspace +
  1981. " Geom:" + geom);
  1982. }
  1983. }
  1984. else
  1985. {
  1986. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  1987. if (sGeomIsIn != IntPtr.Zero)
  1988. {
  1989. if (d.GeomIsSpace(currentspace))
  1990. {
  1991. waitForSpaceUnlock(sGeomIsIn);
  1992. d.SpaceRemove(sGeomIsIn, geom);
  1993. }
  1994. else
  1995. {
  1996. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  1997. sGeomIsIn + " Geom:" + geom);
  1998. }
  1999. }
  2000. }
  2001. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  2002. if (d.SpaceGetNumGeoms(currentspace) == 0)
  2003. {
  2004. if (currentspace != IntPtr.Zero)
  2005. {
  2006. if (d.GeomIsSpace(currentspace))
  2007. {
  2008. waitForSpaceUnlock(currentspace);
  2009. waitForSpaceUnlock(space);
  2010. d.SpaceRemove(space, currentspace);
  2011. // free up memory used by the space.
  2012. //d.SpaceDestroy(currentspace);
  2013. resetSpaceArrayItemToZero(currentspace);
  2014. }
  2015. else
  2016. {
  2017. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2018. currentspace + " Geom:" + geom);
  2019. }
  2020. }
  2021. }
  2022. }
  2023. else
  2024. {
  2025. // this is a physical object that got disabled. ;.;
  2026. if (currentspace != IntPtr.Zero && geom != IntPtr.Zero)
  2027. {
  2028. if (d.SpaceQuery(currentspace, geom))
  2029. {
  2030. if (d.GeomIsSpace(currentspace))
  2031. {
  2032. waitForSpaceUnlock(currentspace);
  2033. d.SpaceRemove(currentspace, geom);
  2034. }
  2035. else
  2036. {
  2037. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2038. currentspace + " Geom:" + geom);
  2039. }
  2040. }
  2041. else
  2042. {
  2043. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2044. if (sGeomIsIn != IntPtr.Zero)
  2045. {
  2046. if (d.GeomIsSpace(sGeomIsIn))
  2047. {
  2048. waitForSpaceUnlock(sGeomIsIn);
  2049. d.SpaceRemove(sGeomIsIn, geom);
  2050. }
  2051. else
  2052. {
  2053. m_log.Info("[Physics]: Invalid Scene passed to 'recalculatespace':" +
  2054. sGeomIsIn + " Geom:" + geom);
  2055. }
  2056. }
  2057. }
  2058. }
  2059. }
  2060. // The routines in the Position and Size sections do the 'inserting' into the space,
  2061. // so all we have to do is make sure that the space that we're putting the prim into
  2062. // is in the 'main' space.
  2063. int[] iprimspaceArrItem = calculateSpaceArrayItemFromPos(pos);
  2064. IntPtr newspace = calculateSpaceForGeom(pos);
  2065. if (newspace == IntPtr.Zero)
  2066. {
  2067. newspace = createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  2068. d.HashSpaceSetLevels(newspace, smallHashspaceLow, smallHashspaceHigh);
  2069. }
  2070. return newspace;
  2071. }
  2072. /// <summary>
  2073. /// Creates a new space at X Y
  2074. /// </summary>
  2075. /// <param name="iprimspaceArrItemX"></param>
  2076. /// <param name="iprimspaceArrItemY"></param>
  2077. /// <returns>A pointer to the created space</returns>
  2078. public IntPtr createprimspace(int iprimspaceArrItemX, int iprimspaceArrItemY)
  2079. {
  2080. // creating a new space for prim and inserting it into main space.
  2081. staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY] = d.HashSpaceCreate(IntPtr.Zero);
  2082. d.GeomSetCategoryBits(staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY], (int)CollisionCategories.Space);
  2083. waitForSpaceUnlock(space);
  2084. d.SpaceSetSublevel(space, 1);
  2085. d.SpaceAdd(space, staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY]);
  2086. return staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY];
  2087. }
  2088. /// <summary>
  2089. /// Calculates the space the prim should be in by its position
  2090. /// </summary>
  2091. /// <param name="pos"></param>
  2092. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  2093. public IntPtr calculateSpaceForGeom(Vector3 pos)
  2094. {
  2095. int[] xyspace = calculateSpaceArrayItemFromPos(pos);
  2096. //m_log.Info("[Physics]: Attempting to use arrayItem: " + xyspace[0].ToString() + "," + xyspace[1].ToString());
  2097. return staticPrimspace[xyspace[0], xyspace[1]];
  2098. }
  2099. /// <summary>
  2100. /// Holds the space allocation logic
  2101. /// </summary>
  2102. /// <param name="pos"></param>
  2103. /// <returns>an array item based on the position</returns>
  2104. public int[] calculateSpaceArrayItemFromPos(Vector3 pos)
  2105. {
  2106. int[] returnint = new int[2];
  2107. returnint[0] = (int) (pos.X/metersInSpace);
  2108. if (returnint[0] > ((int) (259f/metersInSpace)))
  2109. returnint[0] = ((int) (259f/metersInSpace));
  2110. if (returnint[0] < 0)
  2111. returnint[0] = 0;
  2112. returnint[1] = (int) (pos.Y/metersInSpace);
  2113. if (returnint[1] > ((int) (259f/metersInSpace)))
  2114. returnint[1] = ((int) (259f/metersInSpace));
  2115. if (returnint[1] < 0)
  2116. returnint[1] = 0;
  2117. return returnint;
  2118. }
  2119. #endregion
  2120. /// <summary>
  2121. /// Routine to figure out if we need to mesh this prim with our mesher
  2122. /// </summary>
  2123. /// <param name="pbs"></param>
  2124. /// <returns></returns>
  2125. public bool needsMeshing(PrimitiveBaseShape pbs)
  2126. {
  2127. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  2128. // but we still need to check for sculptie meshing being enabled so this is the most
  2129. // convenient place to do it for now...
  2130. // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
  2131. // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
  2132. int iPropertiesNotSupportedDefault = 0;
  2133. if (pbs.SculptEntry && !meshSculptedPrim)
  2134. {
  2135. #if SPAM
  2136. m_log.Warn("NonMesh");
  2137. #endif
  2138. return false;
  2139. }
  2140. // 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
  2141. if (!forceSimplePrimMeshing)
  2142. {
  2143. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  2144. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  2145. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  2146. {
  2147. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  2148. && pbs.ProfileHollow == 0
  2149. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  2150. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  2151. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  2152. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  2153. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  2154. {
  2155. #if SPAM
  2156. m_log.Warn("NonMesh");
  2157. #endif
  2158. return false;
  2159. }
  2160. }
  2161. }
  2162. if (pbs.ProfileHollow != 0)
  2163. iPropertiesNotSupportedDefault++;
  2164. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  2165. iPropertiesNotSupportedDefault++;
  2166. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  2167. iPropertiesNotSupportedDefault++;
  2168. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  2169. iPropertiesNotSupportedDefault++;
  2170. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  2171. iPropertiesNotSupportedDefault++;
  2172. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  2173. iPropertiesNotSupportedDefault++;
  2174. 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))
  2175. iPropertiesNotSupportedDefault++;
  2176. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  2177. iPropertiesNotSupportedDefault++;
  2178. // test for torus
  2179. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  2180. {
  2181. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2182. {
  2183. iPropertiesNotSupportedDefault++;
  2184. }
  2185. }
  2186. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  2187. {
  2188. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2189. {
  2190. iPropertiesNotSupportedDefault++;
  2191. }
  2192. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  2193. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2194. {
  2195. iPropertiesNotSupportedDefault++;
  2196. }
  2197. }
  2198. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  2199. {
  2200. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  2201. {
  2202. iPropertiesNotSupportedDefault++;
  2203. }
  2204. }
  2205. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  2206. {
  2207. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2208. {
  2209. iPropertiesNotSupportedDefault++;
  2210. }
  2211. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2212. {
  2213. iPropertiesNotSupportedDefault++;
  2214. }
  2215. }
  2216. if (iPropertiesNotSupportedDefault == 0)
  2217. {
  2218. #if SPAM
  2219. m_log.Warn("NonMesh");
  2220. #endif
  2221. return false;
  2222. }
  2223. #if SPAM
  2224. m_log.Debug("Mesh");
  2225. #endif
  2226. return true;
  2227. }
  2228. /// <summary>
  2229. /// Called after our prim properties are set Scale, position etc.
  2230. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  2231. /// This assures us that we have no race conditions
  2232. /// </summary>
  2233. /// <param name="prim"></param>
  2234. public override void AddPhysicsActorTaint(PhysicsActor prim)
  2235. {
  2236. if (prim is OdePrim)
  2237. {
  2238. OdePrim taintedprim = ((OdePrim) prim);
  2239. lock (_taintedPrimLock)
  2240. {
  2241. if (!(_taintedPrimH.Contains(taintedprim)))
  2242. {
  2243. //Console.WriteLine("AddPhysicsActorTaint to " + taintedprim.m_primName);
  2244. _taintedPrimH.Add(taintedprim); // HashSet for searching
  2245. _taintedPrimL.Add(taintedprim); // List for ordered readout
  2246. }
  2247. }
  2248. return;
  2249. }
  2250. else if (prim is OdeCharacter)
  2251. {
  2252. OdeCharacter taintedchar = ((OdeCharacter)prim);
  2253. lock (_taintedActors)
  2254. {
  2255. if (!(_taintedActors.Contains(taintedchar)))
  2256. {
  2257. _taintedActors.Add(taintedchar);
  2258. if (taintedchar.bad)
  2259. m_log.DebugFormat("[PHYSICS]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
  2260. }
  2261. }
  2262. }
  2263. }
  2264. /// <summary>
  2265. /// This is our main simulate loop
  2266. /// It's thread locked by a Mutex in the scene.
  2267. /// It holds Collisions, it instructs ODE to step through the physical reactions
  2268. /// It moves the objects around in memory
  2269. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  2270. /// </summary>
  2271. /// <param name="timeStep"></param>
  2272. /// <returns></returns>
  2273. public override float Simulate(float timeStep)
  2274. {
  2275. if (framecount >= int.MaxValue)
  2276. framecount = 0;
  2277. //if (m_worldOffset != Vector3.Zero)
  2278. // return 0;
  2279. framecount++;
  2280. float fps = 0;
  2281. //m_log.Info(timeStep.ToString());
  2282. step_time += timeStep;
  2283. // If We're loaded down by something else,
  2284. // or debugging with the Visual Studio project on pause
  2285. // skip a few frames to catch up gracefully.
  2286. // without shooting the physicsactors all over the place
  2287. if (step_time >= m_SkipFramesAtms)
  2288. {
  2289. // Instead of trying to catch up, it'll do 5 physics frames only
  2290. step_time = ODE_STEPSIZE;
  2291. m_physicsiterations = 5;
  2292. }
  2293. else
  2294. {
  2295. m_physicsiterations = 10;
  2296. }
  2297. if (SupportsNINJAJoints)
  2298. {
  2299. DeleteRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2300. CreateRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2301. }
  2302. lock (OdeLock)
  2303. {
  2304. // Process 10 frames if the sim is running normal..
  2305. // process 5 frames if the sim is running slow
  2306. //try
  2307. //{
  2308. //d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  2309. //}
  2310. //catch (StackOverflowException)
  2311. //{
  2312. // m_log.Error("[PHYSICS]: The operating system wasn't able to allocate enough memory for the simulation. Restarting the sim.");
  2313. // ode.drelease(world);
  2314. //base.TriggerPhysicsBasedRestart();
  2315. //}
  2316. int i = 0;
  2317. // Figure out the Frames Per Second we're going at.
  2318. //(step_time == 0.004f, there's 250 of those per second. Times the step time/step size
  2319. fps = (step_time / ODE_STEPSIZE) * 1000;
  2320. // HACK: Using a time dilation of 1.0 to debug rubberbanding issues
  2321. //m_timeDilation = Math.Min((step_time / ODE_STEPSIZE) / (0.09375f / ODE_STEPSIZE), 1.0f);
  2322. step_time = 0.09375f;
  2323. while (step_time > 0.0f)
  2324. {
  2325. //lock (ode)
  2326. //{
  2327. //if (!ode.lockquery())
  2328. //{
  2329. // ode.dlock(world);
  2330. try
  2331. {
  2332. // Insert, remove Characters
  2333. bool processedtaints = false;
  2334. lock (_taintedActors)
  2335. {
  2336. if (_taintedActors.Count > 0)
  2337. {
  2338. foreach (OdeCharacter character in _taintedActors)
  2339. {
  2340. character.ProcessTaints(timeStep);
  2341. processedtaints = true;
  2342. //character.m_collisionscore = 0;
  2343. }
  2344. if (processedtaints)
  2345. _taintedActors.Clear();
  2346. }
  2347. }
  2348. // Modify other objects in the scene.
  2349. processedtaints = false;
  2350. lock (_taintedPrimLock)
  2351. {
  2352. foreach (OdePrim prim in _taintedPrimL)
  2353. {
  2354. if (prim.m_taintremove)
  2355. {
  2356. //Console.WriteLine("Simulate calls RemovePrimThreadLocked");
  2357. RemovePrimThreadLocked(prim);
  2358. }
  2359. else
  2360. {
  2361. //Console.WriteLine("Simulate calls ProcessTaints");
  2362. prim.ProcessTaints(timeStep);
  2363. }
  2364. processedtaints = true;
  2365. prim.m_collisionscore = 0;
  2366. // This loop can block up the Heartbeat for a very long time on large regions.
  2367. // We need to let the Watchdog know that the Heartbeat is not dead
  2368. // NOTE: This is currently commented out, but if things like OAR loading are
  2369. // timing the heartbeat out we will need to uncomment it
  2370. //Watchdog.UpdateThread();
  2371. }
  2372. if (SupportsNINJAJoints)
  2373. {
  2374. // Create pending joints, if possible
  2375. // joints can only be processed after ALL bodies are processed (and exist in ODE), since creating
  2376. // a joint requires specifying the body id of both involved bodies
  2377. if (pendingJoints.Count > 0)
  2378. {
  2379. List<PhysicsJoint> successfullyProcessedPendingJoints = new List<PhysicsJoint>();
  2380. //DoJointErrorMessage(joints_connecting_actor, "taint: " + pendingJoints.Count + " pending joints");
  2381. foreach (PhysicsJoint joint in pendingJoints)
  2382. {
  2383. //DoJointErrorMessage(joint, "taint: time to create joint with parms: " + joint.RawParams);
  2384. string[] jointParams = joint.RawParams.Split(" ".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
  2385. List<IntPtr> jointBodies = new List<IntPtr>();
  2386. bool allJointBodiesAreReady = true;
  2387. foreach (string jointParam in jointParams)
  2388. {
  2389. if (jointParam == "NULL")
  2390. {
  2391. //DoJointErrorMessage(joint, "attaching NULL joint to world");
  2392. jointBodies.Add(IntPtr.Zero);
  2393. }
  2394. else
  2395. {
  2396. //DoJointErrorMessage(joint, "looking for prim name: " + jointParam);
  2397. bool foundPrim = false;
  2398. lock (_prims)
  2399. {
  2400. foreach (OdePrim prim in _prims) // FIXME: inefficient
  2401. {
  2402. if (prim.SOPName == jointParam)
  2403. {
  2404. //DoJointErrorMessage(joint, "found for prim name: " + jointParam);
  2405. if (prim.IsPhysical && prim.Body != IntPtr.Zero)
  2406. {
  2407. jointBodies.Add(prim.Body);
  2408. foundPrim = true;
  2409. break;
  2410. }
  2411. else
  2412. {
  2413. DoJointErrorMessage(joint, "prim name " + jointParam +
  2414. " exists but is not (yet) physical; deferring joint creation. " +
  2415. "IsPhysical property is " + prim.IsPhysical +
  2416. " and body is " + prim.Body);
  2417. foundPrim = false;
  2418. break;
  2419. }
  2420. }
  2421. }
  2422. }
  2423. if (foundPrim)
  2424. {
  2425. // all is fine
  2426. }
  2427. else
  2428. {
  2429. allJointBodiesAreReady = false;
  2430. break;
  2431. }
  2432. }
  2433. }
  2434. if (allJointBodiesAreReady)
  2435. {
  2436. //DoJointErrorMessage(joint, "allJointBodiesAreReady for " + joint.ObjectNameInScene + " with parms " + joint.RawParams);
  2437. if (jointBodies[0] == jointBodies[1])
  2438. {
  2439. DoJointErrorMessage(joint, "ERROR: joint cannot be created; the joint bodies are the same, body1==body2. Raw body is " + jointBodies[0] + ". raw parms: " + joint.RawParams);
  2440. }
  2441. else
  2442. {
  2443. switch (joint.Type)
  2444. {
  2445. case PhysicsJointType.Ball:
  2446. {
  2447. IntPtr odeJoint;
  2448. //DoJointErrorMessage(joint, "ODE creating ball joint ");
  2449. odeJoint = d.JointCreateBall(world, IntPtr.Zero);
  2450. //DoJointErrorMessage(joint, "ODE attaching ball joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2451. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2452. //DoJointErrorMessage(joint, "ODE setting ball anchor: " + odeJoint + " to vec:" + joint.Position);
  2453. d.JointSetBallAnchor(odeJoint,
  2454. joint.Position.X,
  2455. joint.Position.Y,
  2456. joint.Position.Z);
  2457. //DoJointErrorMessage(joint, "ODE joint setting OK");
  2458. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b0: ");
  2459. //DoJointErrorMessage(joint, "" + (jointBodies[0] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[0]) : "fixed environment"));
  2460. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b1: ");
  2461. //DoJointErrorMessage(joint, "" + (jointBodies[1] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[1]) : "fixed environment"));
  2462. if (joint is OdePhysicsJoint)
  2463. {
  2464. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2465. }
  2466. else
  2467. {
  2468. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2469. }
  2470. }
  2471. break;
  2472. case PhysicsJointType.Hinge:
  2473. {
  2474. IntPtr odeJoint;
  2475. //DoJointErrorMessage(joint, "ODE creating hinge joint ");
  2476. odeJoint = d.JointCreateHinge(world, IntPtr.Zero);
  2477. //DoJointErrorMessage(joint, "ODE attaching hinge joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2478. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2479. //DoJointErrorMessage(joint, "ODE setting hinge anchor: " + odeJoint + " to vec:" + joint.Position);
  2480. d.JointSetHingeAnchor(odeJoint,
  2481. joint.Position.X,
  2482. joint.Position.Y,
  2483. joint.Position.Z);
  2484. // We use the orientation of the x-axis of the joint's coordinate frame
  2485. // as the axis for the hinge.
  2486. // Therefore, we must get the joint's coordinate frame based on the
  2487. // joint.Rotation field, which originates from the orientation of the
  2488. // joint's proxy object in the scene.
  2489. // The joint's coordinate frame is defined as the transformation matrix
  2490. // that converts a vector from joint-local coordinates into world coordinates.
  2491. // World coordinates are defined as the XYZ coordinate system of the sim,
  2492. // as shown in the top status-bar of the viewer.
  2493. // Once we have the joint's coordinate frame, we extract its X axis (AtAxis)
  2494. // and use that as the hinge axis.
  2495. //joint.Rotation.Normalize();
  2496. Matrix4 proxyFrame = Matrix4.CreateFromQuaternion(joint.Rotation);
  2497. // Now extract the X axis of the joint's coordinate frame.
  2498. // Do not try to use proxyFrame.AtAxis or you will become mired in the
  2499. // tar pit of transposed, inverted, and generally messed-up orientations.
  2500. // (In other words, Matrix4.AtAxis() is borked.)
  2501. // Vector3 jointAxis = proxyFrame.AtAxis; <--- this path leadeth to madness
  2502. // Instead, compute the X axis of the coordinate frame by transforming
  2503. // the (1,0,0) vector. At least that works.
  2504. //m_log.Debug("PHY: making axis: complete matrix is " + proxyFrame);
  2505. Vector3 jointAxis = Vector3.Transform(Vector3.UnitX, proxyFrame);
  2506. //m_log.Debug("PHY: making axis: hinge joint axis is " + jointAxis);
  2507. //DoJointErrorMessage(joint, "ODE setting hinge axis: " + odeJoint + " to vec:" + jointAxis);
  2508. d.JointSetHingeAxis(odeJoint,
  2509. jointAxis.X,
  2510. jointAxis.Y,
  2511. jointAxis.Z);
  2512. //d.JointSetHingeParam(odeJoint, (int)dParam.CFM, 0.1f);
  2513. if (joint is OdePhysicsJoint)
  2514. {
  2515. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2516. }
  2517. else
  2518. {
  2519. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2520. }
  2521. }
  2522. break;
  2523. }
  2524. successfullyProcessedPendingJoints.Add(joint);
  2525. }
  2526. }
  2527. else
  2528. {
  2529. DoJointErrorMessage(joint, "joint could not yet be created; still pending");
  2530. }
  2531. }
  2532. foreach (PhysicsJoint successfullyProcessedJoint in successfullyProcessedPendingJoints)
  2533. {
  2534. //DoJointErrorMessage(successfullyProcessedJoint, "finalizing succesfully procsssed joint " + successfullyProcessedJoint.ObjectNameInScene + " parms " + successfullyProcessedJoint.RawParams);
  2535. //DoJointErrorMessage(successfullyProcessedJoint, "removing from pending");
  2536. InternalRemovePendingJoint(successfullyProcessedJoint);
  2537. //DoJointErrorMessage(successfullyProcessedJoint, "adding to active");
  2538. InternalAddActiveJoint(successfullyProcessedJoint);
  2539. //DoJointErrorMessage(successfullyProcessedJoint, "done");
  2540. }
  2541. }
  2542. }
  2543. if (processedtaints)
  2544. //Console.WriteLine("Simulate calls Clear of _taintedPrim list");
  2545. _taintedPrimH.Clear();
  2546. _taintedPrimL.Clear();
  2547. }
  2548. // Move characters
  2549. lock (_characters)
  2550. {
  2551. List<OdeCharacter> defects = new List<OdeCharacter>();
  2552. foreach (OdeCharacter actor in _characters)
  2553. {
  2554. if (actor != null)
  2555. actor.Move(timeStep, defects);
  2556. }
  2557. if (0 != defects.Count)
  2558. {
  2559. foreach (OdeCharacter defect in defects)
  2560. {
  2561. RemoveCharacter(defect);
  2562. }
  2563. }
  2564. }
  2565. // Move other active objects
  2566. lock (_activeprims)
  2567. {
  2568. foreach (OdePrim prim in _activeprims)
  2569. {
  2570. prim.m_collisionscore = 0;
  2571. prim.Move(timeStep);
  2572. }
  2573. }
  2574. //if ((framecount % m_randomizeWater) == 0)
  2575. // randomizeWater(waterlevel);
  2576. //int RayCastTimeMS = m_rayCastManager.ProcessQueuedRequests();
  2577. m_rayCastManager.ProcessQueuedRequests();
  2578. collision_optimized(timeStep);
  2579. lock (_collisionEventPrim)
  2580. {
  2581. foreach (PhysicsActor obj in _collisionEventPrim)
  2582. {
  2583. if (obj == null)
  2584. continue;
  2585. switch ((ActorTypes)obj.PhysicsActorType)
  2586. {
  2587. case ActorTypes.Agent:
  2588. OdeCharacter cobj = (OdeCharacter)obj;
  2589. cobj.AddCollisionFrameTime(100);
  2590. cobj.SendCollisions();
  2591. break;
  2592. case ActorTypes.Prim:
  2593. OdePrim pobj = (OdePrim)obj;
  2594. pobj.SendCollisions();
  2595. break;
  2596. }
  2597. }
  2598. }
  2599. //if (m_global_contactcount > 5)
  2600. //{
  2601. // m_log.DebugFormat("[PHYSICS]: Contacts:{0}", m_global_contactcount);
  2602. //}
  2603. m_global_contactcount = 0;
  2604. d.WorldQuickStep(world, ODE_STEPSIZE);
  2605. d.JointGroupEmpty(contactgroup);
  2606. //ode.dunlock(world);
  2607. }
  2608. catch (Exception e)
  2609. {
  2610. m_log.ErrorFormat("[PHYSICS]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  2611. ode.dunlock(world);
  2612. }
  2613. step_time -= ODE_STEPSIZE;
  2614. i++;
  2615. //}
  2616. //else
  2617. //{
  2618. //fps = 0;
  2619. //}
  2620. //}
  2621. }
  2622. lock (_characters)
  2623. {
  2624. foreach (OdeCharacter actor in _characters)
  2625. {
  2626. if (actor != null)
  2627. {
  2628. if (actor.bad)
  2629. m_log.WarnFormat("[PHYSICS]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  2630. actor.UpdatePositionAndVelocity();
  2631. }
  2632. }
  2633. }
  2634. lock (_badCharacter)
  2635. {
  2636. if (_badCharacter.Count > 0)
  2637. {
  2638. foreach (OdeCharacter chr in _badCharacter)
  2639. {
  2640. RemoveCharacter(chr);
  2641. }
  2642. _badCharacter.Clear();
  2643. }
  2644. }
  2645. lock (_activeprims)
  2646. {
  2647. //if (timeStep < 0.2f)
  2648. {
  2649. foreach (OdePrim actor in _activeprims)
  2650. {
  2651. if (actor.IsPhysical && (d.BodyIsEnabled(actor.Body) || !actor._zeroFlag))
  2652. {
  2653. actor.UpdatePositionAndVelocity();
  2654. if (SupportsNINJAJoints)
  2655. {
  2656. // If an actor moved, move its joint proxy objects as well.
  2657. // There seems to be an event PhysicsActor.OnPositionUpdate that could be used
  2658. // for this purpose but it is never called! So we just do the joint
  2659. // movement code here.
  2660. if (actor.SOPName != null &&
  2661. joints_connecting_actor.ContainsKey(actor.SOPName) &&
  2662. joints_connecting_actor[actor.SOPName] != null &&
  2663. joints_connecting_actor[actor.SOPName].Count > 0)
  2664. {
  2665. foreach (PhysicsJoint affectedJoint in joints_connecting_actor[actor.SOPName])
  2666. {
  2667. if (affectedJoint.IsInPhysicsEngine)
  2668. {
  2669. DoJointMoved(affectedJoint);
  2670. }
  2671. else
  2672. {
  2673. 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);
  2674. }
  2675. }
  2676. }
  2677. }
  2678. }
  2679. }
  2680. }
  2681. }
  2682. //DumpJointInfo();
  2683. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  2684. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  2685. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  2686. if (physics_logging && (physics_logging_interval>0) && (framecount % physics_logging_interval == 0))
  2687. {
  2688. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  2689. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  2690. if (physics_logging_append_existing_logfile)
  2691. {
  2692. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  2693. TextWriter fwriter = File.AppendText(fname);
  2694. fwriter.WriteLine(header);
  2695. fwriter.Close();
  2696. }
  2697. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  2698. }
  2699. }
  2700. return fps;
  2701. }
  2702. public override void GetResults()
  2703. {
  2704. }
  2705. public override bool IsThreaded
  2706. {
  2707. // for now we won't be multithreaded
  2708. get { return (false); }
  2709. }
  2710. #region ODE Specific Terrain Fixes
  2711. public float[] ResizeTerrain512NearestNeighbour(float[] heightMap)
  2712. {
  2713. float[] returnarr = new float[262144];
  2714. float[,] resultarr = new float[(int)WorldExtents.X, (int)WorldExtents.Y];
  2715. // Filling out the array into its multi-dimensional components
  2716. for (int y = 0; y < WorldExtents.Y; y++)
  2717. {
  2718. for (int x = 0; x < WorldExtents.X; x++)
  2719. {
  2720. resultarr[y, x] = heightMap[y * (int)WorldExtents.Y + x];
  2721. }
  2722. }
  2723. // Resize using Nearest Neighbour
  2724. // This particular way is quick but it only works on a multiple of the original
  2725. // The idea behind this method can be described with the following diagrams
  2726. // second pass and third pass happen in the same loop really.. just separated
  2727. // them to show what this does.
  2728. // First Pass
  2729. // ResultArr:
  2730. // 1,1,1,1,1,1
  2731. // 1,1,1,1,1,1
  2732. // 1,1,1,1,1,1
  2733. // 1,1,1,1,1,1
  2734. // 1,1,1,1,1,1
  2735. // 1,1,1,1,1,1
  2736. // Second Pass
  2737. // ResultArr2:
  2738. // 1,,1,,1,,1,,1,,1,
  2739. // ,,,,,,,,,,
  2740. // 1,,1,,1,,1,,1,,1,
  2741. // ,,,,,,,,,,
  2742. // 1,,1,,1,,1,,1,,1,
  2743. // ,,,,,,,,,,
  2744. // 1,,1,,1,,1,,1,,1,
  2745. // ,,,,,,,,,,
  2746. // 1,,1,,1,,1,,1,,1,
  2747. // ,,,,,,,,,,
  2748. // 1,,1,,1,,1,,1,,1,
  2749. // Third pass fills in the blanks
  2750. // ResultArr2:
  2751. // 1,1,1,1,1,1,1,1,1,1,1,1
  2752. // 1,1,1,1,1,1,1,1,1,1,1,1
  2753. // 1,1,1,1,1,1,1,1,1,1,1,1
  2754. // 1,1,1,1,1,1,1,1,1,1,1,1
  2755. // 1,1,1,1,1,1,1,1,1,1,1,1
  2756. // 1,1,1,1,1,1,1,1,1,1,1,1
  2757. // 1,1,1,1,1,1,1,1,1,1,1,1
  2758. // 1,1,1,1,1,1,1,1,1,1,1,1
  2759. // 1,1,1,1,1,1,1,1,1,1,1,1
  2760. // 1,1,1,1,1,1,1,1,1,1,1,1
  2761. // 1,1,1,1,1,1,1,1,1,1,1,1
  2762. // X,Y = .
  2763. // X+1,y = ^
  2764. // X,Y+1 = *
  2765. // X+1,Y+1 = #
  2766. // Filling in like this;
  2767. // .*
  2768. // ^#
  2769. // 1st .
  2770. // 2nd *
  2771. // 3rd ^
  2772. // 4th #
  2773. // on single loop.
  2774. float[,] resultarr2 = new float[512, 512];
  2775. for (int y = 0; y < WorldExtents.Y; y++)
  2776. {
  2777. for (int x = 0; x < WorldExtents.X; x++)
  2778. {
  2779. resultarr2[y * 2, x * 2] = resultarr[y, x];
  2780. if (y < WorldExtents.Y)
  2781. {
  2782. resultarr2[(y * 2) + 1, x * 2] = resultarr[y, x];
  2783. }
  2784. if (x < WorldExtents.X)
  2785. {
  2786. resultarr2[y * 2, (x * 2) + 1] = resultarr[y, x];
  2787. }
  2788. if (x < WorldExtents.X && y < WorldExtents.Y)
  2789. {
  2790. resultarr2[(y * 2) + 1, (x * 2) + 1] = resultarr[y, x];
  2791. }
  2792. }
  2793. }
  2794. //Flatten out the array
  2795. int i = 0;
  2796. for (int y = 0; y < 512; y++)
  2797. {
  2798. for (int x = 0; x < 512; x++)
  2799. {
  2800. if (resultarr2[y, x] <= 0)
  2801. returnarr[i] = 0.0000001f;
  2802. else
  2803. returnarr[i] = resultarr2[y, x];
  2804. i++;
  2805. }
  2806. }
  2807. return returnarr;
  2808. }
  2809. public float[] ResizeTerrain512Interpolation(float[] heightMap)
  2810. {
  2811. float[] returnarr = new float[262144];
  2812. float[,] resultarr = new float[512,512];
  2813. // Filling out the array into its multi-dimensional components
  2814. for (int y = 0; y < 256; y++)
  2815. {
  2816. for (int x = 0; x < 256; x++)
  2817. {
  2818. resultarr[y, x] = heightMap[y * 256 + x];
  2819. }
  2820. }
  2821. // Resize using interpolation
  2822. // This particular way is quick but it only works on a multiple of the original
  2823. // The idea behind this method can be described with the following diagrams
  2824. // second pass and third pass happen in the same loop really.. just separated
  2825. // them to show what this does.
  2826. // First Pass
  2827. // ResultArr:
  2828. // 1,1,1,1,1,1
  2829. // 1,1,1,1,1,1
  2830. // 1,1,1,1,1,1
  2831. // 1,1,1,1,1,1
  2832. // 1,1,1,1,1,1
  2833. // 1,1,1,1,1,1
  2834. // Second Pass
  2835. // ResultArr2:
  2836. // 1,,1,,1,,1,,1,,1,
  2837. // ,,,,,,,,,,
  2838. // 1,,1,,1,,1,,1,,1,
  2839. // ,,,,,,,,,,
  2840. // 1,,1,,1,,1,,1,,1,
  2841. // ,,,,,,,,,,
  2842. // 1,,1,,1,,1,,1,,1,
  2843. // ,,,,,,,,,,
  2844. // 1,,1,,1,,1,,1,,1,
  2845. // ,,,,,,,,,,
  2846. // 1,,1,,1,,1,,1,,1,
  2847. // Third pass fills in the blanks
  2848. // ResultArr2:
  2849. // 1,1,1,1,1,1,1,1,1,1,1,1
  2850. // 1,1,1,1,1,1,1,1,1,1,1,1
  2851. // 1,1,1,1,1,1,1,1,1,1,1,1
  2852. // 1,1,1,1,1,1,1,1,1,1,1,1
  2853. // 1,1,1,1,1,1,1,1,1,1,1,1
  2854. // 1,1,1,1,1,1,1,1,1,1,1,1
  2855. // 1,1,1,1,1,1,1,1,1,1,1,1
  2856. // 1,1,1,1,1,1,1,1,1,1,1,1
  2857. // 1,1,1,1,1,1,1,1,1,1,1,1
  2858. // 1,1,1,1,1,1,1,1,1,1,1,1
  2859. // 1,1,1,1,1,1,1,1,1,1,1,1
  2860. // X,Y = .
  2861. // X+1,y = ^
  2862. // X,Y+1 = *
  2863. // X+1,Y+1 = #
  2864. // Filling in like this;
  2865. // .*
  2866. // ^#
  2867. // 1st .
  2868. // 2nd *
  2869. // 3rd ^
  2870. // 4th #
  2871. // on single loop.
  2872. float[,] resultarr2 = new float[512,512];
  2873. for (int y = 0; y < (int)Constants.RegionSize; y++)
  2874. {
  2875. for (int x = 0; x < (int)Constants.RegionSize; x++)
  2876. {
  2877. resultarr2[y*2, x*2] = resultarr[y, x];
  2878. if (y < (int)Constants.RegionSize)
  2879. {
  2880. if (y + 1 < (int)Constants.RegionSize)
  2881. {
  2882. if (x + 1 < (int)Constants.RegionSize)
  2883. {
  2884. resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x] +
  2885. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  2886. }
  2887. else
  2888. {
  2889. resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x])/2);
  2890. }
  2891. }
  2892. else
  2893. {
  2894. resultarr2[(y*2) + 1, x*2] = resultarr[y, x];
  2895. }
  2896. }
  2897. if (x < (int)Constants.RegionSize)
  2898. {
  2899. if (x + 1 < (int)Constants.RegionSize)
  2900. {
  2901. if (y + 1 < (int)Constants.RegionSize)
  2902. {
  2903. resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
  2904. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  2905. }
  2906. else
  2907. {
  2908. resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y, x + 1])/2);
  2909. }
  2910. }
  2911. else
  2912. {
  2913. resultarr2[y*2, (x*2) + 1] = resultarr[y, x];
  2914. }
  2915. }
  2916. if (x < (int)Constants.RegionSize && y < (int)Constants.RegionSize)
  2917. {
  2918. if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize))
  2919. {
  2920. resultarr2[(y*2) + 1, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
  2921. resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
  2922. }
  2923. else
  2924. {
  2925. resultarr2[(y*2) + 1, (x*2) + 1] = resultarr[y, x];
  2926. }
  2927. }
  2928. }
  2929. }
  2930. //Flatten out the array
  2931. int i = 0;
  2932. for (int y = 0; y < 512; y++)
  2933. {
  2934. for (int x = 0; x < 512; x++)
  2935. {
  2936. if (Single.IsNaN(resultarr2[y, x]) || Single.IsInfinity(resultarr2[y, x]))
  2937. {
  2938. m_log.Warn("[PHYSICS]: Non finite heightfield element detected. Setting it to 0");
  2939. resultarr2[y, x] = 0;
  2940. }
  2941. returnarr[i] = resultarr2[y, x];
  2942. i++;
  2943. }
  2944. }
  2945. return returnarr;
  2946. }
  2947. #endregion
  2948. public override void SetTerrain(float[] heightMap)
  2949. {
  2950. if (m_worldOffset != Vector3.Zero && m_parentScene != null)
  2951. {
  2952. if (m_parentScene is OdeScene)
  2953. {
  2954. ((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
  2955. }
  2956. }
  2957. else
  2958. {
  2959. SetTerrain(heightMap, m_worldOffset);
  2960. }
  2961. }
  2962. public void SetTerrain(float[] heightMap, Vector3 pOffset)
  2963. {
  2964. // this._heightmap[i] = (double)heightMap[i];
  2965. // dbm (danx0r) -- creating a buffer zone of one extra sample all around
  2966. //_origheightmap = heightMap;
  2967. float[] _heightmap;
  2968. // zero out a heightmap array float array (single dimension [flattened]))
  2969. //if ((int)Constants.RegionSize == 256)
  2970. // _heightmap = new float[514 * 514];
  2971. //else
  2972. _heightmap = new float[(((int)Constants.RegionSize + 2) * ((int)Constants.RegionSize + 2))];
  2973. uint heightmapWidth = Constants.RegionSize + 1;
  2974. uint heightmapHeight = Constants.RegionSize + 1;
  2975. uint heightmapWidthSamples;
  2976. uint heightmapHeightSamples;
  2977. //if (((int)Constants.RegionSize) == 256)
  2978. //{
  2979. // heightmapWidthSamples = 2 * (uint)Constants.RegionSize + 2;
  2980. // heightmapHeightSamples = 2 * (uint)Constants.RegionSize + 2;
  2981. // heightmapWidth++;
  2982. // heightmapHeight++;
  2983. //}
  2984. //else
  2985. //{
  2986. heightmapWidthSamples = (uint)Constants.RegionSize + 1;
  2987. heightmapHeightSamples = (uint)Constants.RegionSize + 1;
  2988. //}
  2989. const float scale = 1.0f;
  2990. const float offset = 0.0f;
  2991. const float thickness = 0.2f;
  2992. const int wrap = 0;
  2993. int regionsize = (int) Constants.RegionSize + 2;
  2994. //Double resolution
  2995. //if (((int)Constants.RegionSize) == 256)
  2996. // heightMap = ResizeTerrain512Interpolation(heightMap);
  2997. // if (((int)Constants.RegionSize) == 256 && (int)Constants.RegionSize == 256)
  2998. // regionsize = 512;
  2999. float hfmin = 2000;
  3000. float hfmax = -2000;
  3001. for (int x = 0; x < heightmapWidthSamples; x++)
  3002. {
  3003. for (int y = 0; y < heightmapHeightSamples; y++)
  3004. {
  3005. int xx = Util.Clip(x - 1, 0, regionsize - 1);
  3006. int yy = Util.Clip(y - 1, 0, regionsize - 1);
  3007. float val= heightMap[yy * (int)Constants.RegionSize + xx];
  3008. _heightmap[x * ((int)Constants.RegionSize + 2) + y] = val;
  3009. hfmin = (val < hfmin) ? val : hfmin;
  3010. hfmax = (val > hfmax) ? val : hfmax;
  3011. }
  3012. }
  3013. lock (OdeLock)
  3014. {
  3015. IntPtr GroundGeom = IntPtr.Zero;
  3016. if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
  3017. {
  3018. RegionTerrain.Remove(pOffset);
  3019. if (GroundGeom != IntPtr.Zero)
  3020. {
  3021. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  3022. {
  3023. TerrainHeightFieldHeights.Remove(GroundGeom);
  3024. }
  3025. d.SpaceRemove(space, GroundGeom);
  3026. d.GeomDestroy(GroundGeom);
  3027. }
  3028. }
  3029. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3030. d.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmap, 0, heightmapWidth + 1, heightmapHeight + 1,
  3031. (int)heightmapWidthSamples + 1, (int)heightmapHeightSamples + 1, scale,
  3032. offset, thickness, wrap);
  3033. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  3034. GroundGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3035. if (GroundGeom != IntPtr.Zero)
  3036. {
  3037. d.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
  3038. d.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
  3039. }
  3040. geom_name_map[GroundGeom] = "Terrain";
  3041. d.Matrix3 R = new d.Matrix3();
  3042. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3043. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3044. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3045. q1 = q1 * q2;
  3046. //q1 = q1 * q3;
  3047. Vector3 v3;
  3048. float angle;
  3049. q1.GetAxisAngle(out v3, out angle);
  3050. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3051. d.GeomSetRotation(GroundGeom, ref R);
  3052. d.GeomSetPosition(GroundGeom, (pOffset.X + ((int)Constants.RegionSize * 0.5f)) - 1, (pOffset.Y + ((int)Constants.RegionSize * 0.5f)) - 1, 0);
  3053. IntPtr testGround = IntPtr.Zero;
  3054. if (RegionTerrain.TryGetValue(pOffset, out testGround))
  3055. {
  3056. RegionTerrain.Remove(pOffset);
  3057. }
  3058. RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
  3059. TerrainHeightFieldHeights.Add(GroundGeom,_heightmap);
  3060. }
  3061. }
  3062. public override void DeleteTerrain()
  3063. {
  3064. }
  3065. public float GetWaterLevel()
  3066. {
  3067. return waterlevel;
  3068. }
  3069. public override bool SupportsCombining()
  3070. {
  3071. return true;
  3072. }
  3073. public override void UnCombine(PhysicsScene pScene)
  3074. {
  3075. IntPtr localGround = IntPtr.Zero;
  3076. // float[] localHeightfield;
  3077. bool proceed = false;
  3078. List<IntPtr> geomDestroyList = new List<IntPtr>();
  3079. lock (OdeLock)
  3080. {
  3081. if (RegionTerrain.TryGetValue(Vector3.Zero, out localGround))
  3082. {
  3083. foreach (IntPtr geom in TerrainHeightFieldHeights.Keys)
  3084. {
  3085. if (geom == localGround)
  3086. {
  3087. // localHeightfield = TerrainHeightFieldHeights[geom];
  3088. proceed = true;
  3089. }
  3090. else
  3091. {
  3092. geomDestroyList.Add(geom);
  3093. }
  3094. }
  3095. if (proceed)
  3096. {
  3097. m_worldOffset = Vector3.Zero;
  3098. WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  3099. m_parentScene = null;
  3100. foreach (IntPtr g in geomDestroyList)
  3101. {
  3102. // removingHeightField needs to be done or the garbage collector will
  3103. // collect the terrain data before we tell ODE to destroy it causing
  3104. // memory corruption
  3105. if (TerrainHeightFieldHeights.ContainsKey(g))
  3106. {
  3107. // float[] removingHeightField = TerrainHeightFieldHeights[g];
  3108. TerrainHeightFieldHeights.Remove(g);
  3109. if (RegionTerrain.ContainsKey(g))
  3110. {
  3111. RegionTerrain.Remove(g);
  3112. }
  3113. d.GeomDestroy(g);
  3114. //removingHeightField = new float[0];
  3115. }
  3116. }
  3117. }
  3118. else
  3119. {
  3120. m_log.Warn("[PHYSICS]: Couldn't proceed with UnCombine. Region has inconsistant data.");
  3121. }
  3122. }
  3123. }
  3124. }
  3125. public override void SetWaterLevel(float baseheight)
  3126. {
  3127. waterlevel = baseheight;
  3128. randomizeWater(waterlevel);
  3129. }
  3130. public void randomizeWater(float baseheight)
  3131. {
  3132. const uint heightmapWidth = m_regionWidth + 2;
  3133. const uint heightmapHeight = m_regionHeight + 2;
  3134. const uint heightmapWidthSamples = m_regionWidth + 2;
  3135. const uint heightmapHeightSamples = m_regionHeight + 2;
  3136. const float scale = 1.0f;
  3137. const float offset = 0.0f;
  3138. const float thickness = 2.9f;
  3139. const int wrap = 0;
  3140. for (int i = 0; i < (258 * 258); i++)
  3141. {
  3142. _watermap[i] = (baseheight-0.1f) + ((float)fluidRandomizer.Next(1,9) / 10f);
  3143. // m_log.Info((baseheight - 0.1f) + ((float)fluidRandomizer.Next(1, 9) / 10f));
  3144. }
  3145. lock (OdeLock)
  3146. {
  3147. if (WaterGeom != IntPtr.Zero)
  3148. {
  3149. d.SpaceRemove(space, WaterGeom);
  3150. }
  3151. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3152. d.GeomHeightfieldDataBuildSingle(HeightmapData, _watermap, 0, heightmapWidth, heightmapHeight,
  3153. (int)heightmapWidthSamples, (int)heightmapHeightSamples, scale,
  3154. offset, thickness, wrap);
  3155. d.GeomHeightfieldDataSetBounds(HeightmapData, m_regionWidth, m_regionHeight);
  3156. WaterGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3157. if (WaterGeom != IntPtr.Zero)
  3158. {
  3159. d.GeomSetCategoryBits(WaterGeom, (int)(CollisionCategories.Water));
  3160. d.GeomSetCollideBits(WaterGeom, (int)(CollisionCategories.Space));
  3161. }
  3162. geom_name_map[WaterGeom] = "Water";
  3163. d.Matrix3 R = new d.Matrix3();
  3164. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3165. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3166. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3167. q1 = q1 * q2;
  3168. //q1 = q1 * q3;
  3169. Vector3 v3;
  3170. float angle;
  3171. q1.GetAxisAngle(out v3, out angle);
  3172. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3173. d.GeomSetRotation(WaterGeom, ref R);
  3174. d.GeomSetPosition(WaterGeom, 128, 128, 0);
  3175. }
  3176. }
  3177. public override void Dispose()
  3178. {
  3179. m_rayCastManager.Dispose();
  3180. m_rayCastManager = null;
  3181. lock (OdeLock)
  3182. {
  3183. lock (_prims)
  3184. {
  3185. foreach (OdePrim prm in _prims)
  3186. {
  3187. RemovePrim(prm);
  3188. }
  3189. }
  3190. //foreach (OdeCharacter act in _characters)
  3191. //{
  3192. //RemoveAvatar(act);
  3193. //}
  3194. d.WorldDestroy(world);
  3195. //d.CloseODE();
  3196. }
  3197. }
  3198. public override Dictionary<uint, float> GetTopColliders()
  3199. {
  3200. Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
  3201. int cnt = 0;
  3202. lock (_prims)
  3203. {
  3204. foreach (OdePrim prm in _prims)
  3205. {
  3206. if (prm.CollisionScore > 0)
  3207. {
  3208. returncolliders.Add(prm.m_localID, prm.CollisionScore);
  3209. cnt++;
  3210. prm.CollisionScore = 0f;
  3211. if (cnt > 25)
  3212. {
  3213. break;
  3214. }
  3215. }
  3216. }
  3217. }
  3218. return returncolliders;
  3219. }
  3220. public override bool SupportsRayCast()
  3221. {
  3222. return true;
  3223. }
  3224. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  3225. {
  3226. if (retMethod != null)
  3227. {
  3228. m_rayCastManager.QueueRequest(position, direction, length, retMethod);
  3229. }
  3230. }
  3231. #if USE_DRAWSTUFF
  3232. // Keyboard callback
  3233. public void command(int cmd)
  3234. {
  3235. IntPtr geom;
  3236. d.Mass mass;
  3237. d.Vector3 sides = new d.Vector3(d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f);
  3238. Char ch = Char.ToLower((Char)cmd);
  3239. switch ((Char)ch)
  3240. {
  3241. case 'w':
  3242. try
  3243. {
  3244. 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));
  3245. xyz.X += rotate.X; xyz.Y += rotate.Y; xyz.Z += rotate.Z;
  3246. ds.SetViewpoint(ref xyz, ref hpr);
  3247. }
  3248. catch (ArgumentException)
  3249. { hpr.X = 0; }
  3250. break;
  3251. case 'a':
  3252. hpr.X++;
  3253. ds.SetViewpoint(ref xyz, ref hpr);
  3254. break;
  3255. case 's':
  3256. try
  3257. {
  3258. 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));
  3259. xyz.X += rotate2.X; xyz.Y += rotate2.Y; xyz.Z += rotate2.Z;
  3260. ds.SetViewpoint(ref xyz, ref hpr);
  3261. }
  3262. catch (ArgumentException)
  3263. { hpr.X = 0; }
  3264. break;
  3265. case 'd':
  3266. hpr.X--;
  3267. ds.SetViewpoint(ref xyz, ref hpr);
  3268. break;
  3269. case 'r':
  3270. xyz.Z++;
  3271. ds.SetViewpoint(ref xyz, ref hpr);
  3272. break;
  3273. case 'f':
  3274. xyz.Z--;
  3275. ds.SetViewpoint(ref xyz, ref hpr);
  3276. break;
  3277. case 'e':
  3278. xyz.Y++;
  3279. ds.SetViewpoint(ref xyz, ref hpr);
  3280. break;
  3281. case 'q':
  3282. xyz.Y--;
  3283. ds.SetViewpoint(ref xyz, ref hpr);
  3284. break;
  3285. }
  3286. }
  3287. public void step(int pause)
  3288. {
  3289. ds.SetColor(1.0f, 1.0f, 0.0f);
  3290. ds.SetTexture(ds.Texture.Wood);
  3291. lock (_prims)
  3292. {
  3293. foreach (OdePrim prm in _prims)
  3294. {
  3295. //IntPtr body = d.GeomGetBody(prm.prim_geom);
  3296. if (prm.prim_geom != IntPtr.Zero)
  3297. {
  3298. d.Vector3 pos;
  3299. d.GeomCopyPosition(prm.prim_geom, out pos);
  3300. //d.BodyCopyPosition(body, out pos);
  3301. d.Matrix3 R;
  3302. d.GeomCopyRotation(prm.prim_geom, out R);
  3303. //d.BodyCopyRotation(body, out R);
  3304. d.Vector3 sides = new d.Vector3();
  3305. sides.X = prm.Size.X;
  3306. sides.Y = prm.Size.Y;
  3307. sides.Z = prm.Size.Z;
  3308. ds.DrawBox(ref pos, ref R, ref sides);
  3309. }
  3310. }
  3311. }
  3312. ds.SetColor(1.0f, 0.0f, 0.0f);
  3313. lock (_characters)
  3314. {
  3315. foreach (OdeCharacter chr in _characters)
  3316. {
  3317. if (chr.Shell != IntPtr.Zero)
  3318. {
  3319. IntPtr body = d.GeomGetBody(chr.Shell);
  3320. d.Vector3 pos;
  3321. d.GeomCopyPosition(chr.Shell, out pos);
  3322. //d.BodyCopyPosition(body, out pos);
  3323. d.Matrix3 R;
  3324. d.GeomCopyRotation(chr.Shell, out R);
  3325. //d.BodyCopyRotation(body, out R);
  3326. ds.DrawCapsule(ref pos, ref R, chr.Size.Z, 0.35f);
  3327. d.Vector3 sides = new d.Vector3();
  3328. sides.X = 0.5f;
  3329. sides.Y = 0.5f;
  3330. sides.Z = 0.5f;
  3331. ds.DrawBox(ref pos, ref R, ref sides);
  3332. }
  3333. }
  3334. }
  3335. }
  3336. public void start(int unused)
  3337. {
  3338. ds.SetViewpoint(ref xyz, ref hpr);
  3339. }
  3340. #endif
  3341. }
  3342. }