ODEScene.cs 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823
  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. // Revision 2011/12/13 by Ubit Umarov
  28. //#define SPAM
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Linq;
  32. using System.Reflection;
  33. using System.Runtime.InteropServices;
  34. using System.Threading;
  35. using System.IO;
  36. using System.Diagnostics;
  37. using log4net;
  38. using Nini.Config;
  39. using Mono.Addins;
  40. using OdeAPI;
  41. using OpenSim.Framework;
  42. using OpenSim.Region.Framework.Scenes;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.PhysicsModules.SharedBase;
  45. using OpenMetaverse;
  46. namespace OpenSim.Region.PhysicsModule.ubOde
  47. {
  48. // colision flags of things others can colide with
  49. // rays, sensors, probes removed since can't be colided with
  50. // The top space where things are placed provided further selection
  51. // ie physical are in active space nonphysical in static
  52. // this should be exclusive as possible
  53. [Flags]
  54. public enum CollisionCategories : uint
  55. {
  56. Disabled = 0,
  57. //by 'things' types
  58. Space = 0x01,
  59. Geom = 0x02, // aka prim/part
  60. Character = 0x04,
  61. Land = 0x08,
  62. Water = 0x010,
  63. // by state
  64. Phantom = 0x01000,
  65. VolumeDtc = 0x02000,
  66. Selected = 0x04000,
  67. NoShape = 0x08000,
  68. All = 0xffffffff
  69. }
  70. /// <summary>
  71. /// Material type for a primitive
  72. /// </summary>
  73. public enum Material : int
  74. {
  75. /// <summary></summary>
  76. Stone = 0,
  77. /// <summary></summary>
  78. Metal = 1,
  79. /// <summary></summary>
  80. Glass = 2,
  81. /// <summary></summary>
  82. Wood = 3,
  83. /// <summary></summary>
  84. Flesh = 4,
  85. /// <summary></summary>
  86. Plastic = 5,
  87. /// <summary></summary>
  88. Rubber = 6,
  89. light = 7 // compatibility with old viewers
  90. }
  91. public enum changes : int
  92. {
  93. Add = 0, // arg null. finishs the prim creation. should be used internally only ( to remove later ?)
  94. Remove,
  95. Link, // arg AuroraODEPrim new parent prim or null to delink. Makes the prim part of a object with prim parent as root
  96. // or removes from a object if arg is null
  97. DeLink,
  98. Position, // arg Vector3 new position in world coords. Changes prim position. Prim must know if it is root or child
  99. Orientation, // arg Quaternion new orientation in world coords. Changes prim position. Prim must know it it is root or child
  100. PosOffset, // not in use
  101. // arg Vector3 new position in local coords. Changes prim position in object
  102. OriOffset, // not in use
  103. // arg Vector3 new position in local coords. Changes prim position in object
  104. Velocity,
  105. TargetVelocity,
  106. AngVelocity,
  107. Acceleration,
  108. Force,
  109. Torque,
  110. Momentum,
  111. AddForce,
  112. AddAngForce,
  113. AngLock,
  114. Buoyancy,
  115. PIDTarget,
  116. PIDTau,
  117. PIDActive,
  118. PIDHoverHeight,
  119. PIDHoverType,
  120. PIDHoverTau,
  121. PIDHoverActive,
  122. Size,
  123. AvatarSize,
  124. Shape,
  125. PhysRepData,
  126. AddPhysRep,
  127. CollidesWater,
  128. VolumeDtc,
  129. Physical,
  130. Phantom,
  131. Selected,
  132. disabled,
  133. building,
  134. VehicleType,
  135. VehicleFloatParam,
  136. VehicleVectorParam,
  137. VehicleRotationParam,
  138. VehicleFlags,
  139. SetVehicle,
  140. SetInertia,
  141. Null //keep this last used do dim the methods array. does nothing but pulsing the prim
  142. }
  143. public struct ODEchangeitem
  144. {
  145. public PhysicsActor actor;
  146. public OdeCharacter character;
  147. public changes what;
  148. public Object arg;
  149. }
  150. public class ODEScene : PhysicsScene
  151. {
  152. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  153. public bool m_OSOdeLib = false;
  154. public Scene m_frameWorkScene = null;
  155. // private int threadid = 0;
  156. // const d.ContactFlags comumContactFlags = d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM |d.ContactFlags.Approx1 | d.ContactFlags.Bounce;
  157. const d.ContactFlags comumContactFlags = d.ContactFlags.Bounce | d.ContactFlags.Approx1 | d.ContactFlags.Slip1 | d.ContactFlags.Slip2;
  158. const float comumContactERP = 0.75f;
  159. const float comumContactCFM = 0.0001f;
  160. const float comumContactSLIP = 0f;
  161. float frictionMovementMult = 0.8f;
  162. float TerrainBounce = 0.001f;
  163. float TerrainFriction = 0.3f;
  164. public float AvatarFriction = 0;// 0.9f * 0.5f;
  165. // this netx dimensions are only relevant for terrain partition (mega regions)
  166. // WorldExtents below has the simulation dimensions
  167. // they should be identical except on mega regions
  168. private uint m_regionWidth = Constants.RegionSize;
  169. private uint m_regionHeight = Constants.RegionSize;
  170. public float ODE_STEPSIZE = 0.020f;
  171. public float HalfOdeStep = 0.01f;
  172. public int odetimestepMS = 20; // rounded
  173. private float metersInSpace = 25.6f;
  174. private float m_timeDilation = 1.0f;
  175. private DateTime m_lastframe;
  176. private DateTime m_lastMeshExpire;
  177. public float gravityx = 0f;
  178. public float gravityy = 0f;
  179. public float gravityz = -9.8f;
  180. private float waterlevel = 0f;
  181. private int framecount = 0;
  182. private float avDensity = 80f;
  183. private float avMovementDivisorWalk = 1.3f;
  184. private float avMovementDivisorRun = 0.8f;
  185. private float minimumGroundFlightOffset = 3f;
  186. public float maximumMassObject = 10000.01f;
  187. public float geomDefaultDensity = 10.0f;
  188. public float maximumAngularVelocity = 12.0f; // default 12rad/s
  189. public float maxAngVelocitySQ = 144f; // squared value
  190. public float bodyPIDD = 35f;
  191. public float bodyPIDG = 25;
  192. public int bodyFramesAutoDisable = 5;
  193. private d.NearCallback nearCallback;
  194. private Dictionary<uint,OdePrim> _prims = new Dictionary<uint,OdePrim>();
  195. private HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  196. private HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  197. private HashSet<OdePrim> _activegroups = new HashSet<OdePrim>();
  198. public OpenSim.Framework.LocklessQueue<ODEchangeitem> ChangesQueue = new OpenSim.Framework.LocklessQueue<ODEchangeitem>();
  199. /// <summary>
  200. /// A list of actors that should receive collision events.
  201. /// </summary>
  202. private List<PhysicsActor> _collisionEventPrim = new List<PhysicsActor>();
  203. private List<PhysicsActor> _collisionEventPrimRemove = new List<PhysicsActor>();
  204. private HashSet<OdeCharacter> _badCharacter = new HashSet<OdeCharacter>();
  205. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  206. private float contactsurfacelayer = 0.002f;
  207. private int contactsPerCollision = 80;
  208. internal IntPtr ContactgeomsArray = IntPtr.Zero;
  209. private IntPtr GlobalContactsArray = IntPtr.Zero;
  210. private d.Contact SharedTmpcontact = new d.Contact();
  211. const int maxContactsbeforedeath = 6000;
  212. private volatile int m_global_contactcount = 0;
  213. private IntPtr contactgroup;
  214. public ContactData[] m_materialContactsData = new ContactData[8];
  215. private IntPtr TerrainGeom;
  216. private float[] TerrainHeightFieldHeight;
  217. private GCHandle TerrainHeightFieldHeightsHandler = new GCHandle();
  218. private int m_physicsiterations = 15;
  219. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  220. // private PhysicsActor PANull = new NullPhysicsActor();
  221. private float step_time = 0.0f;
  222. public IntPtr world;
  223. // split the spaces acording to contents type
  224. // ActiveSpace contains characters and active prims
  225. // StaticSpace contains land and other that is mostly static in enviroment
  226. // this can contain subspaces, like the grid in staticspace
  227. // as now space only contains this 2 top spaces
  228. public IntPtr TopSpace; // the global space
  229. public IntPtr ActiveSpace; // space for active prims
  230. public IntPtr CharsSpace; // space for active prims
  231. public IntPtr StaticSpace; // space for the static things around
  232. public IntPtr GroundSpace; // space for ground
  233. // some speedup variables
  234. private int spaceGridMaxX;
  235. private int spaceGridMaxY;
  236. private float spacesPerMeterX;
  237. private float spacesPerMeterY;
  238. // split static geometry collision into a grid as before
  239. private IntPtr[,] staticPrimspace;
  240. private IntPtr[] staticPrimspaceOffRegion;
  241. public Object OdeLock;
  242. public static Object SimulationLock;
  243. public IMesher mesher;
  244. public IConfigSource m_config;
  245. public bool physics_logging = false;
  246. public int physics_logging_interval = 0;
  247. public bool physics_logging_append_existing_logfile = false;
  248. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  249. private ODERayCastRequestManager m_rayCastManager;
  250. public ODEMeshWorker m_meshWorker;
  251. /* maybe needed if ode uses tls
  252. private void checkThread()
  253. {
  254. int th = Thread.CurrentThread.ManagedThreadId;
  255. if(th != threadid)
  256. {
  257. threadid = th;
  258. d.AllocateODEDataForThread(~0U);
  259. }
  260. }
  261. */
  262. IConfig physicsconfig = null;
  263. public ODEScene(Scene pscene, IConfigSource psourceconfig, string pname, string pversion, bool pOSOdeLib)
  264. {
  265. OdeLock = new Object();
  266. EngineType = pname;
  267. PhysicsSceneName = EngineType + "/" + pscene.RegionInfo.RegionName;
  268. EngineName = pname + " " + pversion;
  269. m_config = psourceconfig;
  270. m_OSOdeLib = pOSOdeLib;
  271. // m_OSOdeLib = false; //debug
  272. m_frameWorkScene = pscene;
  273. m_frameWorkScene.RegisterModuleInterface<PhysicsScene>(this);
  274. Initialization();
  275. base.Initialise(m_frameWorkScene.PhysicsRequestAsset,
  276. (m_frameWorkScene.Heightmap != null ? m_frameWorkScene.Heightmap.GetFloatsSerialised() : new float[m_frameWorkScene.RegionInfo.RegionSizeX * m_frameWorkScene.RegionInfo.RegionSizeY]),
  277. (float)m_frameWorkScene.RegionInfo.RegionSettings.WaterHeight);
  278. }
  279. public void RegionLoaded()
  280. {
  281. mesher = m_frameWorkScene.RequestModuleInterface<IMesher>();
  282. if (mesher == null)
  283. {
  284. m_log.ErrorFormat("[ubOde] No mesher. module disabled");
  285. return;
  286. }
  287. m_meshWorker = new ODEMeshWorker(this, m_log, mesher, physicsconfig);
  288. m_frameWorkScene.PhysicsEnabled = true;
  289. }
  290. /// <summary>
  291. /// Initiailizes the scene
  292. /// Sets many properties that ODE requires to be stable
  293. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  294. /// </summary>
  295. private void Initialization()
  296. {
  297. d.AllocateODEDataForThread(~0U);
  298. SimulationLock = new Object();
  299. nearCallback = near;
  300. m_rayCastManager = new ODERayCastRequestManager(this);
  301. WorldExtents.X = m_frameWorkScene.RegionInfo.RegionSizeX;
  302. m_regionWidth = (uint)WorldExtents.X;
  303. WorldExtents.Y = m_frameWorkScene.RegionInfo.RegionSizeY;
  304. m_regionHeight = (uint)WorldExtents.Y;
  305. lock (OdeLock)
  306. {
  307. // Create the world and the first space
  308. try
  309. {
  310. world = d.WorldCreate();
  311. TopSpace = d.HashSpaceCreate(IntPtr.Zero);
  312. // now the major subspaces
  313. ActiveSpace = d.HashSpaceCreate(TopSpace);
  314. CharsSpace = d.HashSpaceCreate(TopSpace);
  315. StaticSpace = d.HashSpaceCreate(TopSpace);
  316. GroundSpace = d.HashSpaceCreate(TopSpace);
  317. }
  318. catch
  319. {
  320. // i must RtC#FM
  321. // i did!
  322. }
  323. d.HashSpaceSetLevels(TopSpace, -5, 12);
  324. d.HashSpaceSetLevels(ActiveSpace, -5, 10);
  325. d.HashSpaceSetLevels(CharsSpace, -4, 3);
  326. d.HashSpaceSetLevels(StaticSpace, -5, 12);
  327. d.HashSpaceSetLevels(GroundSpace, 0, 8);
  328. // demote to second level
  329. d.SpaceSetSublevel(ActiveSpace, 1);
  330. d.SpaceSetSublevel(CharsSpace, 1);
  331. d.SpaceSetSublevel(StaticSpace, 1);
  332. d.SpaceSetSublevel(GroundSpace, 1);
  333. d.GeomSetCategoryBits(ActiveSpace, (uint)(CollisionCategories.Space |
  334. CollisionCategories.Geom |
  335. CollisionCategories.Character |
  336. CollisionCategories.Phantom |
  337. CollisionCategories.VolumeDtc
  338. ));
  339. d.GeomSetCollideBits(ActiveSpace, (uint)(CollisionCategories.Space |
  340. CollisionCategories.Geom |
  341. CollisionCategories.Character |
  342. CollisionCategories.Phantom |
  343. CollisionCategories.VolumeDtc
  344. ));
  345. d.GeomSetCategoryBits(CharsSpace, (uint)(CollisionCategories.Space |
  346. CollisionCategories.Geom |
  347. CollisionCategories.Character |
  348. CollisionCategories.Phantom |
  349. CollisionCategories.VolumeDtc
  350. ));
  351. d.GeomSetCollideBits(CharsSpace, 0);
  352. d.GeomSetCategoryBits(StaticSpace, (uint)(CollisionCategories.Space |
  353. CollisionCategories.Geom |
  354. // CollisionCategories.Land |
  355. // CollisionCategories.Water |
  356. CollisionCategories.Phantom |
  357. CollisionCategories.VolumeDtc
  358. ));
  359. d.GeomSetCollideBits(StaticSpace, 0);
  360. d.GeomSetCategoryBits(GroundSpace, (uint)(CollisionCategories.Land));
  361. d.GeomSetCollideBits(GroundSpace, 0);
  362. contactgroup = d.JointGroupCreate(maxContactsbeforedeath + 1);
  363. //contactgroup
  364. d.WorldSetAutoDisableFlag(world, false);
  365. }
  366. // checkThread();
  367. // Defaults
  368. int contactsPerCollision = 80;
  369. physicsconfig = null;
  370. if (m_config != null)
  371. {
  372. physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  373. if (physicsconfig != null)
  374. {
  375. gravityx = physicsconfig.GetFloat("world_gravityx", gravityx);
  376. gravityy = physicsconfig.GetFloat("world_gravityy", gravityy);
  377. gravityz = physicsconfig.GetFloat("world_gravityz", gravityz);
  378. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", metersInSpace);
  379. // contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", contactsurfacelayer);
  380. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  381. avDensity = physicsconfig.GetFloat("av_density", avDensity);
  382. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", avMovementDivisorWalk);
  383. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", avMovementDivisorRun);
  384. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", contactsPerCollision);
  385. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", geomDefaultDensity);
  386. bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", bodyFramesAutoDisable);
  387. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  388. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  389. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  390. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", minimumGroundFlightOffset);
  391. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", maximumMassObject);
  392. avDensity *= 3f / 80f; // scale other engines density option to this
  393. }
  394. }
  395. float heartbeat = 1/m_frameWorkScene.FrameTime;
  396. maximumAngularVelocity = 0.49f * heartbeat *(float)Math.PI;
  397. maxAngVelocitySQ = maximumAngularVelocity * maximumAngularVelocity;
  398. d.WorldSetCFM(world, comumContactCFM);
  399. d.WorldSetERP(world, comumContactERP);
  400. d.WorldSetGravity(world, gravityx, gravityy, gravityz);
  401. d.WorldSetLinearDamping(world, 0.001f);
  402. d.WorldSetAngularDamping(world, 0.002f);
  403. d.WorldSetAngularDampingThreshold(world, 0f);
  404. d.WorldSetLinearDampingThreshold(world, 0f);
  405. d.WorldSetMaxAngularSpeed(world, maximumAngularVelocity);
  406. d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  407. d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  408. d.WorldSetContactMaxCorrectingVel(world, 60.0f);
  409. HalfOdeStep = ODE_STEPSIZE * 0.5f;
  410. odetimestepMS = (int)(1000.0f * ODE_STEPSIZE + 0.5f);
  411. ContactgeomsArray = Marshal.AllocHGlobal(contactsPerCollision * d.ContactGeom.unmanagedSizeOf);
  412. GlobalContactsArray = Marshal.AllocHGlobal((maxContactsbeforedeath + 100) * d.Contact.unmanagedSizeOf);
  413. SharedTmpcontact.geom.g1 = IntPtr.Zero;
  414. SharedTmpcontact.geom.g2 = IntPtr.Zero;
  415. SharedTmpcontact.geom.side1 = -1;
  416. SharedTmpcontact.geom.side2 = -1;
  417. SharedTmpcontact.surface.mode = comumContactFlags;
  418. SharedTmpcontact.surface.mu = 0;
  419. SharedTmpcontact.surface.bounce = 0;
  420. SharedTmpcontact.surface.bounce_vel = 1.5f;
  421. SharedTmpcontact.surface.soft_cfm = comumContactCFM;
  422. SharedTmpcontact.surface.soft_erp = comumContactERP;
  423. SharedTmpcontact.surface.slip1 = comumContactSLIP;
  424. SharedTmpcontact.surface.slip2 = comumContactSLIP;
  425. m_materialContactsData[(int)Material.Stone].mu = 0.8f;
  426. m_materialContactsData[(int)Material.Stone].bounce = 0.4f;
  427. m_materialContactsData[(int)Material.Metal].mu = 0.3f;
  428. m_materialContactsData[(int)Material.Metal].bounce = 0.4f;
  429. m_materialContactsData[(int)Material.Glass].mu = 0.2f;
  430. m_materialContactsData[(int)Material.Glass].bounce = 0.7f;
  431. m_materialContactsData[(int)Material.Wood].mu = 0.6f;
  432. m_materialContactsData[(int)Material.Wood].bounce = 0.5f;
  433. m_materialContactsData[(int)Material.Flesh].mu = 0.9f;
  434. m_materialContactsData[(int)Material.Flesh].bounce = 0.3f;
  435. m_materialContactsData[(int)Material.Plastic].mu = 0.4f;
  436. m_materialContactsData[(int)Material.Plastic].bounce = 0.7f;
  437. m_materialContactsData[(int)Material.Rubber].mu = 0.9f;
  438. m_materialContactsData[(int)Material.Rubber].bounce = 0.95f;
  439. m_materialContactsData[(int)Material.light].mu = 0.0f;
  440. m_materialContactsData[(int)Material.light].bounce = 0.0f;
  441. spacesPerMeterX = 1.0f / metersInSpace;
  442. spacesPerMeterY = spacesPerMeterX;
  443. spaceGridMaxX = (int)(WorldExtents.X * spacesPerMeterX);
  444. spaceGridMaxY = (int)(WorldExtents.Y * spacesPerMeterY);
  445. if (spaceGridMaxX > 24)
  446. {
  447. spaceGridMaxX = 24;
  448. spacesPerMeterX = spaceGridMaxX / WorldExtents.X;
  449. }
  450. if (spaceGridMaxY > 24)
  451. {
  452. spaceGridMaxY = 24;
  453. spacesPerMeterY = spaceGridMaxY / WorldExtents.Y;
  454. }
  455. staticPrimspace = new IntPtr[spaceGridMaxX, spaceGridMaxY];
  456. // create all spaces now
  457. int i, j;
  458. IntPtr newspace;
  459. for (i = 0; i < spaceGridMaxX; i++)
  460. for (j = 0; j < spaceGridMaxY; j++)
  461. {
  462. newspace = d.HashSpaceCreate(StaticSpace);
  463. d.GeomSetCategoryBits(newspace, (int)CollisionCategories.Space);
  464. waitForSpaceUnlock(newspace);
  465. d.SpaceSetSublevel(newspace, 2);
  466. d.HashSpaceSetLevels(newspace, -2, 8);
  467. d.GeomSetCategoryBits(newspace, (uint)(CollisionCategories.Space |
  468. CollisionCategories.Geom |
  469. CollisionCategories.Land |
  470. CollisionCategories.Water |
  471. CollisionCategories.Phantom |
  472. CollisionCategories.VolumeDtc
  473. ));
  474. d.GeomSetCollideBits(newspace, 0);
  475. staticPrimspace[i, j] = newspace;
  476. }
  477. // let this now be index limit
  478. spaceGridMaxX--;
  479. spaceGridMaxY--;
  480. // create 4 off world spaces (x<0,x>max,y<0,y>max)
  481. staticPrimspaceOffRegion = new IntPtr[4];
  482. for (i = 0; i < 4; i++)
  483. {
  484. newspace = d.HashSpaceCreate(StaticSpace);
  485. d.GeomSetCategoryBits(newspace, (int)CollisionCategories.Space);
  486. waitForSpaceUnlock(newspace);
  487. d.SpaceSetSublevel(newspace, 2);
  488. d.HashSpaceSetLevels(newspace, -2, 8);
  489. d.GeomSetCategoryBits(newspace, (uint)(CollisionCategories.Space |
  490. CollisionCategories.Geom |
  491. CollisionCategories.Land |
  492. CollisionCategories.Water |
  493. CollisionCategories.Phantom |
  494. CollisionCategories.VolumeDtc
  495. ));
  496. d.GeomSetCollideBits(newspace, 0);
  497. staticPrimspaceOffRegion[i] = newspace;
  498. }
  499. m_lastframe = DateTime.UtcNow;
  500. m_lastMeshExpire = m_lastframe;
  501. }
  502. internal void waitForSpaceUnlock(IntPtr space)
  503. {
  504. //if (space != IntPtr.Zero)
  505. //while (d.SpaceLockQuery(space)) { } // Wait and do nothing
  506. }
  507. #region Collision Detection
  508. // sets a global contact for a joint for contactgeom , and base contact description)
  509. private IntPtr CreateContacJoint(ref d.ContactGeom contactGeom,bool smooth)
  510. {
  511. if (m_global_contactcount >= maxContactsbeforedeath)
  512. return IntPtr.Zero;
  513. m_global_contactcount++;
  514. if(smooth)
  515. SharedTmpcontact.geom.depth = contactGeom.depth * 0.05f;
  516. else
  517. SharedTmpcontact.geom.depth = contactGeom.depth;
  518. SharedTmpcontact.geom.pos = contactGeom.pos;
  519. SharedTmpcontact.geom.normal = contactGeom.normal;
  520. IntPtr contact = new IntPtr(GlobalContactsArray.ToInt64() + (Int64)(m_global_contactcount * d.Contact.unmanagedSizeOf));
  521. Marshal.StructureToPtr(SharedTmpcontact, contact, true);
  522. return d.JointCreateContactPtr(world, contactgroup, contact);
  523. }
  524. private bool GetCurContactGeom(int index, ref d.ContactGeom newcontactgeom)
  525. {
  526. if (ContactgeomsArray == IntPtr.Zero || index >= contactsPerCollision)
  527. return false;
  528. IntPtr contactptr = new IntPtr(ContactgeomsArray.ToInt64() + (Int64)(index * d.ContactGeom.unmanagedSizeOf));
  529. newcontactgeom = (d.ContactGeom)Marshal.PtrToStructure(contactptr, typeof(d.ContactGeom));
  530. return true;
  531. }
  532. /// <summary>
  533. /// This is our near callback. A geometry is near a body
  534. /// </summary>
  535. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  536. /// <param name="g1">a geometry or space</param>
  537. /// <param name="g2">another geometry or space</param>
  538. ///
  539. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  540. {
  541. // no lock here! It's invoked from within Simulate(), which is thread-locked
  542. if (m_global_contactcount >= maxContactsbeforedeath)
  543. return;
  544. // Test if we're colliding a geom with a space.
  545. // If so we have to drill down into the space recursively
  546. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  547. return;
  548. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  549. {
  550. // We'll be calling near recursivly if one
  551. // of them is a space to find all of the
  552. // contact points in the space
  553. try
  554. {
  555. d.SpaceCollide2(g1, g2, IntPtr.Zero, nearCallback);
  556. }
  557. catch (AccessViolationException)
  558. {
  559. m_log.Warn("[PHYSICS]: Unable to collide test a space");
  560. return;
  561. }
  562. //here one should check collisions of geoms inside a space
  563. // but on each space we only should have geoms that not colide amoung each other
  564. // so we don't dig inside spaces
  565. return;
  566. }
  567. // get geom bodies to check if we already a joint contact
  568. // guess this shouldn't happen now
  569. IntPtr b1 = d.GeomGetBody(g1);
  570. IntPtr b2 = d.GeomGetBody(g2);
  571. // d.GeomClassID id = d.GeomGetClass(g1);
  572. // Figure out how many contact points we have
  573. int count = 0;
  574. try
  575. {
  576. // Colliding Geom To Geom
  577. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  578. if (g1 == g2)
  579. return; // Can't collide with yourself
  580. // if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
  581. // return;
  582. /*
  583. // debug
  584. PhysicsActor dp2;
  585. if (d.GeomGetClass(g1) == d.GeomClassID.HeightfieldClass)
  586. {
  587. d.AABB aabb;
  588. d.GeomGetAABB(g2, out aabb);
  589. float x = aabb.MaxX - aabb.MinX;
  590. float y = aabb.MaxY - aabb.MinY;
  591. float z = aabb.MaxZ - aabb.MinZ;
  592. if (x > 60.0f || y > 60.0f || z > 60.0f)
  593. {
  594. if (!actor_name_map.TryGetValue(g2, out dp2))
  595. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 2");
  596. else
  597. m_log.WarnFormat("[PHYSICS]: land versus large prim geo {0},size {1}, AABBsize <{2},{3},{4}>, at {5} ori {6},({7})",
  598. dp2.Name, dp2.Size, x, y, z,
  599. dp2.Position.ToString(),
  600. dp2.Orientation.ToString(),
  601. dp2.Orientation.Length());
  602. return;
  603. }
  604. }
  605. //
  606. */
  607. if (d.GeomGetCategoryBits(g1) == (uint)CollisionCategories.VolumeDtc ||
  608. d.GeomGetCategoryBits(g2) == (uint)CollisionCategories.VolumeDtc)
  609. {
  610. int cflags;
  611. unchecked
  612. {
  613. cflags = (int)(1 | d.CONTACTS_UNIMPORTANT);
  614. }
  615. count = d.CollidePtr(g1, g2, cflags, ContactgeomsArray, d.ContactGeom.unmanagedSizeOf);
  616. }
  617. else
  618. count = d.CollidePtr(g1, g2, (contactsPerCollision & 0xffff), ContactgeomsArray, d.ContactGeom.unmanagedSizeOf);
  619. }
  620. catch (SEHException)
  621. {
  622. 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.");
  623. // ode.drelease(world);
  624. base.TriggerPhysicsBasedRestart();
  625. }
  626. catch (Exception e)
  627. {
  628. m_log.WarnFormat("[PHYSICS]: Unable to collide test an object: {0}", e.Message);
  629. return;
  630. }
  631. // contacts done
  632. if (count == 0)
  633. return;
  634. // try get physical actors
  635. PhysicsActor p1;
  636. PhysicsActor p2;
  637. if (!actor_name_map.TryGetValue(g1, out p1))
  638. {
  639. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 1");
  640. return;
  641. }
  642. if (!actor_name_map.TryGetValue(g2, out p2))
  643. {
  644. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 2");
  645. return;
  646. }
  647. // get first contact
  648. d.ContactGeom curContact = new d.ContactGeom();
  649. if (!GetCurContactGeom(0, ref curContact))
  650. return;
  651. ContactPoint maxDepthContact = new ContactPoint();
  652. // do volume detection case
  653. if ((p1.IsVolumeDtc || p2.IsVolumeDtc))
  654. {
  655. maxDepthContact = new ContactPoint(
  656. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  657. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  658. curContact.depth, false
  659. );
  660. collision_accounting_events(p1, p2, maxDepthContact);
  661. return;
  662. }
  663. // big messy collision analises
  664. float mu = 0;
  665. float bounce = 0;
  666. // bool IgnoreNegSides = false;
  667. ContactData contactdata1 = new ContactData(0, 0, false);
  668. ContactData contactdata2 = new ContactData(0, 0, false);
  669. bool dop1ava = false;
  670. bool dop2ava = false;
  671. bool ignore = false;
  672. bool smoothMesh = false;
  673. switch (p1.PhysicsActorType)
  674. {
  675. case (int)ActorTypes.Agent:
  676. {
  677. dop1ava = true;
  678. switch (p2.PhysicsActorType)
  679. {
  680. case (int)ActorTypes.Agent:
  681. case (int)ActorTypes.Prim:
  682. break;
  683. default:
  684. ignore = true; // avatar to terrain and water ignored
  685. break;
  686. }
  687. break;
  688. }
  689. case (int)ActorTypes.Prim:
  690. {
  691. switch (p2.PhysicsActorType)
  692. {
  693. case (int)ActorTypes.Agent:
  694. dop2ava = true;
  695. break;
  696. case (int)ActorTypes.Prim:
  697. Vector3 relV = p1.rootVelocity - p2.rootVelocity;
  698. float relVlenSQ = relV.LengthSquared();
  699. if (relVlenSQ > 0.0001f)
  700. {
  701. p1.CollidingObj = true;
  702. p2.CollidingObj = true;
  703. }
  704. p1.getContactData(ref contactdata1);
  705. p2.getContactData(ref contactdata2);
  706. bounce = contactdata1.bounce * contactdata2.bounce;
  707. mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
  708. if (relVlenSQ > 0.01f)
  709. mu *= frictionMovementMult;
  710. if(d.GeomGetClass(g2) == d.GeomClassID.TriMeshClass &&
  711. d.GeomGetClass(g1) == d.GeomClassID.TriMeshClass)
  712. smoothMesh = true;
  713. break;
  714. case (int)ActorTypes.Ground:
  715. p1.getContactData(ref contactdata1);
  716. bounce = contactdata1.bounce * TerrainBounce;
  717. mu = (float)Math.Sqrt(contactdata1.mu * TerrainFriction);
  718. Vector3 v1 = p1.rootVelocity;
  719. if (Math.Abs(v1.X) > 0.1f || Math.Abs(v1.Y) > 0.1f)
  720. mu *= frictionMovementMult;
  721. p1.CollidingGround = true;
  722. if(d.GeomGetClass(g1) == d.GeomClassID.TriMeshClass)
  723. smoothMesh = true;
  724. break;
  725. case (int)ActorTypes.Water:
  726. default:
  727. ignore = true;
  728. break;
  729. }
  730. }
  731. break;
  732. case (int)ActorTypes.Ground:
  733. if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  734. {
  735. p2.CollidingGround = true;
  736. p2.getContactData(ref contactdata2);
  737. bounce = contactdata2.bounce * TerrainBounce;
  738. mu = (float)Math.Sqrt(contactdata2.mu * TerrainFriction);
  739. // if (curContact.side1 > 0) // should be 2 ?
  740. // IgnoreNegSides = true;
  741. Vector3 v2 = p2.rootVelocity;
  742. if (Math.Abs(v2.X) > 0.1f || Math.Abs(v2.Y) > 0.1f)
  743. mu *= frictionMovementMult;
  744. if(d.GeomGetClass(g2) == d.GeomClassID.TriMeshClass)
  745. smoothMesh = true;
  746. }
  747. else
  748. ignore = true;
  749. break;
  750. case (int)ActorTypes.Water:
  751. default:
  752. break;
  753. }
  754. if (ignore)
  755. return;
  756. IntPtr Joint;
  757. bool FeetCollision = false;
  758. int ncontacts = 0;
  759. int i = 0;
  760. maxDepthContact = new ContactPoint();
  761. maxDepthContact.PenetrationDepth = float.MinValue;
  762. ContactPoint minDepthContact = new ContactPoint();
  763. minDepthContact.PenetrationDepth = float.MaxValue;
  764. SharedTmpcontact.geom.depth = 0;
  765. SharedTmpcontact.surface.mu = mu;
  766. SharedTmpcontact.surface.bounce = bounce;
  767. d.ContactGeom altContact = new d.ContactGeom();
  768. bool useAltcontact = false;
  769. bool noskip = true;
  770. if(dop1ava || dop2ava)
  771. smoothMesh = false;
  772. while (true)
  773. {
  774. noskip = true;
  775. useAltcontact = false;
  776. if (dop1ava)
  777. {
  778. if ((((OdeCharacter)p1).Collide(g1, g2, false, ref curContact, ref altContact , ref useAltcontact, ref FeetCollision)))
  779. {
  780. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  781. {
  782. p1.CollidingObj = true;
  783. p2.CollidingObj = true;
  784. }
  785. else if (p2.rootVelocity.LengthSquared() > 0.0f)
  786. p2.CollidingObj = true;
  787. }
  788. else
  789. noskip = false;
  790. }
  791. else if (dop2ava)
  792. {
  793. if ((((OdeCharacter)p2).Collide(g2, g1, true, ref curContact, ref altContact , ref useAltcontact, ref FeetCollision)))
  794. {
  795. if (p1.PhysicsActorType == (int)ActorTypes.Agent)
  796. {
  797. p1.CollidingObj = true;
  798. p2.CollidingObj = true;
  799. }
  800. else if (p1.rootVelocity.LengthSquared() > 0.0f)
  801. p1.CollidingObj = true;
  802. }
  803. else
  804. noskip = false;
  805. }
  806. if (noskip)
  807. {
  808. if(useAltcontact)
  809. Joint = CreateContacJoint(ref altContact,smoothMesh);
  810. else
  811. Joint = CreateContacJoint(ref curContact,smoothMesh);
  812. if (Joint == IntPtr.Zero)
  813. break;
  814. d.JointAttach(Joint, b1, b2);
  815. ncontacts++;
  816. if (curContact.depth > maxDepthContact.PenetrationDepth)
  817. {
  818. maxDepthContact.Position.X = curContact.pos.X;
  819. maxDepthContact.Position.Y = curContact.pos.Y;
  820. maxDepthContact.Position.Z = curContact.pos.Z;
  821. maxDepthContact.PenetrationDepth = curContact.depth;
  822. maxDepthContact.CharacterFeet = FeetCollision;
  823. }
  824. if (curContact.depth < minDepthContact.PenetrationDepth)
  825. {
  826. minDepthContact.PenetrationDepth = curContact.depth;
  827. minDepthContact.SurfaceNormal.X = curContact.normal.X;
  828. minDepthContact.SurfaceNormal.Y = curContact.normal.Y;
  829. minDepthContact.SurfaceNormal.Z = curContact.normal.Z;
  830. }
  831. }
  832. if (++i >= count)
  833. break;
  834. if (!GetCurContactGeom(i, ref curContact))
  835. break;
  836. }
  837. if (ncontacts > 0)
  838. {
  839. maxDepthContact.SurfaceNormal.X = minDepthContact.SurfaceNormal.X;
  840. maxDepthContact.SurfaceNormal.Y = minDepthContact.SurfaceNormal.Y;
  841. maxDepthContact.SurfaceNormal.Z = minDepthContact.SurfaceNormal.Z;
  842. collision_accounting_events(p1, p2, maxDepthContact);
  843. }
  844. }
  845. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  846. {
  847. uint obj2LocalID = 0;
  848. // update actors collision score
  849. if (p1.CollisionScore < float.MaxValue)
  850. p1.CollisionScore += 1.0f;
  851. if (p2.CollisionScore < float.MaxValue)
  852. p2.CollisionScore += 1.0f;
  853. bool p1events = p1.SubscribedEvents();
  854. bool p2events = p2.SubscribedEvents();
  855. if (p1.IsVolumeDtc)
  856. p2events = false;
  857. if (p2.IsVolumeDtc)
  858. p1events = false;
  859. if (!p2events && !p1events)
  860. return;
  861. Vector3 vel = Vector3.Zero;
  862. if (p2 != null && p2.IsPhysical)
  863. vel = p2.rootVelocity;
  864. if (p1 != null && p1.IsPhysical)
  865. vel -= p1.rootVelocity;
  866. contact.RelativeSpeed = Vector3.Dot(vel, contact.SurfaceNormal);
  867. switch ((ActorTypes)p1.PhysicsActorType)
  868. {
  869. case ActorTypes.Agent:
  870. case ActorTypes.Prim:
  871. {
  872. switch ((ActorTypes)p2.PhysicsActorType)
  873. {
  874. case ActorTypes.Agent:
  875. case ActorTypes.Prim:
  876. if (p2events)
  877. {
  878. //AddCollisionEventReporting(p2);
  879. p2.AddCollisionEvent(p1.ParentActor.LocalID, contact);
  880. }
  881. else if(p1.IsVolumeDtc)
  882. p2.AddVDTCCollisionEvent(p1.ParentActor.LocalID, contact);
  883. obj2LocalID = p2.ParentActor.LocalID;
  884. break;
  885. case ActorTypes.Ground:
  886. case ActorTypes.Unknown:
  887. default:
  888. obj2LocalID = 0;
  889. break;
  890. }
  891. if (p1events)
  892. {
  893. contact.SurfaceNormal = -contact.SurfaceNormal;
  894. contact.RelativeSpeed = -contact.RelativeSpeed;
  895. //AddCollisionEventReporting(p1);
  896. p1.AddCollisionEvent(obj2LocalID, contact);
  897. }
  898. else if(p2.IsVolumeDtc)
  899. {
  900. contact.SurfaceNormal = -contact.SurfaceNormal;
  901. contact.RelativeSpeed = -contact.RelativeSpeed;
  902. //AddCollisionEventReporting(p1);
  903. p1.AddVDTCCollisionEvent(obj2LocalID, contact);
  904. }
  905. break;
  906. }
  907. case ActorTypes.Ground:
  908. case ActorTypes.Unknown:
  909. default:
  910. {
  911. if (p2events && !p2.IsVolumeDtc)
  912. {
  913. //AddCollisionEventReporting(p2);
  914. p2.AddCollisionEvent(0, contact);
  915. }
  916. break;
  917. }
  918. }
  919. }
  920. /// <summary>
  921. /// This is our collision testing routine in ODE
  922. /// </summary>
  923. /// <param name="timeStep"></param>
  924. private void collision_optimized()
  925. {
  926. lock (_characters)
  927. {
  928. try
  929. {
  930. foreach (OdeCharacter chr in _characters)
  931. {
  932. if (chr == null)
  933. continue;
  934. chr.IsColliding = false;
  935. // chr.CollidingGround = false; not done here
  936. chr.CollidingObj = false;
  937. if(chr.Body == IntPtr.Zero || chr.collider == IntPtr.Zero )
  938. continue;
  939. // do colisions with static space
  940. d.SpaceCollide2(chr.collider, StaticSpace, IntPtr.Zero, nearCallback);
  941. // no coll with gnd
  942. }
  943. // chars with chars
  944. d.SpaceCollide(CharsSpace, IntPtr.Zero, nearCallback);
  945. }
  946. catch (AccessViolationException)
  947. {
  948. m_log.Warn("[PHYSICS]: Unable to collide Character to static space");
  949. }
  950. }
  951. lock (_activeprims)
  952. {
  953. foreach (OdePrim aprim in _activeprims)
  954. {
  955. aprim.CollisionScore = 0;
  956. aprim.IsColliding = false;
  957. if(!aprim.m_outbounds && d.BodyIsEnabled(aprim.Body))
  958. aprim.clearSleeperCollisions();
  959. }
  960. }
  961. lock (_activegroups)
  962. {
  963. try
  964. {
  965. foreach (OdePrim aprim in _activegroups)
  966. {
  967. if(!aprim.m_outbounds && d.BodyIsEnabled(aprim.Body) &&
  968. aprim.collide_geom != IntPtr.Zero)
  969. {
  970. d.SpaceCollide2(StaticSpace, aprim.collide_geom, IntPtr.Zero, nearCallback);
  971. d.SpaceCollide2(GroundSpace, aprim.collide_geom, IntPtr.Zero, nearCallback);
  972. }
  973. }
  974. }
  975. catch (Exception e)
  976. {
  977. m_log.Warn("[PHYSICS]: Unable to collide Active to Static: " + e.Message);
  978. }
  979. }
  980. // colide active amoung them
  981. try
  982. {
  983. d.SpaceCollide(ActiveSpace, IntPtr.Zero, nearCallback);
  984. }
  985. catch (Exception e)
  986. {
  987. m_log.Warn("[PHYSICS]: Unable to collide in Active: " + e.Message);
  988. }
  989. // and with chars
  990. try
  991. {
  992. d.SpaceCollide2(CharsSpace,ActiveSpace, IntPtr.Zero, nearCallback);
  993. }
  994. catch (Exception e)
  995. {
  996. m_log.Warn("[PHYSICS]: Unable to collide Active to Character: " + e.Message);
  997. }
  998. }
  999. #endregion
  1000. /// <summary>
  1001. /// Add actor to the list that should receive collision events in the simulate loop.
  1002. /// </summary>
  1003. /// <param name="obj"></param>
  1004. public void AddCollisionEventReporting(PhysicsActor obj)
  1005. {
  1006. if (!_collisionEventPrim.Contains(obj))
  1007. _collisionEventPrim.Add(obj);
  1008. }
  1009. /// <summary>
  1010. /// Remove actor from the list that should receive collision events in the simulate loop.
  1011. /// </summary>
  1012. /// <param name="obj"></param>
  1013. public void RemoveCollisionEventReporting(PhysicsActor obj)
  1014. {
  1015. lock(_collisionEventPrimRemove)
  1016. {
  1017. if (_collisionEventPrim.Contains(obj) && !_collisionEventPrimRemove.Contains(obj))
  1018. _collisionEventPrimRemove.Add(obj);
  1019. }
  1020. }
  1021. public override float TimeDilation
  1022. {
  1023. get { return m_timeDilation; }
  1024. }
  1025. public override bool SupportsNINJAJoints
  1026. {
  1027. get { return false; }
  1028. }
  1029. #region Add/Remove Entities
  1030. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  1031. {
  1032. return null;
  1033. }
  1034. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, float feetOffset, bool isFlying)
  1035. {
  1036. OdeCharacter newAv = new OdeCharacter(localID, avName, this, position,
  1037. size, feetOffset, avDensity, avMovementDivisorWalk, avMovementDivisorRun);
  1038. newAv.Flying = isFlying;
  1039. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1040. return newAv;
  1041. }
  1042. public void AddCharacter(OdeCharacter chr)
  1043. {
  1044. lock (_characters)
  1045. {
  1046. if (!_characters.Contains(chr))
  1047. {
  1048. _characters.Add(chr);
  1049. if (chr.bad)
  1050. m_log.DebugFormat("[PHYSICS] Added BAD actor {0} to characters list", chr.m_uuid);
  1051. }
  1052. }
  1053. }
  1054. public void RemoveCharacter(OdeCharacter chr)
  1055. {
  1056. lock (_characters)
  1057. {
  1058. if (_characters.Contains(chr))
  1059. {
  1060. _characters.Remove(chr);
  1061. }
  1062. }
  1063. }
  1064. public void BadCharacter(OdeCharacter chr)
  1065. {
  1066. lock (_badCharacter)
  1067. {
  1068. if (!_badCharacter.Contains(chr))
  1069. _badCharacter.Add(chr);
  1070. }
  1071. }
  1072. public override void RemoveAvatar(PhysicsActor actor)
  1073. {
  1074. //m_log.Debug("[PHYSICS]:ODELOCK");
  1075. lock (OdeLock)
  1076. {
  1077. d.AllocateODEDataForThread(0);
  1078. ((OdeCharacter) actor).Destroy();
  1079. }
  1080. }
  1081. public void addActivePrim(OdePrim activatePrim)
  1082. {
  1083. // adds active prim..
  1084. lock (_activeprims)
  1085. {
  1086. if (!_activeprims.Contains(activatePrim))
  1087. _activeprims.Add(activatePrim);
  1088. }
  1089. }
  1090. public void addActiveGroups(OdePrim activatePrim)
  1091. {
  1092. lock (_activegroups)
  1093. {
  1094. if (!_activegroups.Contains(activatePrim))
  1095. _activegroups.Add(activatePrim);
  1096. }
  1097. }
  1098. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1099. PrimitiveBaseShape pbs, bool isphysical, bool isPhantom, byte shapeType, uint localID)
  1100. {
  1101. OdePrim newPrim;
  1102. lock (OdeLock)
  1103. {
  1104. newPrim = new OdePrim(name, this, position, size, rotation, pbs, isphysical, isPhantom, shapeType, localID);
  1105. }
  1106. return newPrim;
  1107. }
  1108. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1109. Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, uint localid)
  1110. {
  1111. return AddPrim(primName, position, size, rotation, pbs, isPhysical, isPhantom, 0 , localid);
  1112. }
  1113. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1114. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1115. {
  1116. return AddPrim(primName, position, size, rotation, pbs, isPhysical,false, 0, localid);
  1117. }
  1118. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1119. Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapeType, uint localid)
  1120. {
  1121. return AddPrim(primName, position, size, rotation, pbs, isPhysical,isPhantom, shapeType, localid);
  1122. }
  1123. public void remActivePrim(OdePrim deactivatePrim)
  1124. {
  1125. lock (_activeprims)
  1126. {
  1127. _activeprims.Remove(deactivatePrim);
  1128. }
  1129. }
  1130. public void remActiveGroup(OdePrim deactivatePrim)
  1131. {
  1132. lock (_activegroups)
  1133. {
  1134. _activegroups.Remove(deactivatePrim);
  1135. }
  1136. }
  1137. public override void RemovePrim(PhysicsActor prim)
  1138. {
  1139. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  1140. // removed in the next physics simulate pass.
  1141. if (prim is OdePrim)
  1142. {
  1143. // lock (OdeLock)
  1144. {
  1145. OdePrim p = (OdePrim)prim;
  1146. p.setPrimForRemoval();
  1147. }
  1148. }
  1149. }
  1150. public void RemovePrimThreadLocked(OdePrim prim)
  1151. {
  1152. //Console.WriteLine("RemovePrimThreadLocked " + prim.m_primName);
  1153. lock (prim)
  1154. {
  1155. // RemoveCollisionEventReporting(prim);
  1156. lock (_prims)
  1157. _prims.Remove(prim.LocalID);
  1158. }
  1159. }
  1160. public void addToPrims(OdePrim prim)
  1161. {
  1162. lock (_prims)
  1163. _prims[prim.LocalID] = prim;
  1164. }
  1165. public OdePrim getPrim(uint id)
  1166. {
  1167. lock (_prims)
  1168. {
  1169. if(_prims.ContainsKey(id))
  1170. return _prims[id];
  1171. else
  1172. return null;
  1173. }
  1174. }
  1175. public bool havePrim(OdePrim prm)
  1176. {
  1177. lock (_prims)
  1178. return _prims.ContainsKey(prm.LocalID);
  1179. }
  1180. public void changePrimID(OdePrim prim,uint oldID)
  1181. {
  1182. lock (_prims)
  1183. {
  1184. if(_prims.ContainsKey(oldID))
  1185. _prims.Remove(oldID);
  1186. _prims[prim.LocalID] = prim;
  1187. }
  1188. }
  1189. public bool haveActor(PhysicsActor actor)
  1190. {
  1191. if (actor is OdePrim)
  1192. {
  1193. lock (_prims)
  1194. return _prims.ContainsKey(((OdePrim)actor).LocalID);
  1195. }
  1196. else if (actor is OdeCharacter)
  1197. {
  1198. lock (_characters)
  1199. return _characters.Contains((OdeCharacter)actor);
  1200. }
  1201. return false;
  1202. }
  1203. #endregion
  1204. #region Space Separation Calculation
  1205. /// <summary>
  1206. /// Called when a static prim moves or becomes static
  1207. /// Places the prim in a space one the static sub-spaces grid
  1208. /// </summary>
  1209. /// <param name="geom">the pointer to the geom that moved</param>
  1210. /// <param name="pos">the position that the geom moved to</param>
  1211. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1212. /// <returns>a pointer to the new space it's in</returns>
  1213. public IntPtr MoveGeomToStaticSpace(IntPtr geom, Vector3 pos, IntPtr currentspace)
  1214. {
  1215. // moves a prim into another static sub-space or from another space into a static sub-space
  1216. // Called ODEPrim so
  1217. // it's already in locked space.
  1218. if (geom == IntPtr.Zero) // shouldn't happen
  1219. return IntPtr.Zero;
  1220. // get the static sub-space for current position
  1221. IntPtr newspace = calculateSpaceForGeom(pos);
  1222. if (newspace == currentspace) // if we are there all done
  1223. return newspace;
  1224. // else remove it from its current space
  1225. if (currentspace != IntPtr.Zero && d.SpaceQuery(currentspace, geom))
  1226. {
  1227. if (d.GeomIsSpace(currentspace))
  1228. {
  1229. waitForSpaceUnlock(currentspace);
  1230. d.SpaceRemove(currentspace, geom);
  1231. if (d.SpaceGetSublevel(currentspace) > 2 && d.SpaceGetNumGeoms(currentspace) == 0)
  1232. {
  1233. d.SpaceDestroy(currentspace);
  1234. }
  1235. }
  1236. else
  1237. {
  1238. m_log.Info("[Physics]: Invalid or empty Space passed to 'MoveGeomToStaticSpace':" + currentspace +
  1239. " Geom:" + geom);
  1240. }
  1241. }
  1242. else // odd currentspace is null or doesn't contain the geom? lets try the geom ideia of current space
  1243. {
  1244. currentspace = d.GeomGetSpace(geom);
  1245. if (currentspace != IntPtr.Zero)
  1246. {
  1247. if (d.GeomIsSpace(currentspace))
  1248. {
  1249. waitForSpaceUnlock(currentspace);
  1250. d.SpaceRemove(currentspace, geom);
  1251. if (d.SpaceGetSublevel(currentspace) > 2 && d.SpaceGetNumGeoms(currentspace) == 0)
  1252. {
  1253. d.SpaceDestroy(currentspace);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. // put the geom in the newspace
  1259. waitForSpaceUnlock(newspace);
  1260. d.SpaceAdd(newspace, geom);
  1261. // let caller know this newspace
  1262. return newspace;
  1263. }
  1264. /// <summary>
  1265. /// Calculates the space the prim should be in by its position
  1266. /// </summary>
  1267. /// <param name="pos"></param>
  1268. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  1269. public IntPtr calculateSpaceForGeom(Vector3 pos)
  1270. {
  1271. int x, y;
  1272. if (pos.X < 0)
  1273. return staticPrimspaceOffRegion[0];
  1274. if (pos.Y < 0)
  1275. return staticPrimspaceOffRegion[2];
  1276. x = (int)(pos.X * spacesPerMeterX);
  1277. if (x > spaceGridMaxX)
  1278. return staticPrimspaceOffRegion[1];
  1279. y = (int)(pos.Y * spacesPerMeterY);
  1280. if (y > spaceGridMaxY)
  1281. return staticPrimspaceOffRegion[3];
  1282. return staticPrimspace[x, y];
  1283. }
  1284. #endregion
  1285. /// <summary>
  1286. /// Called to queue a change to a actor
  1287. /// to use in place of old taint mechanism so changes do have a time sequence
  1288. /// </summary>
  1289. public void AddChange(PhysicsActor actor, changes what, Object arg)
  1290. {
  1291. ODEchangeitem item = new ODEchangeitem();
  1292. item.actor = actor;
  1293. item.what = what;
  1294. item.arg = arg;
  1295. ChangesQueue.Enqueue(item);
  1296. }
  1297. /// <summary>
  1298. /// Called after our prim properties are set Scale, position etc.
  1299. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  1300. /// This assures us that we have no race conditions
  1301. /// </summary>
  1302. /// <param name="prim"></param>
  1303. public override void AddPhysicsActorTaint(PhysicsActor prim)
  1304. {
  1305. }
  1306. // does all pending changes generated during region load process
  1307. public override void ProcessPreSimulation()
  1308. {
  1309. lock (OdeLock)
  1310. {
  1311. if (world == IntPtr.Zero)
  1312. {
  1313. ChangesQueue.Clear();
  1314. return;
  1315. }
  1316. d.AllocateODEDataForThread(~0U);
  1317. ODEchangeitem item;
  1318. int donechanges = 0;
  1319. if (ChangesQueue.Count > 0)
  1320. {
  1321. m_log.InfoFormat("[ubOde] start processing pending actor operations");
  1322. int tstart = Util.EnvironmentTickCount();
  1323. while (ChangesQueue.Dequeue(out item))
  1324. {
  1325. if (item.actor != null)
  1326. {
  1327. try
  1328. {
  1329. if (item.actor is OdeCharacter)
  1330. ((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
  1331. else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
  1332. RemovePrimThreadLocked((OdePrim)item.actor);
  1333. }
  1334. catch
  1335. {
  1336. m_log.WarnFormat("[PHYSICS]: Operation failed for a actor {0} {1}",
  1337. item.actor.Name, item.what.ToString());
  1338. }
  1339. }
  1340. donechanges++;
  1341. }
  1342. int time = Util.EnvironmentTickCountSubtract(tstart);
  1343. m_log.InfoFormat("[ubOde] finished {0} operations in {1}ms", donechanges, time);
  1344. }
  1345. m_log.InfoFormat("[ubOde] {0} prim actors loaded",_prims.Count);
  1346. }
  1347. }
  1348. /// <summary>
  1349. /// This is our main simulate loop
  1350. /// It's thread locked by a Mutex in the scene.
  1351. /// It holds Collisions, it instructs ODE to step through the physical reactions
  1352. /// It moves the objects around in memory
  1353. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  1354. /// </summary>
  1355. /// <param name="timeStep"></param>
  1356. /// <returns></returns>
  1357. public override float Simulate(float reqTimeStep)
  1358. {
  1359. DateTime now = DateTime.UtcNow;
  1360. TimeSpan timedif = now - m_lastframe;
  1361. float timeStep = (float)timedif.TotalSeconds;
  1362. m_lastframe = now;
  1363. // acumulate time so we can reduce error
  1364. step_time += timeStep;
  1365. if (step_time < HalfOdeStep)
  1366. return 0;
  1367. if (framecount < 0)
  1368. framecount = 0;
  1369. framecount++;
  1370. // checkThread();
  1371. int nodeframes = 0;
  1372. float fps = 0;
  1373. lock (SimulationLock)
  1374. lock(OdeLock)
  1375. {
  1376. if (world == IntPtr.Zero)
  1377. {
  1378. ChangesQueue.Clear();
  1379. return 0;
  1380. }
  1381. ODEchangeitem item;
  1382. // d.WorldSetQuickStepNumIterations(world, curphysiteractions);
  1383. double loopstartMS = Util.GetTimeStampMS();
  1384. double looptimeMS = 0;
  1385. double changestimeMS = 0;
  1386. double maxChangestime = (int)(reqTimeStep * 500f); // half the time
  1387. double maxLoopTime = (int)(reqTimeStep * 1200f); // 1.2 the time
  1388. // double collisionTime = 0;
  1389. // double qstepTIme = 0;
  1390. // double tmpTime = 0;
  1391. d.AllocateODEDataForThread(~0U);
  1392. if (ChangesQueue.Count > 0)
  1393. {
  1394. while (ChangesQueue.Dequeue(out item))
  1395. {
  1396. if (item.actor != null)
  1397. {
  1398. try
  1399. {
  1400. if (item.actor is OdeCharacter)
  1401. ((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
  1402. else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
  1403. RemovePrimThreadLocked((OdePrim)item.actor);
  1404. }
  1405. catch
  1406. {
  1407. m_log.WarnFormat("[PHYSICS]: doChange failed for a actor {0} {1}",
  1408. item.actor.Name, item.what.ToString());
  1409. }
  1410. }
  1411. changestimeMS = Util.GetTimeStampMS() - loopstartMS;
  1412. if (changestimeMS > maxChangestime)
  1413. break;
  1414. }
  1415. }
  1416. // do simulation taking at most 150ms total time including changes
  1417. while (step_time > HalfOdeStep)
  1418. {
  1419. try
  1420. {
  1421. // clear pointer/counter to contacts to pass into joints
  1422. m_global_contactcount = 0;
  1423. // Move characters
  1424. lock (_characters)
  1425. {
  1426. List<OdeCharacter> defects = new List<OdeCharacter>();
  1427. foreach (OdeCharacter actor in _characters)
  1428. {
  1429. if (actor != null)
  1430. actor.Move(defects);
  1431. }
  1432. if (defects.Count != 0)
  1433. {
  1434. foreach (OdeCharacter defect in defects)
  1435. {
  1436. RemoveCharacter(defect);
  1437. }
  1438. defects.Clear();
  1439. }
  1440. }
  1441. // Move other active objects
  1442. lock (_activegroups)
  1443. {
  1444. foreach (OdePrim aprim in _activegroups)
  1445. {
  1446. aprim.Move();
  1447. }
  1448. }
  1449. m_rayCastManager.ProcessQueuedRequests();
  1450. // tmpTime = Util.GetTimeStampMS();
  1451. collision_optimized();
  1452. // collisionTime += Util.GetTimeStampMS() - tmpTime;
  1453. lock(_collisionEventPrimRemove)
  1454. {
  1455. foreach (PhysicsActor obj in _collisionEventPrimRemove)
  1456. _collisionEventPrim.Remove(obj);
  1457. _collisionEventPrimRemove.Clear();
  1458. }
  1459. List<OdePrim> sleepers = new List<OdePrim>();
  1460. foreach (PhysicsActor obj in _collisionEventPrim)
  1461. {
  1462. if (obj == null)
  1463. continue;
  1464. switch ((ActorTypes)obj.PhysicsActorType)
  1465. {
  1466. case ActorTypes.Agent:
  1467. OdeCharacter cobj = (OdeCharacter)obj;
  1468. cobj.SendCollisions((int)(odetimestepMS));
  1469. break;
  1470. case ActorTypes.Prim:
  1471. OdePrim pobj = (OdePrim)obj;
  1472. if (!pobj.m_outbounds)
  1473. {
  1474. pobj.SendCollisions((int)(odetimestepMS));
  1475. if(pobj.Body != IntPtr.Zero && !pobj.m_isSelected &&
  1476. !pobj.m_disabled && !pobj.m_building &&
  1477. !d.BodyIsEnabled(pobj.Body))
  1478. sleepers.Add(pobj);
  1479. }
  1480. break;
  1481. }
  1482. }
  1483. foreach(OdePrim prm in sleepers)
  1484. prm.SleeperAddCollisionEvents();
  1485. sleepers.Clear();
  1486. // do a ode simulation step
  1487. // tmpTime = Util.GetTimeStampMS();
  1488. d.WorldQuickStep(world, ODE_STEPSIZE);
  1489. d.JointGroupEmpty(contactgroup);
  1490. // qstepTIme += Util.GetTimeStampMS() - tmpTime;
  1491. // update managed ideia of physical data and do updates to core
  1492. /*
  1493. lock (_characters)
  1494. {
  1495. foreach (OdeCharacter actor in _characters)
  1496. {
  1497. if (actor != null)
  1498. {
  1499. if (actor.bad)
  1500. m_log.WarnFormat("[PHYSICS]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  1501. actor.UpdatePositionAndVelocity();
  1502. }
  1503. }
  1504. }
  1505. */
  1506. lock (_activegroups)
  1507. {
  1508. {
  1509. foreach (OdePrim actor in _activegroups)
  1510. {
  1511. if (actor.IsPhysical)
  1512. {
  1513. actor.UpdatePositionAndVelocity(framecount);
  1514. }
  1515. }
  1516. }
  1517. }
  1518. }
  1519. catch (Exception e)
  1520. {
  1521. m_log.ErrorFormat("[PHYSICS]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  1522. // ode.dunlock(world);
  1523. }
  1524. step_time -= ODE_STEPSIZE;
  1525. nodeframes++;
  1526. looptimeMS = Util.GetTimeStampMS() - loopstartMS;
  1527. if (looptimeMS > maxLoopTime)
  1528. break;
  1529. }
  1530. lock (_badCharacter)
  1531. {
  1532. if (_badCharacter.Count > 0)
  1533. {
  1534. foreach (OdeCharacter chr in _badCharacter)
  1535. {
  1536. RemoveCharacter(chr);
  1537. }
  1538. _badCharacter.Clear();
  1539. }
  1540. }
  1541. timedif = now - m_lastMeshExpire;
  1542. if (timedif.Seconds > 10)
  1543. {
  1544. mesher.ExpireReleaseMeshs();
  1545. m_lastMeshExpire = now;
  1546. }
  1547. // information block for in debug breakpoint only
  1548. /*
  1549. int ntopactivegeoms = d.SpaceGetNumGeoms(ActiveSpace);
  1550. int ntopstaticgeoms = d.SpaceGetNumGeoms(StaticSpace);
  1551. int ngroundgeoms = d.SpaceGetNumGeoms(GroundSpace);
  1552. int nactivegeoms = 0;
  1553. int nactivespaces = 0;
  1554. int nstaticgeoms = 0;
  1555. int nstaticspaces = 0;
  1556. IntPtr sp;
  1557. for (int i = 0; i < ntopactivegeoms; i++)
  1558. {
  1559. sp = d.SpaceGetGeom(ActiveSpace, i);
  1560. if (d.GeomIsSpace(sp))
  1561. {
  1562. nactivespaces++;
  1563. nactivegeoms += d.SpaceGetNumGeoms(sp);
  1564. }
  1565. else
  1566. nactivegeoms++;
  1567. }
  1568. for (int i = 0; i < ntopstaticgeoms; i++)
  1569. {
  1570. sp = d.SpaceGetGeom(StaticSpace, i);
  1571. if (d.GeomIsSpace(sp))
  1572. {
  1573. nstaticspaces++;
  1574. nstaticgeoms += d.SpaceGetNumGeoms(sp);
  1575. }
  1576. else
  1577. nstaticgeoms++;
  1578. }
  1579. int ntopgeoms = d.SpaceGetNumGeoms(TopSpace);
  1580. int totgeoms = nstaticgeoms + nactivegeoms + ngroundgeoms + 1; // one ray
  1581. int nbodies = d.NTotalBodies;
  1582. int ngeoms = d.NTotalGeoms;
  1583. */
  1584. /*
  1585. looptimeMS /= nodeframes;
  1586. if(looptimeMS > 0.080)
  1587. {
  1588. collisionTime /= nodeframes;
  1589. qstepTIme /= nodeframes;
  1590. }
  1591. */
  1592. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  1593. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  1594. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  1595. if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
  1596. {
  1597. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  1598. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  1599. if (physics_logging_append_existing_logfile)
  1600. {
  1601. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  1602. TextWriter fwriter = File.AppendText(fname);
  1603. fwriter.WriteLine(header);
  1604. fwriter.Close();
  1605. }
  1606. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  1607. }
  1608. fps = (float)nodeframes * ODE_STEPSIZE / reqTimeStep;
  1609. if(step_time < HalfOdeStep)
  1610. m_timeDilation = 1.0f;
  1611. else if (step_time > m_SkipFramesAtms)
  1612. {
  1613. // if we lag too much skip frames
  1614. m_timeDilation = 0.0f;
  1615. step_time = 0;
  1616. m_lastframe = DateTime.UtcNow; // skip also the time lost
  1617. }
  1618. else
  1619. {
  1620. m_timeDilation = ODE_STEPSIZE / step_time;
  1621. if (m_timeDilation > 1)
  1622. m_timeDilation = 1;
  1623. }
  1624. }
  1625. return fps;
  1626. }
  1627. /// <summary>
  1628. public override void GetResults()
  1629. {
  1630. }
  1631. public override bool IsThreaded
  1632. {
  1633. // for now we won't be multithreaded
  1634. get { return (false); }
  1635. }
  1636. public float GetTerrainHeightAtXY(float x, float y)
  1637. {
  1638. if (TerrainGeom == IntPtr.Zero)
  1639. return 0f;
  1640. if (TerrainHeightFieldHeight == null || TerrainHeightFieldHeight.Length == 0)
  1641. return 0f;
  1642. // TerrainHeightField for ODE as offset 1m
  1643. x += 1f;
  1644. y += 1f;
  1645. // make position fit into array
  1646. if (x < 0)
  1647. x = 0;
  1648. if (y < 0)
  1649. y = 0;
  1650. // integer indexs
  1651. int ix;
  1652. int iy;
  1653. // interpolators offset
  1654. float dx;
  1655. float dy;
  1656. int regsizeX = (int)m_regionWidth + 3; // map size see setterrain number of samples
  1657. int regsizeY = (int)m_regionHeight + 3; // map size see setterrain number of samples
  1658. int regsize = regsizeX;
  1659. if (m_OSOdeLib)
  1660. {
  1661. if (x < regsizeX - 1)
  1662. {
  1663. ix = (int)x;
  1664. dx = x - (float)ix;
  1665. }
  1666. else // out world use external height
  1667. {
  1668. ix = regsizeX - 2;
  1669. dx = 0;
  1670. }
  1671. if (y < regsizeY - 1)
  1672. {
  1673. iy = (int)y;
  1674. dy = y - (float)iy;
  1675. }
  1676. else
  1677. {
  1678. iy = regsizeY - 2;
  1679. dy = 0;
  1680. }
  1681. }
  1682. else
  1683. {
  1684. // we still have square fixed size regions
  1685. // also flip x and y because of how map is done for ODE fliped axis
  1686. // so ix,iy,dx and dy are inter exchanged
  1687. regsize = regsizeY;
  1688. if (x < regsizeX - 1)
  1689. {
  1690. iy = (int)x;
  1691. dy = x - (float)iy;
  1692. }
  1693. else // out world use external height
  1694. {
  1695. iy = regsizeX - 2;
  1696. dy = 0;
  1697. }
  1698. if (y < regsizeY - 1)
  1699. {
  1700. ix = (int)y;
  1701. dx = y - (float)ix;
  1702. }
  1703. else
  1704. {
  1705. ix = regsizeY - 2;
  1706. dx = 0;
  1707. }
  1708. }
  1709. float h0;
  1710. float h1;
  1711. float h2;
  1712. iy *= regsize;
  1713. iy += ix; // all indexes have iy + ix
  1714. float[] heights = TerrainHeightFieldHeight;
  1715. /*
  1716. if ((dx + dy) <= 1.0f)
  1717. {
  1718. h0 = ((float)heights[iy]); // 0,0 vertice
  1719. h1 = (((float)heights[iy + 1]) - h0) * dx; // 1,0 vertice minus 0,0
  1720. h2 = (((float)heights[iy + regsize]) - h0) * dy; // 0,1 vertice minus 0,0
  1721. }
  1722. else
  1723. {
  1724. h0 = ((float)heights[iy + regsize + 1]); // 1,1 vertice
  1725. h1 = (((float)heights[iy + 1]) - h0) * (1 - dy); // 1,1 vertice minus 1,0
  1726. h2 = (((float)heights[iy + regsize]) - h0) * (1 - dx); // 1,1 vertice minus 0,1
  1727. }
  1728. */
  1729. h0 = ((float)heights[iy]); // 0,0 vertice
  1730. if (dy>dx)
  1731. {
  1732. iy += regsize;
  1733. h2 = (float)heights[iy]; // 0,1 vertice
  1734. h1 = (h2 - h0) * dy; // 0,1 vertice minus 0,0
  1735. h2 = ((float)heights[iy + 1] - h2) * dx; // 1,1 vertice minus 0,1
  1736. }
  1737. else
  1738. {
  1739. iy++;
  1740. h2 = (float)heights[iy]; // vertice 1,0
  1741. h1 = (h2 - h0) * dx; // 1,0 vertice minus 0,0
  1742. h2 = (((float)heights[iy + regsize]) - h2) * dy; // 1,1 vertice minus 1,0
  1743. }
  1744. return h0 + h1 + h2;
  1745. }
  1746. public Vector3 GetTerrainNormalAtXY(float x, float y)
  1747. {
  1748. Vector3 norm = new Vector3(0, 0, 1);
  1749. if (TerrainGeom == IntPtr.Zero)
  1750. return norm;
  1751. if (TerrainHeightFieldHeight == null || TerrainHeightFieldHeight.Length == 0)
  1752. return norm;
  1753. // TerrainHeightField for ODE as offset 1m
  1754. x += 1f;
  1755. y += 1f;
  1756. // make position fit into array
  1757. if (x < 0)
  1758. x = 0;
  1759. if (y < 0)
  1760. y = 0;
  1761. // integer indexs
  1762. int ix;
  1763. int iy;
  1764. // interpolators offset
  1765. float dx;
  1766. float dy;
  1767. int regsizeX = (int)m_regionWidth + 3; // map size see setterrain number of samples
  1768. int regsizeY = (int)m_regionHeight + 3; // map size see setterrain number of samples
  1769. int regsize = regsizeX;
  1770. int xstep = 1;
  1771. int ystep = regsizeX;
  1772. bool firstTri = false;
  1773. if (m_OSOdeLib)
  1774. {
  1775. if (x < regsizeX - 1)
  1776. {
  1777. ix = (int)x;
  1778. dx = x - (float)ix;
  1779. }
  1780. else // out world use external height
  1781. {
  1782. ix = regsizeX - 2;
  1783. dx = 0;
  1784. }
  1785. if (y < regsizeY - 1)
  1786. {
  1787. iy = (int)y;
  1788. dy = y - (float)iy;
  1789. }
  1790. else
  1791. {
  1792. iy = regsizeY - 2;
  1793. dy = 0;
  1794. }
  1795. firstTri = dy > dx;
  1796. }
  1797. else
  1798. {
  1799. xstep = regsizeY;
  1800. ystep = 1;
  1801. regsize = regsizeY;
  1802. // we still have square fixed size regions
  1803. // also flip x and y because of how map is done for ODE fliped axis
  1804. // so ix,iy,dx and dy are inter exchanged
  1805. if (x < regsizeX - 1)
  1806. {
  1807. iy = (int)x;
  1808. dy = x - (float)iy;
  1809. }
  1810. else // out world use external height
  1811. {
  1812. iy = regsizeX - 2;
  1813. dy = 0;
  1814. }
  1815. if (y < regsizeY - 1)
  1816. {
  1817. ix = (int)y;
  1818. dx = y - (float)ix;
  1819. }
  1820. else
  1821. {
  1822. ix = regsizeY - 2;
  1823. dx = 0;
  1824. }
  1825. firstTri = dx > dy;
  1826. }
  1827. float h0;
  1828. float h1;
  1829. float h2;
  1830. iy *= regsize;
  1831. iy += ix; // all indexes have iy + ix
  1832. float[] heights = TerrainHeightFieldHeight;
  1833. if (firstTri)
  1834. {
  1835. h1 = ((float)heights[iy]); // 0,0 vertice
  1836. iy += ystep;
  1837. h0 = (float)heights[iy]; // 0,1
  1838. h2 = (float)heights[iy+xstep]; // 1,1 vertice
  1839. norm.X = h0 - h2;
  1840. norm.Y = h1 - h0;
  1841. }
  1842. else
  1843. {
  1844. h2 = ((float)heights[iy]); // 0,0 vertice
  1845. iy += xstep;
  1846. h0 = ((float)heights[iy]); // 1,0 vertice
  1847. h1 = (float)heights[iy+ystep]; // vertice 1,1
  1848. norm.X = h2 - h0;
  1849. norm.Y = h0 - h1;
  1850. }
  1851. norm.Z = 1;
  1852. norm.Normalize();
  1853. return norm;
  1854. }
  1855. public override void SetTerrain(float[] heightMap)
  1856. {
  1857. if (m_OSOdeLib)
  1858. OSSetTerrain(heightMap);
  1859. else
  1860. OriSetTerrain(heightMap);
  1861. }
  1862. public void OriSetTerrain(float[] heightMap)
  1863. {
  1864. // assumes 1m size grid and constante size square regions
  1865. // needs to know about sims around in future
  1866. float[] _heightmap;
  1867. uint regionsizeX = m_regionWidth;
  1868. uint regionsizeY = m_regionHeight;
  1869. // map is rotated
  1870. uint heightmapWidth = regionsizeY + 2;
  1871. uint heightmapHeight = regionsizeX + 2;
  1872. uint heightmapWidthSamples = heightmapWidth + 1;
  1873. uint heightmapHeightSamples = heightmapHeight + 1;
  1874. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  1875. const float scale = 1.0f;
  1876. const float offset = 0.0f;
  1877. const float thickness = 10f;
  1878. const int wrap = 0;
  1879. float hfmin = float.MaxValue;
  1880. float hfmax = float.MinValue;
  1881. float val;
  1882. uint xx;
  1883. uint yy;
  1884. uint maxXX = regionsizeX - 1;
  1885. uint maxYY = regionsizeY - 1;
  1886. // flipping map adding one margin all around so things don't fall in edges
  1887. uint xt = 0;
  1888. xx = 0;
  1889. for (uint x = 0; x < heightmapWidthSamples; x++)
  1890. {
  1891. if (x > 1 && xx < maxXX)
  1892. xx++;
  1893. yy = 0;
  1894. for (uint y = 0; y < heightmapHeightSamples; y++)
  1895. {
  1896. if (y > 1 && y < maxYY)
  1897. yy += regionsizeX;
  1898. val = heightMap[yy + xx];
  1899. if (val < 0.0f)
  1900. val = 0.0f; // no neg terrain as in chode
  1901. _heightmap[xt + y] = val;
  1902. if (hfmin > val)
  1903. hfmin = val;
  1904. if (hfmax < val)
  1905. hfmax = val;
  1906. }
  1907. xt += heightmapHeightSamples;
  1908. }
  1909. lock (OdeLock)
  1910. {
  1911. d.AllocateODEDataForThread(~0U);
  1912. if (TerrainGeom != IntPtr.Zero)
  1913. {
  1914. actor_name_map.Remove(TerrainGeom);
  1915. d.GeomDestroy(TerrainGeom);
  1916. }
  1917. if (TerrainHeightFieldHeightsHandler.IsAllocated)
  1918. TerrainHeightFieldHeightsHandler.Free();
  1919. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  1920. TerrainHeightFieldHeightsHandler = GCHandle.Alloc(_heightmap, GCHandleType.Pinned);
  1921. d.GeomHeightfieldDataBuildSingle(HeightmapData, TerrainHeightFieldHeightsHandler.AddrOfPinnedObject(), 0,
  1922. heightmapHeight, heightmapWidth ,
  1923. (int)heightmapHeightSamples, (int)heightmapWidthSamples, scale,
  1924. offset, thickness, wrap);
  1925. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  1926. TerrainGeom = d.CreateHeightfield(GroundSpace, HeightmapData, 1);
  1927. if (TerrainGeom != IntPtr.Zero)
  1928. {
  1929. d.GeomSetCategoryBits(TerrainGeom, (uint)(CollisionCategories.Land));
  1930. d.GeomSetCollideBits(TerrainGeom, 0);
  1931. PhysicsActor pa = new NullPhysicsActor();
  1932. pa.Name = "Terrain";
  1933. pa.PhysicsActorType = (int)ActorTypes.Ground;
  1934. actor_name_map[TerrainGeom] = pa;
  1935. // geom_name_map[GroundGeom] = "Terrain";
  1936. d.Quaternion q = new d.Quaternion();
  1937. q.X = 0.5f;
  1938. q.Y = 0.5f;
  1939. q.Z = 0.5f;
  1940. q.W = 0.5f;
  1941. d.GeomSetQuaternion(TerrainGeom, ref q);
  1942. d.GeomSetPosition(TerrainGeom, m_regionWidth * 0.5f, m_regionHeight * 0.5f, 0.0f);
  1943. TerrainHeightFieldHeight = _heightmap;
  1944. }
  1945. else
  1946. TerrainHeightFieldHeightsHandler.Free();
  1947. }
  1948. }
  1949. public void OSSetTerrain(float[] heightMap)
  1950. {
  1951. // assumes 1m size grid and constante size square regions
  1952. // needs to know about sims around in future
  1953. float[] _heightmap;
  1954. uint regionsizeX = m_regionWidth;
  1955. uint regionsizeY = m_regionHeight;
  1956. uint heightmapWidth = regionsizeX + 2;
  1957. uint heightmapHeight = regionsizeY + 2;
  1958. uint heightmapWidthSamples = heightmapWidth + 1;
  1959. uint heightmapHeightSamples = heightmapHeight + 1;
  1960. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  1961. float hfmin = float.MaxValue;
  1962. // float hfmax = float.MinValue;
  1963. float val;
  1964. uint maxXX = regionsizeX - 1;
  1965. uint maxYY = regionsizeY - 1;
  1966. // adding one margin all around so things don't fall in edges
  1967. uint xx;
  1968. uint yy = 0;
  1969. uint yt = 0;
  1970. for (uint y = 0; y < heightmapHeightSamples; y++)
  1971. {
  1972. if (y > 1 && y < maxYY)
  1973. yy += regionsizeX;
  1974. xx = 0;
  1975. for (uint x = 0; x < heightmapWidthSamples; x++)
  1976. {
  1977. if (x > 1 && x < maxXX)
  1978. xx++;
  1979. val = heightMap[yy + xx];
  1980. if (val < 0.0f)
  1981. val = 0.0f; // no neg terrain as in chode
  1982. _heightmap[yt + x] = val;
  1983. if (hfmin > val)
  1984. hfmin = val;
  1985. // if (hfmax < val)
  1986. // hfmax = val;
  1987. }
  1988. yt += heightmapWidthSamples;
  1989. }
  1990. lock (OdeLock)
  1991. {
  1992. if (TerrainGeom != IntPtr.Zero)
  1993. {
  1994. actor_name_map.Remove(TerrainGeom);
  1995. d.GeomDestroy(TerrainGeom);
  1996. }
  1997. if (TerrainHeightFieldHeightsHandler.IsAllocated)
  1998. TerrainHeightFieldHeightsHandler.Free();
  1999. TerrainHeightFieldHeight = null;
  2000. IntPtr HeightmapData = d.GeomOSTerrainDataCreate();
  2001. const int wrap = 0;
  2002. float thickness = hfmin;
  2003. if (thickness < 0)
  2004. thickness = 1;
  2005. TerrainHeightFieldHeightsHandler = GCHandle.Alloc(_heightmap, GCHandleType.Pinned);
  2006. d.GeomOSTerrainDataBuild(HeightmapData, TerrainHeightFieldHeightsHandler.AddrOfPinnedObject(), 0, 1.0f,
  2007. (int)heightmapWidthSamples, (int)heightmapHeightSamples,
  2008. thickness, wrap);
  2009. // d.GeomOSTerrainDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  2010. TerrainGeom = d.CreateOSTerrain(GroundSpace, HeightmapData, 1);
  2011. if (TerrainGeom != IntPtr.Zero)
  2012. {
  2013. d.GeomSetCategoryBits(TerrainGeom, (uint)(CollisionCategories.Land));
  2014. d.GeomSetCollideBits(TerrainGeom, 0);
  2015. PhysicsActor pa = new NullPhysicsActor();
  2016. pa.Name = "Terrain";
  2017. pa.PhysicsActorType = (int)ActorTypes.Ground;
  2018. actor_name_map[TerrainGeom] = pa;
  2019. // geom_name_map[GroundGeom] = "Terrain";
  2020. d.GeomSetPosition(TerrainGeom, m_regionWidth * 0.5f, m_regionHeight * 0.5f, 0.0f);
  2021. TerrainHeightFieldHeight = _heightmap;
  2022. }
  2023. else
  2024. TerrainHeightFieldHeightsHandler.Free();
  2025. }
  2026. }
  2027. public override void DeleteTerrain()
  2028. {
  2029. }
  2030. public float GetWaterLevel()
  2031. {
  2032. return waterlevel;
  2033. }
  2034. public override void SetWaterLevel(float baseheight)
  2035. {
  2036. waterlevel = baseheight;
  2037. }
  2038. public override void Dispose()
  2039. {
  2040. lock (OdeLock)
  2041. {
  2042. if (world == IntPtr.Zero)
  2043. return;
  2044. d.AllocateODEDataForThread(~0U);
  2045. if (m_meshWorker != null)
  2046. m_meshWorker.Stop();
  2047. if (m_rayCastManager != null)
  2048. {
  2049. m_rayCastManager.Dispose();
  2050. m_rayCastManager = null;
  2051. }
  2052. lock (_prims)
  2053. {
  2054. ChangesQueue.Clear();
  2055. foreach (OdePrim prm in _prims.Values)
  2056. {
  2057. prm.DoAChange(changes.Remove, null);
  2058. _collisionEventPrim.Remove(prm);
  2059. }
  2060. _prims.Clear();
  2061. }
  2062. OdeCharacter[] chtorem;
  2063. lock (_characters)
  2064. {
  2065. chtorem = new OdeCharacter[_characters.Count];
  2066. _characters.CopyTo(chtorem);
  2067. }
  2068. ChangesQueue.Clear();
  2069. foreach (OdeCharacter ch in chtorem)
  2070. ch.DoAChange(changes.Remove, null);
  2071. if (TerrainGeom != IntPtr.Zero)
  2072. d.GeomDestroy(TerrainGeom);
  2073. TerrainGeom = IntPtr.Zero;
  2074. if (TerrainHeightFieldHeightsHandler.IsAllocated)
  2075. TerrainHeightFieldHeightsHandler.Free();
  2076. TerrainHeightFieldHeight = null;
  2077. if (ContactgeomsArray != IntPtr.Zero)
  2078. {
  2079. Marshal.FreeHGlobal(ContactgeomsArray);
  2080. ContactgeomsArray = IntPtr.Zero;
  2081. }
  2082. if (GlobalContactsArray != IntPtr.Zero)
  2083. {
  2084. Marshal.FreeHGlobal(GlobalContactsArray);
  2085. GlobalContactsArray = IntPtr.Zero;
  2086. }
  2087. d.WorldDestroy(world);
  2088. world = IntPtr.Zero;
  2089. //d.CloseODE();
  2090. }
  2091. }
  2092. private int compareByCollisionsDesc(OdePrim A, OdePrim B)
  2093. {
  2094. return -A.CollisionScore.CompareTo(B.CollisionScore);
  2095. }
  2096. public override Dictionary<uint, float> GetTopColliders()
  2097. {
  2098. Dictionary<uint, float> topColliders;
  2099. List<OdePrim> orderedPrims;
  2100. lock (_activeprims)
  2101. orderedPrims = new List<OdePrim>(_activeprims);
  2102. orderedPrims.Sort(compareByCollisionsDesc);
  2103. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  2104. return topColliders;
  2105. }
  2106. public override bool SupportsRayCast()
  2107. {
  2108. return true;
  2109. }
  2110. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  2111. {
  2112. if (retMethod != null)
  2113. {
  2114. ODERayRequest req = new ODERayRequest();
  2115. req.actor = null;
  2116. req.callbackMethod = retMethod;
  2117. req.length = length;
  2118. req.Normal = direction;
  2119. req.Origin = position;
  2120. req.Count = 0;
  2121. req.filter = RayFilterFlags.AllPrims;
  2122. m_rayCastManager.QueueRequest(req);
  2123. }
  2124. }
  2125. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  2126. {
  2127. if (retMethod != null)
  2128. {
  2129. ODERayRequest req = new ODERayRequest();
  2130. req.actor = null;
  2131. req.callbackMethod = retMethod;
  2132. req.length = length;
  2133. req.Normal = direction;
  2134. req.Origin = position;
  2135. req.Count = Count;
  2136. req.filter = RayFilterFlags.AllPrims;
  2137. m_rayCastManager.QueueRequest(req);
  2138. }
  2139. }
  2140. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  2141. {
  2142. List<ContactResult> ourresults = new List<ContactResult>();
  2143. object SyncObject = new object();
  2144. RayCallback retMethod = delegate(List<ContactResult> results)
  2145. {
  2146. lock (SyncObject)
  2147. {
  2148. ourresults = results;
  2149. Monitor.PulseAll(SyncObject);
  2150. }
  2151. };
  2152. ODERayRequest req = new ODERayRequest();
  2153. req.actor = null;
  2154. req.callbackMethod = retMethod;
  2155. req.length = length;
  2156. req.Normal = direction;
  2157. req.Origin = position;
  2158. req.Count = Count;
  2159. req.filter = RayFilterFlags.AllPrims;
  2160. lock (SyncObject)
  2161. {
  2162. m_rayCastManager.QueueRequest(req);
  2163. if (!Monitor.Wait(SyncObject, 500))
  2164. return null;
  2165. else
  2166. return ourresults;
  2167. }
  2168. }
  2169. public override bool SupportsRaycastWorldFiltered()
  2170. {
  2171. return true;
  2172. }
  2173. public override object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  2174. {
  2175. object SyncObject = new object();
  2176. List<ContactResult> ourresults = new List<ContactResult>();
  2177. RayCallback retMethod = delegate(List<ContactResult> results)
  2178. {
  2179. lock (SyncObject)
  2180. {
  2181. ourresults = results;
  2182. Monitor.PulseAll(SyncObject);
  2183. }
  2184. };
  2185. ODERayRequest req = new ODERayRequest();
  2186. req.actor = null;
  2187. req.callbackMethod = retMethod;
  2188. req.length = length;
  2189. req.Normal = direction;
  2190. req.Origin = position;
  2191. req.Count = Count;
  2192. req.filter = filter;
  2193. lock (SyncObject)
  2194. {
  2195. m_rayCastManager.QueueRequest(req);
  2196. if (!Monitor.Wait(SyncObject, 500))
  2197. return null;
  2198. else
  2199. return ourresults;
  2200. }
  2201. }
  2202. public override List<ContactResult> RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags flags)
  2203. {
  2204. if (actor == null)
  2205. return new List<ContactResult>();
  2206. IntPtr geom;
  2207. if (actor is OdePrim)
  2208. geom = ((OdePrim)actor).prim_geom;
  2209. else if (actor is OdeCharacter)
  2210. geom = ((OdePrim)actor).prim_geom;
  2211. else
  2212. return new List<ContactResult>();
  2213. if (geom == IntPtr.Zero)
  2214. return new List<ContactResult>();
  2215. List<ContactResult> ourResults = null;
  2216. object SyncObject = new object();
  2217. RayCallback retMethod = delegate(List<ContactResult> results)
  2218. {
  2219. lock (SyncObject)
  2220. {
  2221. ourResults = results;
  2222. Monitor.PulseAll(SyncObject);
  2223. }
  2224. };
  2225. ODERayRequest req = new ODERayRequest();
  2226. req.actor = actor;
  2227. req.callbackMethod = retMethod;
  2228. req.length = length;
  2229. req.Normal = direction;
  2230. req.Origin = position;
  2231. req.Count = Count;
  2232. req.filter = flags;
  2233. lock (SyncObject)
  2234. {
  2235. m_rayCastManager.QueueRequest(req);
  2236. if (!Monitor.Wait(SyncObject, 500))
  2237. return new List<ContactResult>();
  2238. }
  2239. if (ourResults == null)
  2240. return new List<ContactResult>();
  2241. return ourResults;
  2242. }
  2243. public override List<ContactResult> BoxProbe(Vector3 position, Vector3 size, Quaternion orientation, int Count, RayFilterFlags flags)
  2244. {
  2245. List<ContactResult> ourResults = null;
  2246. object SyncObject = new object();
  2247. ProbeBoxCallback retMethod = delegate(List<ContactResult> results)
  2248. {
  2249. lock (SyncObject)
  2250. {
  2251. ourResults = results;
  2252. Monitor.PulseAll(SyncObject);
  2253. }
  2254. };
  2255. ODERayRequest req = new ODERayRequest();
  2256. req.actor = null;
  2257. req.callbackMethod = retMethod;
  2258. req.Normal = size;
  2259. req.Origin = position;
  2260. req.orientation = orientation;
  2261. req.Count = Count;
  2262. req.filter = flags;
  2263. lock (SyncObject)
  2264. {
  2265. m_rayCastManager.QueueRequest(req);
  2266. if (!Monitor.Wait(SyncObject, 500))
  2267. return new List<ContactResult>();
  2268. }
  2269. if (ourResults == null)
  2270. return new List<ContactResult>();
  2271. return ourResults;
  2272. }
  2273. public override List<ContactResult> SphereProbe(Vector3 position, float radius, int Count, RayFilterFlags flags)
  2274. {
  2275. List<ContactResult> ourResults = null;
  2276. object SyncObject = new object();
  2277. ProbeSphereCallback retMethod = delegate(List<ContactResult> results)
  2278. {
  2279. ourResults = results;
  2280. Monitor.PulseAll(SyncObject);
  2281. };
  2282. ODERayRequest req = new ODERayRequest();
  2283. req.actor = null;
  2284. req.callbackMethod = retMethod;
  2285. req.length = radius;
  2286. req.Origin = position;
  2287. req.Count = Count;
  2288. req.filter = flags;
  2289. lock (SyncObject)
  2290. {
  2291. m_rayCastManager.QueueRequest(req);
  2292. if (!Monitor.Wait(SyncObject, 500))
  2293. return new List<ContactResult>();
  2294. }
  2295. if (ourResults == null)
  2296. return new List<ContactResult>();
  2297. return ourResults;
  2298. }
  2299. public override List<ContactResult> PlaneProbe(PhysicsActor actor, Vector4 plane, int Count, RayFilterFlags flags)
  2300. {
  2301. IntPtr geom = IntPtr.Zero;;
  2302. if (actor != null)
  2303. {
  2304. if (actor is OdePrim)
  2305. geom = ((OdePrim)actor).prim_geom;
  2306. else if (actor is OdeCharacter)
  2307. geom = ((OdePrim)actor).prim_geom;
  2308. }
  2309. List<ContactResult> ourResults = null;
  2310. object SyncObject = new object();
  2311. ProbePlaneCallback retMethod = delegate(List<ContactResult> results)
  2312. {
  2313. ourResults = results;
  2314. Monitor.PulseAll(SyncObject);
  2315. };
  2316. ODERayRequest req = new ODERayRequest();
  2317. req.actor = null;
  2318. req.callbackMethod = retMethod;
  2319. req.length = plane.W;
  2320. req.Normal.X = plane.X;
  2321. req.Normal.Y = plane.Y;
  2322. req.Normal.Z = plane.Z;
  2323. req.Count = Count;
  2324. req.filter = flags;
  2325. lock (SyncObject)
  2326. {
  2327. m_rayCastManager.QueueRequest(req);
  2328. if (!Monitor.Wait(SyncObject, 500))
  2329. return new List<ContactResult>();
  2330. }
  2331. if (ourResults == null)
  2332. return new List<ContactResult>();
  2333. return ourResults;
  2334. }
  2335. public override int SitAvatar(PhysicsActor actor, Vector3 AbsolutePosition, Vector3 CameraPosition, Vector3 offset, Vector3 AvatarSize, SitAvatarCallback PhysicsSitResponse)
  2336. {
  2337. Util.FireAndForget( delegate
  2338. {
  2339. ODESitAvatar sitAvatar = new ODESitAvatar(this, m_rayCastManager);
  2340. if(sitAvatar != null)
  2341. sitAvatar.Sit(actor, AbsolutePosition, CameraPosition, offset, AvatarSize, PhysicsSitResponse);
  2342. });
  2343. return 1;
  2344. }
  2345. }
  2346. }