ODEScene.cs 103 KB

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