1
0

ODEScene.cs 91 KB

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