OdePlugin.cs 162 KB

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