OdeScene.cs 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541
  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. // changes for varsize regions
  28. // note that raycasts need to have limited range
  29. // (even in normal regions)
  30. // or application thread stack may just blowup
  31. // see RayCast(ODERayCastRequest req)
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Diagnostics;
  35. using System.IO;
  36. using System.Linq;
  37. using System.Reflection;
  38. using System.Runtime.ExceptionServices;
  39. using System.Runtime.InteropServices;
  40. using System.Threading;
  41. using log4net;
  42. using Nini.Config;
  43. using Mono.Addins;
  44. using OpenMetaverse;
  45. using OpenSim.Framework;
  46. using OpenSim.Region.PhysicsModules.SharedBase;
  47. using OpenSim.Region.Framework.Scenes;
  48. using OpenSim.Region.Framework.Interfaces;
  49. namespace OpenSim.Region.PhysicsModule.ODE
  50. {
  51. public enum StatusIndicators : int
  52. {
  53. Generic = 0,
  54. Start = 1,
  55. End = 2
  56. }
  57. [Flags]
  58. public enum CollisionCategories : int
  59. {
  60. Disabled = 0,
  61. Geom = 0x00000001,
  62. Body = 0x00000002,
  63. Space = 0x00000004,
  64. Character = 0x00000008,
  65. Land = 0x00000010,
  66. Water = 0x00000020,
  67. Wind = 0x00000040,
  68. Sensor = 0x00000080,
  69. Selected = 0x00000100
  70. }
  71. /// <summary>
  72. /// Material type for a primitive
  73. /// </summary>
  74. public enum Material : int
  75. {
  76. /// <summary></summary>
  77. Stone = 0,
  78. /// <summary></summary>
  79. Metal = 1,
  80. /// <summary></summary>
  81. Glass = 2,
  82. /// <summary></summary>
  83. Wood = 3,
  84. /// <summary></summary>
  85. Flesh = 4,
  86. /// <summary></summary>
  87. Plastic = 5,
  88. /// <summary></summary>
  89. Rubber = 6
  90. }
  91. public class OdeScene : PhysicsScene
  92. {
  93. private readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.ToString());
  94. // private Dictionary<string, sCollisionData> m_storedCollisions = new Dictionary<string, sCollisionData>();
  95. /// <summary>
  96. /// Provide a sync object so that only one thread calls d.Collide() at a time across all OdeScene instances.
  97. /// </summary>
  98. /// <remarks>
  99. /// With ODE as of r1755 (though also tested on r1860), only one thread can call d.Collide() at a
  100. /// time, even where physics objects are in entirely different ODE worlds. This is because generating contacts
  101. /// uses a static cache at the ODE level.
  102. ///
  103. /// Without locking, simulators running multiple regions will eventually crash with a native stack trace similar
  104. /// to
  105. ///
  106. /// mono() [0x489171]
  107. /// mono() [0x4d154f]
  108. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f6ded592c60]
  109. /// .../opensim/bin/libode-x86_64.so(_ZN6Opcode11OBBCollider8_CollideEPKNS_14AABBNoLeafNodeE+0xd7a) [0x7f6dd822628a]
  110. ///
  111. /// ODE provides an experimental option to cache in thread local storage but compiling ODE with this option
  112. /// causes OpenSimulator to immediately crash with a native stack trace similar to
  113. ///
  114. /// mono() [0x489171]
  115. /// mono() [0x4d154f]
  116. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f03c9849c60]
  117. /// .../opensim/bin/libode-x86_64.so(_Z12dCollideCCTLP6dxGeomS0_iP12dContactGeomi+0x92) [0x7f03b44bcf82]
  118. /// </remarks>
  119. internal static Object UniversalColliderSyncObject = new Object();
  120. internal static Object SimulationLock = new Object();
  121. /// <summary>
  122. /// Is stats collecting enabled for this ODE scene?
  123. /// </summary>
  124. public bool CollectStats { get; set; }
  125. /// <summary>
  126. /// Statistics for this scene.
  127. /// </summary>
  128. private Dictionary<string, float> m_stats = new Dictionary<string, float>();
  129. /// <summary>
  130. /// Stat name for total number of avatars in this ODE scene.
  131. /// </summary>
  132. public const string ODETotalAvatarsStatName = "ODETotalAvatars";
  133. /// <summary>
  134. /// Stat name for total number of prims in this ODE scene.
  135. /// </summary>
  136. public const string ODETotalPrimsStatName = "ODETotalPrims";
  137. /// <summary>
  138. /// Stat name for total number of prims with active physics in this ODE scene.
  139. /// </summary>
  140. public const string ODEActivePrimsStatName = "ODEActivePrims";
  141. /// <summary>
  142. /// Stat name for the total time spent in ODE frame processing.
  143. /// </summary>
  144. /// <remarks>
  145. /// A sanity check for the main scene loop physics time.
  146. /// </remarks>
  147. public const string ODETotalFrameMsStatName = "ODETotalFrameMS";
  148. /// <summary>
  149. /// Stat name for time spent processing avatar taints per frame
  150. /// </summary>
  151. public const string ODEAvatarTaintMsStatName = "ODEAvatarTaintFrameMS";
  152. /// <summary>
  153. /// Stat name for time spent processing prim taints per frame
  154. /// </summary>
  155. public const string ODEPrimTaintMsStatName = "ODEPrimTaintFrameMS";
  156. /// <summary>
  157. /// Stat name for time spent calculating avatar forces per frame.
  158. /// </summary>
  159. public const string ODEAvatarForcesFrameMsStatName = "ODEAvatarForcesFrameMS";
  160. /// <summary>
  161. /// Stat name for time spent calculating prim forces per frame
  162. /// </summary>
  163. public const string ODEPrimForcesFrameMsStatName = "ODEPrimForcesFrameMS";
  164. /// <summary>
  165. /// Stat name for time spent fulfilling raycasting requests per frame
  166. /// </summary>
  167. public const string ODERaycastingFrameMsStatName = "ODERaycastingFrameMS";
  168. /// <summary>
  169. /// Stat name for time spent in native code that actually steps through the simulation.
  170. /// </summary>
  171. public const string ODENativeStepFrameMsStatName = "ODENativeStepFrameMS";
  172. /// <summary>
  173. /// Stat name for the number of milliseconds that ODE spends in native space collision code.
  174. /// </summary>
  175. public const string ODENativeSpaceCollisionFrameMsStatName = "ODENativeSpaceCollisionFrameMS";
  176. /// <summary>
  177. /// Stat name for milliseconds that ODE spends in native geom collision code.
  178. /// </summary>
  179. public const string ODENativeGeomCollisionFrameMsStatName = "ODENativeGeomCollisionFrameMS";
  180. /// <summary>
  181. /// Time spent in collision processing that is not spent in native space or geom collision code.
  182. /// </summary>
  183. public const string ODEOtherCollisionFrameMsStatName = "ODEOtherCollisionFrameMS";
  184. /// <summary>
  185. /// Stat name for time spent notifying listeners of collisions
  186. /// </summary>
  187. public const string ODECollisionNotificationFrameMsStatName = "ODECollisionNotificationFrameMS";
  188. /// <summary>
  189. /// Stat name for milliseconds spent updating avatar position and velocity
  190. /// </summary>
  191. public const string ODEAvatarUpdateFrameMsStatName = "ODEAvatarUpdateFrameMS";
  192. /// <summary>
  193. /// Stat name for the milliseconds spent updating prim position and velocity
  194. /// </summary>
  195. public const string ODEPrimUpdateFrameMsStatName = "ODEPrimUpdateFrameMS";
  196. /// <summary>
  197. /// Stat name for avatar collisions with another entity.
  198. /// </summary>
  199. public const string ODEAvatarContactsStatsName = "ODEAvatarContacts";
  200. /// <summary>
  201. /// Stat name for prim collisions with another entity.
  202. /// </summary>
  203. public const string ODEPrimContactsStatName = "ODEPrimContacts";
  204. /// <summary>
  205. /// Used to hold tick numbers for stat collection purposes.
  206. /// </summary>
  207. private int m_nativeCollisionStartTick;
  208. /// <summary>
  209. /// A messy way to tell if we need to avoid adding a collision time because this was already done in the callback.
  210. /// </summary>
  211. private bool m_inCollisionTiming;
  212. /// <summary>
  213. /// A temporary holder for the number of avatar collisions in a frame, so we can work out how many object
  214. /// collisions occured using the _perloopcontact if stats collection is enabled.
  215. /// </summary>
  216. private int m_tempAvatarCollisionsThisFrame;
  217. /// <summary>
  218. /// Used in calculating physics frame time dilation
  219. /// </summary>
  220. private int tickCountFrameRun;
  221. /// <summary>
  222. /// Used in calculating physics frame time dilation
  223. /// </summary>
  224. private int latertickcount;
  225. private Random fluidRandomizer = new Random(Environment.TickCount);
  226. private uint m_regionWidth = Constants.RegionSize;
  227. private uint m_regionHeight = Constants.RegionSize;
  228. private float ODE_STEPSIZE = 0.0178f;
  229. private float metersInSpace = 29.9f;
  230. private float m_timeDilation = 1.0f;
  231. public float gravityx = 0f;
  232. public float gravityy = 0f;
  233. public float gravityz = -9.8f;
  234. public float AvatarTerminalVelocity { get; set; }
  235. private float contactsurfacelayer = 0.001f;
  236. private int HashspaceLow = -5;
  237. private int HashspaceHigh = 12;
  238. private float waterlevel = 0f;
  239. private int framecount = 0;
  240. //private int m_returncollisions = 10;
  241. private IntPtr contactgroup;
  242. // internal IntPtr WaterGeom;
  243. private float nmTerrainContactFriction = 255.0f;
  244. private float nmTerrainContactBounce = 0.1f;
  245. private float nmTerrainContactERP = 0.1025f;
  246. private float mTerrainContactFriction = 75f;
  247. private float mTerrainContactBounce = 0.1f;
  248. private float mTerrainContactERP = 0.05025f;
  249. private float nmAvatarObjectContactFriction = 250f;
  250. private float nmAvatarObjectContactBounce = 0.1f;
  251. private float mAvatarObjectContactFriction = 75f;
  252. private float mAvatarObjectContactBounce = 0.1f;
  253. private float avPIDD = 3200f;
  254. private float avPIDP = 1400f;
  255. private float avCapRadius = 0.37f;
  256. private float avStandupTensor = 2000000f;
  257. /// <summary>
  258. /// true = old compatibility mode with leaning capsule; false = new corrected mode
  259. /// </summary>
  260. /// <remarks>
  261. /// Even when set to false, the capsule still tilts but this is done in a different way.
  262. /// </remarks>
  263. public bool IsAvCapsuleTilted { get; private set; }
  264. private float avDensity = 80f;
  265. private float avMovementDivisorWalk = 1.3f;
  266. private float avMovementDivisorRun = 0.8f;
  267. private float minimumGroundFlightOffset = 3f;
  268. public float maximumMassObject = 10000.01f;
  269. public bool meshSculptedPrim = true;
  270. public bool forceSimplePrimMeshing = false;
  271. public float meshSculptLOD = 32;
  272. public float MeshSculptphysicalLOD = 16;
  273. public float geomDefaultDensity = 10.000006836f;
  274. public int geomContactPointsStartthrottle = 3;
  275. public int geomUpdatesPerThrottledUpdate = 15;
  276. private const int avatarExpectedContacts = 3;
  277. public float bodyPIDD = 35f;
  278. public float bodyPIDG = 25;
  279. public int bodyFramesAutoDisable = 20;
  280. private bool m_filterCollisions = true;
  281. private d.NearCallback nearCallback;
  282. public d.TriCallback triCallback;
  283. public d.TriArrayCallback triArrayCallback;
  284. /// <summary>
  285. /// Avatars in the physics scene.
  286. /// </summary>
  287. private readonly HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  288. /// <summary>
  289. /// Prims in the physics scene.
  290. /// </summary>
  291. private readonly HashSet<OdePrim> _prims = new HashSet<OdePrim>();
  292. /// <summary>
  293. /// Prims in the physics scene that are subject to physics, not just collisions.
  294. /// </summary>
  295. private readonly HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  296. /// <summary>
  297. /// Prims that the simulator has created/deleted/updated and so need updating in ODE.
  298. /// </summary>
  299. private readonly HashSet<OdePrim> _taintedPrims = new HashSet<OdePrim>();
  300. /// <summary>
  301. /// Record a character that has taints to be processed.
  302. /// </summary>
  303. private readonly HashSet<OdeCharacter> _taintedActors = new HashSet<OdeCharacter>();
  304. /// <summary>
  305. /// Keep record of contacts in the physics loop so that we can remove duplicates.
  306. /// </summary>
  307. private readonly List<d.ContactGeom> _perloopContact = new List<d.ContactGeom>();
  308. /// <summary>
  309. /// A dictionary of actors that should receive collision events.
  310. /// </summary>
  311. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActors = new Dictionary<uint, PhysicsActor>();
  312. /// <summary>
  313. /// A dictionary of collision event changes that are waiting to be processed.
  314. /// </summary>
  315. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActorsChanges = new Dictionary<uint, PhysicsActor>();
  316. /// <summary>
  317. /// Maps a unique geometry id (a memory location) to a physics actor name.
  318. /// </summary>
  319. /// <remarks>
  320. /// Only actors participating in collisions have geometries. This has to be maintained separately from
  321. /// actor_name_map because terrain and water currently don't conceptually have a physics actor of their own
  322. /// apart from the singleton PANull
  323. /// </remarks>
  324. public Dictionary<IntPtr, String> geom_name_map = new Dictionary<IntPtr, String>();
  325. /// <summary>
  326. /// Maps a unique geometry id (a memory location) to a physics actor.
  327. /// </summary>
  328. /// <remarks>
  329. /// Only actors participating in collisions have geometries.
  330. /// </remarks>
  331. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  332. /// <summary>
  333. /// Defects list to remove characters that no longer have finite positions due to some other bug.
  334. /// </summary>
  335. /// <remarks>
  336. /// Used repeatedly in Simulate() but initialized once here.
  337. /// </remarks>
  338. private readonly List<OdeCharacter> defects = new List<OdeCharacter>();
  339. private bool m_NINJA_physics_joints_enabled = false;
  340. //private Dictionary<String, IntPtr> jointpart_name_map = new Dictionary<String,IntPtr>();
  341. private readonly Dictionary<String, List<PhysicsJoint>> joints_connecting_actor = new Dictionary<String, List<PhysicsJoint>>();
  342. private d.ContactGeom[] contacts;
  343. /// <summary>
  344. /// Lock only briefly. accessed by external code (to request new joints) and by OdeScene.Simulate() to move those joints into pending/active
  345. /// </summary>
  346. private readonly List<PhysicsJoint> requestedJointsToBeCreated = new List<PhysicsJoint>();
  347. /// <summary>
  348. /// can lock for longer. accessed only by OdeScene.
  349. /// </summary>
  350. private readonly List<PhysicsJoint> pendingJoints = new List<PhysicsJoint>();
  351. /// <summary>
  352. /// can lock for longer. accessed only by OdeScene.
  353. /// </summary>
  354. private readonly List<PhysicsJoint> activeJoints = new List<PhysicsJoint>();
  355. /// <summary>
  356. /// lock only briefly. accessed by external code (to request deletion of joints) and by OdeScene.Simulate() to move those joints out of pending/active
  357. /// </summary>
  358. private readonly List<string> requestedJointsToBeDeleted = new List<string>();
  359. private Object externalJointRequestsLock = new Object();
  360. private readonly Dictionary<String, PhysicsJoint> SOPName_to_activeJoint = new Dictionary<String, PhysicsJoint>();
  361. private readonly Dictionary<String, PhysicsJoint> SOPName_to_pendingJoint = new Dictionary<String, PhysicsJoint>();
  362. private readonly DoubleDictionary<Vector3, IntPtr, IntPtr> RegionTerrain = new DoubleDictionary<Vector3, IntPtr, IntPtr>();
  363. private readonly Dictionary<IntPtr,float[]> TerrainHeightFieldHeights = new Dictionary<IntPtr, float[]>();
  364. private d.Contact contact;
  365. private d.Contact TerrainContact;
  366. private d.Contact AvatarMovementprimContact;
  367. private d.Contact AvatarMovementTerrainContact;
  368. private d.Contact WaterContact;
  369. private d.Contact[,] m_materialContacts;
  370. private int m_physicsiterations = 10;
  371. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  372. private readonly PhysicsActor PANull = new NullPhysicsActor();
  373. private float step_time = 0.0f;
  374. public IntPtr world;
  375. private uint obj2LocalID = 0;
  376. private OdeCharacter cc1;
  377. private OdePrim cp1;
  378. private OdeCharacter cc2;
  379. private OdePrim cp2;
  380. private int p1ExpectedPoints = 0;
  381. private int p2ExpectedPoints = 0;
  382. public IntPtr space;
  383. // split static geometry collision handling into spaces of 30 meters
  384. public IntPtr[,] staticPrimspace;
  385. /// <summary>
  386. /// Used to lock the entire physics scene. Locked during the main part of Simulate()
  387. /// </summary>
  388. internal Object OdeLock = new Object();
  389. private bool _worldInitialized = false;
  390. public IMesher mesher;
  391. private IConfigSource m_config;
  392. public bool physics_logging = false;
  393. public int physics_logging_interval = 0;
  394. public bool physics_logging_append_existing_logfile = false;
  395. private bool avplanted = false;
  396. private bool av_av_collisions_off = false;
  397. public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f);
  398. public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f);
  399. private volatile int m_global_contactcount = 0;
  400. private Vector3 m_worldOffset = Vector3.Zero;
  401. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  402. private PhysicsScene m_parentScene = null;
  403. float spacesPerMeterX;
  404. float spacesPerMeterY;
  405. int spaceGridMaxX;
  406. int spaceGridMaxY;
  407. private ODERayCastRequestManager m_rayCastManager;
  408. public Scene m_frameWorkScene = null;
  409. public OdeScene(Scene pscene, IConfigSource psourceconfig, string pname, string pversion)
  410. {
  411. m_config = psourceconfig;
  412. m_frameWorkScene = pscene;
  413. EngineType = pname;
  414. PhysicsSceneName = EngineType + "/" + pscene.RegionInfo.RegionName;
  415. EngineName = pname + " " + pversion;
  416. pscene.RegisterModuleInterface<PhysicsScene>(this);
  417. Vector3 extent = new Vector3(pscene.RegionInfo.RegionSizeX, pscene.RegionInfo.RegionSizeY, pscene.RegionInfo.RegionSizeZ);
  418. Initialise(extent);
  419. InitialiseFromConfig(m_config);
  420. // This may not be that good since terrain may not be avaiable at this point
  421. base.Initialise(pscene.PhysicsRequestAsset,
  422. (pscene.Heightmap != null ? pscene.Heightmap.GetFloatsSerialised() : new float[(int)(extent.X * extent.Y)]),
  423. (float)pscene.RegionInfo.RegionSettings.WaterHeight);
  424. }
  425. public void RegionLoaded()
  426. {
  427. mesher = m_frameWorkScene.RequestModuleInterface<IMesher>();
  428. if (mesher == null)
  429. m_log.WarnFormat("[ODE SCENE]: No mesher in {0}. Things will not work well.", PhysicsSceneName);
  430. m_frameWorkScene.PhysicsEnabled = true;
  431. }
  432. /// <summary>
  433. /// Initiailizes the scene
  434. /// Sets many properties that ODE requires to be stable
  435. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  436. /// </summary>
  437. private void Initialise(Vector3 regionExtent)
  438. {
  439. WorldExtents.X = regionExtent.X;
  440. m_regionWidth = (uint)regionExtent.X;
  441. WorldExtents.Y = regionExtent.Y;
  442. m_regionHeight = (uint)regionExtent.Y;
  443. nearCallback = near;
  444. m_rayCastManager = new ODERayCastRequestManager(this);
  445. // Create the world and the first space
  446. world = d.WorldCreate();
  447. space = d.HashSpaceCreate(IntPtr.Zero);
  448. contactgroup = d.JointGroupCreate(0);
  449. d.WorldSetAutoDisableFlag(world, false);
  450. }
  451. // Initialize from configs
  452. private void InitialiseFromConfig(IConfigSource config)
  453. {
  454. InitializeExtraStats();
  455. m_config = config;
  456. // Defaults
  457. avPIDD = 2200.0f;
  458. avPIDP = 900.0f;
  459. avStandupTensor = 550000f;
  460. int contactsPerCollision = 80;
  461. if (m_config != null)
  462. {
  463. IConfig physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  464. if (physicsconfig != null)
  465. {
  466. CollectStats = physicsconfig.GetBoolean("collect_stats", false);
  467. gravityx = physicsconfig.GetFloat("world_gravityx", 0f);
  468. gravityy = physicsconfig.GetFloat("world_gravityy", 0f);
  469. gravityz = physicsconfig.GetFloat("world_gravityz", -9.8f);
  470. float avatarTerminalVelocity = physicsconfig.GetFloat("avatar_terminal_velocity", 54f);
  471. AvatarTerminalVelocity = Util.Clamp<float>(avatarTerminalVelocity, 0, 255f);
  472. if (AvatarTerminalVelocity != avatarTerminalVelocity)
  473. {
  474. m_log.WarnFormat(
  475. "[ODE SCENE]: avatar_terminal_velocity of {0} is invalid. Clamping to {1}",
  476. avatarTerminalVelocity, AvatarTerminalVelocity);
  477. }
  478. HashspaceLow = physicsconfig.GetInt("world_hashspace_level_low", -5);
  479. HashspaceHigh = physicsconfig.GetInt("world_hashspace_level_high", 12);
  480. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", 29.9f);
  481. contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", 0.001f);
  482. nmTerrainContactFriction = physicsconfig.GetFloat("nm_terraincontact_friction", 255.0f);
  483. nmTerrainContactBounce = physicsconfig.GetFloat("nm_terraincontact_bounce", 0.1f);
  484. nmTerrainContactERP = physicsconfig.GetFloat("nm_terraincontact_erp", 0.1025f);
  485. mTerrainContactFriction = physicsconfig.GetFloat("m_terraincontact_friction", 75f);
  486. mTerrainContactBounce = physicsconfig.GetFloat("m_terraincontact_bounce", 0.05f);
  487. mTerrainContactERP = physicsconfig.GetFloat("m_terraincontact_erp", 0.05025f);
  488. nmAvatarObjectContactFriction = physicsconfig.GetFloat("objectcontact_friction", 250f);
  489. nmAvatarObjectContactBounce = physicsconfig.GetFloat("objectcontact_bounce", 0.2f);
  490. mAvatarObjectContactFriction = physicsconfig.GetFloat("m_avatarobjectcontact_friction", 75f);
  491. mAvatarObjectContactBounce = physicsconfig.GetFloat("m_avatarobjectcontact_bounce", 0.1f);
  492. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  493. m_physicsiterations = physicsconfig.GetInt("world_solver_iterations", 10);
  494. avDensity = physicsconfig.GetFloat("av_density", 80f);
  495. // avHeightFudgeFactor = physicsconfig.GetFloat("av_height_fudge_factor", 0.52f);
  496. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f);
  497. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f);
  498. avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f);
  499. avplanted = physicsconfig.GetBoolean("av_planted", false);
  500. av_av_collisions_off = physicsconfig.GetBoolean("av_av_collisions_off", false);
  501. IsAvCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false);
  502. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80);
  503. geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 5);
  504. geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15);
  505. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", 10.000006836f);
  506. bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", 20);
  507. bodyPIDD = physicsconfig.GetFloat("body_pid_derivative", 35f);
  508. bodyPIDG = physicsconfig.GetFloat("body_pid_gain", 25f);
  509. forceSimplePrimMeshing = physicsconfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
  510. meshSculptedPrim = physicsconfig.GetBoolean("mesh_sculpted_prim", true);
  511. meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f);
  512. MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f);
  513. m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false);
  514. avPIDD = physicsconfig.GetFloat("av_pid_derivative", 2200.0f);
  515. avPIDP = physicsconfig.GetFloat("av_pid_proportional", 900.0f);
  516. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor", 550000f);
  517. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  518. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  519. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  520. // m_NINJA_physics_joints_enabled = physicsconfig.GetBoolean("use_NINJA_physics_joints", false);
  521. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", 3f);
  522. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", 10000.01f);
  523. }
  524. }
  525. contacts = new d.ContactGeom[contactsPerCollision];
  526. spacesPerMeterX = 1.0f / metersInSpace;
  527. spacesPerMeterY = 1.0f / metersInSpace;
  528. spaceGridMaxX = (int)(WorldExtents.X * spacesPerMeterX);
  529. spaceGridMaxY = (int)(WorldExtents.Y * spacesPerMeterY);
  530. // note: limit number of spaces
  531. if (spaceGridMaxX > 24)
  532. {
  533. spaceGridMaxX = 24;
  534. spacesPerMeterX = spaceGridMaxX / WorldExtents.X;
  535. }
  536. if (spaceGridMaxY > 24)
  537. {
  538. spaceGridMaxY = 24;
  539. spacesPerMeterY = spaceGridMaxY / WorldExtents.Y;
  540. }
  541. staticPrimspace = new IntPtr[spaceGridMaxX, spaceGridMaxY];
  542. // make this index limits
  543. spaceGridMaxX--;
  544. spaceGridMaxY--;
  545. // Centeral contact friction and bounce
  546. // ckrinke 11/10/08 Enabling soft_erp but not soft_cfm until I figure out why
  547. // an avatar falls through in Z but not in X or Y when walking on a prim.
  548. contact.surface.mode |= d.ContactFlags.SoftERP;
  549. contact.surface.mu = nmAvatarObjectContactFriction;
  550. contact.surface.bounce = nmAvatarObjectContactBounce;
  551. contact.surface.soft_cfm = 0.010f;
  552. contact.surface.soft_erp = 0.010f;
  553. // Terrain contact friction and Bounce
  554. // This is the *non* moving version. Use this when an avatar
  555. // isn't moving to keep it in place better
  556. TerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  557. TerrainContact.surface.mu = nmTerrainContactFriction;
  558. TerrainContact.surface.bounce = nmTerrainContactBounce;
  559. TerrainContact.surface.soft_erp = nmTerrainContactERP;
  560. WaterContact.surface.mode |= (d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM);
  561. WaterContact.surface.mu = 0f; // No friction
  562. WaterContact.surface.bounce = 0.0f; // No bounce
  563. WaterContact.surface.soft_cfm = 0.010f;
  564. WaterContact.surface.soft_erp = 0.010f;
  565. // Prim contact friction and bounce
  566. // THis is the *non* moving version of friction and bounce
  567. // Use this when an avatar comes in contact with a prim
  568. // and is moving
  569. AvatarMovementprimContact.surface.mu = mAvatarObjectContactFriction;
  570. AvatarMovementprimContact.surface.bounce = mAvatarObjectContactBounce;
  571. // Terrain contact friction bounce and various error correcting calculations
  572. // Use this when an avatar is in contact with the terrain and moving.
  573. AvatarMovementTerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  574. AvatarMovementTerrainContact.surface.mu = mTerrainContactFriction;
  575. AvatarMovementTerrainContact.surface.bounce = mTerrainContactBounce;
  576. AvatarMovementTerrainContact.surface.soft_erp = mTerrainContactERP;
  577. /*
  578. <summary></summary>
  579. Stone = 0,
  580. /// <summary></summary>
  581. Metal = 1,
  582. /// <summary></summary>
  583. Glass = 2,
  584. /// <summary></summary>
  585. Wood = 3,
  586. /// <summary></summary>
  587. Flesh = 4,
  588. /// <summary></summary>
  589. Plastic = 5,
  590. /// <summary></summary>
  591. Rubber = 6
  592. */
  593. m_materialContacts = new d.Contact[7,2];
  594. m_materialContacts[(int)Material.Stone, 0] = new d.Contact();
  595. m_materialContacts[(int)Material.Stone, 0].surface.mode |= d.ContactFlags.SoftERP;
  596. m_materialContacts[(int)Material.Stone, 0].surface.mu = nmAvatarObjectContactFriction;
  597. m_materialContacts[(int)Material.Stone, 0].surface.bounce = nmAvatarObjectContactBounce;
  598. m_materialContacts[(int)Material.Stone, 0].surface.soft_cfm = 0.010f;
  599. m_materialContacts[(int)Material.Stone, 0].surface.soft_erp = 0.010f;
  600. m_materialContacts[(int)Material.Stone, 1] = new d.Contact();
  601. m_materialContacts[(int)Material.Stone, 1].surface.mode |= d.ContactFlags.SoftERP;
  602. m_materialContacts[(int)Material.Stone, 1].surface.mu = mAvatarObjectContactFriction;
  603. m_materialContacts[(int)Material.Stone, 1].surface.bounce = mAvatarObjectContactBounce;
  604. m_materialContacts[(int)Material.Stone, 1].surface.soft_cfm = 0.010f;
  605. m_materialContacts[(int)Material.Stone, 1].surface.soft_erp = 0.010f;
  606. m_materialContacts[(int)Material.Metal, 0] = new d.Contact();
  607. m_materialContacts[(int)Material.Metal, 0].surface.mode |= d.ContactFlags.SoftERP;
  608. m_materialContacts[(int)Material.Metal, 0].surface.mu = nmAvatarObjectContactFriction;
  609. m_materialContacts[(int)Material.Metal, 0].surface.bounce = nmAvatarObjectContactBounce;
  610. m_materialContacts[(int)Material.Metal, 0].surface.soft_cfm = 0.010f;
  611. m_materialContacts[(int)Material.Metal, 0].surface.soft_erp = 0.010f;
  612. m_materialContacts[(int)Material.Metal, 1] = new d.Contact();
  613. m_materialContacts[(int)Material.Metal, 1].surface.mode |= d.ContactFlags.SoftERP;
  614. m_materialContacts[(int)Material.Metal, 1].surface.mu = mAvatarObjectContactFriction;
  615. m_materialContacts[(int)Material.Metal, 1].surface.bounce = mAvatarObjectContactBounce;
  616. m_materialContacts[(int)Material.Metal, 1].surface.soft_cfm = 0.010f;
  617. m_materialContacts[(int)Material.Metal, 1].surface.soft_erp = 0.010f;
  618. m_materialContacts[(int)Material.Glass, 0] = new d.Contact();
  619. m_materialContacts[(int)Material.Glass, 0].surface.mode |= d.ContactFlags.SoftERP;
  620. m_materialContacts[(int)Material.Glass, 0].surface.mu = 1f;
  621. m_materialContacts[(int)Material.Glass, 0].surface.bounce = 0.5f;
  622. m_materialContacts[(int)Material.Glass, 0].surface.soft_cfm = 0.010f;
  623. m_materialContacts[(int)Material.Glass, 0].surface.soft_erp = 0.010f;
  624. /*
  625. private float nmAvatarObjectContactFriction = 250f;
  626. private float nmAvatarObjectContactBounce = 0.1f;
  627. private float mAvatarObjectContactFriction = 75f;
  628. private float mAvatarObjectContactBounce = 0.1f;
  629. */
  630. m_materialContacts[(int)Material.Glass, 1] = new d.Contact();
  631. m_materialContacts[(int)Material.Glass, 1].surface.mode |= d.ContactFlags.SoftERP;
  632. m_materialContacts[(int)Material.Glass, 1].surface.mu = 1f;
  633. m_materialContacts[(int)Material.Glass, 1].surface.bounce = 0.5f;
  634. m_materialContacts[(int)Material.Glass, 1].surface.soft_cfm = 0.010f;
  635. m_materialContacts[(int)Material.Glass, 1].surface.soft_erp = 0.010f;
  636. m_materialContacts[(int)Material.Wood, 0] = new d.Contact();
  637. m_materialContacts[(int)Material.Wood, 0].surface.mode |= d.ContactFlags.SoftERP;
  638. m_materialContacts[(int)Material.Wood, 0].surface.mu = nmAvatarObjectContactFriction;
  639. m_materialContacts[(int)Material.Wood, 0].surface.bounce = nmAvatarObjectContactBounce;
  640. m_materialContacts[(int)Material.Wood, 0].surface.soft_cfm = 0.010f;
  641. m_materialContacts[(int)Material.Wood, 0].surface.soft_erp = 0.010f;
  642. m_materialContacts[(int)Material.Wood, 1] = new d.Contact();
  643. m_materialContacts[(int)Material.Wood, 1].surface.mode |= d.ContactFlags.SoftERP;
  644. m_materialContacts[(int)Material.Wood, 1].surface.mu = mAvatarObjectContactFriction;
  645. m_materialContacts[(int)Material.Wood, 1].surface.bounce = mAvatarObjectContactBounce;
  646. m_materialContacts[(int)Material.Wood, 1].surface.soft_cfm = 0.010f;
  647. m_materialContacts[(int)Material.Wood, 1].surface.soft_erp = 0.010f;
  648. m_materialContacts[(int)Material.Flesh, 0] = new d.Contact();
  649. m_materialContacts[(int)Material.Flesh, 0].surface.mode |= d.ContactFlags.SoftERP;
  650. m_materialContacts[(int)Material.Flesh, 0].surface.mu = nmAvatarObjectContactFriction;
  651. m_materialContacts[(int)Material.Flesh, 0].surface.bounce = nmAvatarObjectContactBounce;
  652. m_materialContacts[(int)Material.Flesh, 0].surface.soft_cfm = 0.010f;
  653. m_materialContacts[(int)Material.Flesh, 0].surface.soft_erp = 0.010f;
  654. m_materialContacts[(int)Material.Flesh, 1] = new d.Contact();
  655. m_materialContacts[(int)Material.Flesh, 1].surface.mode |= d.ContactFlags.SoftERP;
  656. m_materialContacts[(int)Material.Flesh, 1].surface.mu = mAvatarObjectContactFriction;
  657. m_materialContacts[(int)Material.Flesh, 1].surface.bounce = mAvatarObjectContactBounce;
  658. m_materialContacts[(int)Material.Flesh, 1].surface.soft_cfm = 0.010f;
  659. m_materialContacts[(int)Material.Flesh, 1].surface.soft_erp = 0.010f;
  660. m_materialContacts[(int)Material.Plastic, 0] = new d.Contact();
  661. m_materialContacts[(int)Material.Plastic, 0].surface.mode |= d.ContactFlags.SoftERP;
  662. m_materialContacts[(int)Material.Plastic, 0].surface.mu = nmAvatarObjectContactFriction;
  663. m_materialContacts[(int)Material.Plastic, 0].surface.bounce = nmAvatarObjectContactBounce;
  664. m_materialContacts[(int)Material.Plastic, 0].surface.soft_cfm = 0.010f;
  665. m_materialContacts[(int)Material.Plastic, 0].surface.soft_erp = 0.010f;
  666. m_materialContacts[(int)Material.Plastic, 1] = new d.Contact();
  667. m_materialContacts[(int)Material.Plastic, 1].surface.mode |= d.ContactFlags.SoftERP;
  668. m_materialContacts[(int)Material.Plastic, 1].surface.mu = mAvatarObjectContactFriction;
  669. m_materialContacts[(int)Material.Plastic, 1].surface.bounce = mAvatarObjectContactBounce;
  670. m_materialContacts[(int)Material.Plastic, 1].surface.soft_cfm = 0.010f;
  671. m_materialContacts[(int)Material.Plastic, 1].surface.soft_erp = 0.010f;
  672. m_materialContacts[(int)Material.Rubber, 0] = new d.Contact();
  673. m_materialContacts[(int)Material.Rubber, 0].surface.mode |= d.ContactFlags.SoftERP;
  674. m_materialContacts[(int)Material.Rubber, 0].surface.mu = nmAvatarObjectContactFriction;
  675. m_materialContacts[(int)Material.Rubber, 0].surface.bounce = nmAvatarObjectContactBounce;
  676. m_materialContacts[(int)Material.Rubber, 0].surface.soft_cfm = 0.010f;
  677. m_materialContacts[(int)Material.Rubber, 0].surface.soft_erp = 0.010f;
  678. m_materialContacts[(int)Material.Rubber, 1] = new d.Contact();
  679. m_materialContacts[(int)Material.Rubber, 1].surface.mode |= d.ContactFlags.SoftERP;
  680. m_materialContacts[(int)Material.Rubber, 1].surface.mu = mAvatarObjectContactFriction;
  681. m_materialContacts[(int)Material.Rubber, 1].surface.bounce = mAvatarObjectContactBounce;
  682. m_materialContacts[(int)Material.Rubber, 1].surface.soft_cfm = 0.010f;
  683. m_materialContacts[(int)Material.Rubber, 1].surface.soft_erp = 0.010f;
  684. d.HashSpaceSetLevels(space, HashspaceLow, HashspaceHigh);
  685. // Set the gravity,, don't disable things automatically (we set it explicitly on some things)
  686. d.WorldSetGravity(world, gravityx, gravityy, gravityz);
  687. d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  688. d.WorldSetLinearDamping(world, 256f);
  689. d.WorldSetAngularDamping(world, 256f);
  690. d.WorldSetAngularDampingThreshold(world, 256f);
  691. d.WorldSetLinearDampingThreshold(world, 256f);
  692. d.WorldSetMaxAngularSpeed(world, 256f);
  693. d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  694. //d.WorldSetContactMaxCorrectingVel(world, 1000.0f);
  695. for (int i = 0; i < staticPrimspace.GetLength(0); i++)
  696. {
  697. for (int j = 0; j < staticPrimspace.GetLength(1); j++)
  698. {
  699. staticPrimspace[i, j] = IntPtr.Zero;
  700. }
  701. }
  702. _worldInitialized = true;
  703. }
  704. #region Collision Detection
  705. /// <summary>
  706. /// Collides two geometries.
  707. /// </summary>
  708. /// <returns></returns>
  709. /// <param name='geom1'></param>
  710. /// <param name='geom2'>/param>
  711. /// <param name='maxContacts'></param>
  712. /// <param name='contactsArray'></param>
  713. /// <param name='contactGeomSize'></param>
  714. private int CollideGeoms(
  715. IntPtr geom1, IntPtr geom2, int maxContacts, d.ContactGeom[] contactsArray, int contactGeomSize)
  716. {
  717. int count;
  718. lock (OdeScene.UniversalColliderSyncObject)
  719. {
  720. // We do this inside the lock so that we don't count any delay in acquiring it
  721. if (CollectStats)
  722. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  723. count = d.Collide(geom1, geom2, maxContacts, contactsArray, contactGeomSize);
  724. }
  725. // We do this outside the lock so that any waiting threads aren't held up, though the effect is probably
  726. // negligable
  727. if (CollectStats)
  728. m_stats[ODENativeGeomCollisionFrameMsStatName]
  729. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  730. return count;
  731. }
  732. /// <summary>
  733. /// Collide two spaces or a space and a geometry.
  734. /// </summary>
  735. /// <param name='space1'></param>
  736. /// <param name='space2'>/param>
  737. /// <param name='data'></param>
  738. private void CollideSpaces(IntPtr space1, IntPtr space2, IntPtr data)
  739. {
  740. if (CollectStats)
  741. {
  742. m_inCollisionTiming = true;
  743. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  744. }
  745. d.SpaceCollide2(space1, space2, data, nearCallback);
  746. if (CollectStats && m_inCollisionTiming)
  747. {
  748. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  749. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  750. m_inCollisionTiming = false;
  751. }
  752. }
  753. /// <summary>
  754. /// This is our near callback. A geometry is near a body
  755. /// </summary>
  756. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  757. /// <param name="g1">a geometry or space</param>
  758. /// <param name="g2">another geometry or space</param>
  759. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  760. {
  761. if (CollectStats && m_inCollisionTiming)
  762. {
  763. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  764. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  765. m_inCollisionTiming = false;
  766. }
  767. // m_log.DebugFormat("[PHYSICS]: Colliding {0} and {1} in {2}", g1, g2, space);
  768. // no lock here! It's invoked from within Simulate(), which is thread-locked
  769. // Test if we're colliding a geom with a space.
  770. // If so we have to drill down into the space recursively
  771. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  772. {
  773. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  774. return;
  775. // Separating static prim geometry spaces.
  776. // We'll be calling near recursivly if one
  777. // of them is a space to find all of the
  778. // contact points in the space
  779. try
  780. {
  781. CollideSpaces(g1, g2, IntPtr.Zero);
  782. }
  783. catch (AccessViolationException)
  784. {
  785. m_log.Error("[ODE SCENE]: Unable to collide test a space");
  786. return;
  787. }
  788. //Colliding a space or a geom with a space or a geom. so drill down
  789. //Collide all geoms in each space..
  790. //if (d.GeomIsSpace(g1)) d.SpaceCollide(g1, IntPtr.Zero, nearCallback);
  791. //if (d.GeomIsSpace(g2)) d.SpaceCollide(g2, IntPtr.Zero, nearCallback);
  792. return;
  793. }
  794. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  795. return;
  796. IntPtr b1 = d.GeomGetBody(g1);
  797. IntPtr b2 = d.GeomGetBody(g2);
  798. // d.GeomClassID id = d.GeomGetClass(g1);
  799. String name1 = null;
  800. String name2 = null;
  801. if (!geom_name_map.TryGetValue(g1, out name1))
  802. {
  803. name1 = "null";
  804. }
  805. if (!geom_name_map.TryGetValue(g2, out name2))
  806. {
  807. name2 = "null";
  808. }
  809. // Figure out how many contact points we have
  810. int count = 0;
  811. try
  812. {
  813. // Colliding Geom To Geom
  814. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  815. if (g1 == g2)
  816. return; // Can't collide with yourself
  817. if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
  818. return;
  819. count = CollideGeoms(g1, g2, contacts.Length, contacts, d.ContactGeom.unmanagedSizeOf);
  820. // All code after this is only relevant if we have any collisions
  821. if (count <= 0)
  822. return;
  823. if (count > contacts.Length)
  824. m_log.Error("[ODE SCENE]: Got " + count + " contacts when we asked for a maximum of " + contacts.Length);
  825. }
  826. catch (SEHException)
  827. {
  828. m_log.Error(
  829. "[ODE SCENE]: 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.");
  830. base.TriggerPhysicsBasedRestart();
  831. }
  832. catch (Exception e)
  833. {
  834. m_log.ErrorFormat("[ODE SCENE]: Unable to collide test an object: {0}", e.Message);
  835. return;
  836. }
  837. PhysicsActor p1;
  838. PhysicsActor p2;
  839. p1ExpectedPoints = 0;
  840. p2ExpectedPoints = 0;
  841. if (!actor_name_map.TryGetValue(g1, out p1))
  842. {
  843. p1 = PANull;
  844. }
  845. if (!actor_name_map.TryGetValue(g2, out p2))
  846. {
  847. p2 = PANull;
  848. }
  849. ContactPoint maxDepthContact = new ContactPoint();
  850. if (p1.CollisionScore + count >= float.MaxValue)
  851. p1.CollisionScore = 0;
  852. p1.CollisionScore += count;
  853. if (p2.CollisionScore + count >= float.MaxValue)
  854. p2.CollisionScore = 0;
  855. p2.CollisionScore += count;
  856. for (int i = 0; i < count; i++)
  857. {
  858. d.ContactGeom curContact = contacts[i];
  859. if (curContact.depth > maxDepthContact.PenetrationDepth)
  860. {
  861. maxDepthContact = new ContactPoint(
  862. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  863. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  864. curContact.depth
  865. );
  866. }
  867. //m_log.Warn("[CCOUNT]: " + count);
  868. IntPtr joint;
  869. // If we're colliding with terrain, use 'TerrainContact' instead of contact.
  870. // allows us to have different settings
  871. // We only need to test p2 for 'jump crouch purposes'
  872. if (p2 is OdeCharacter && p1.PhysicsActorType == (int)ActorTypes.Prim)
  873. {
  874. // Testing if the collision is at the feet of the avatar
  875. //m_log.DebugFormat("[PHYSICS]: {0} - {1} - {2} - {3}", curContact.pos.Z, p2.Position.Z, (p2.Position.Z - curContact.pos.Z), (p2.Size.Z * 0.6f));
  876. if ((p2.Position.Z - curContact.pos.Z) > (p2.Size.Z * 0.6f))
  877. p2.IsColliding = true;
  878. }
  879. else
  880. {
  881. p2.IsColliding = true;
  882. }
  883. //if ((framecount % m_returncollisions) == 0)
  884. switch (p1.PhysicsActorType)
  885. {
  886. case (int)ActorTypes.Agent:
  887. p1ExpectedPoints = avatarExpectedContacts;
  888. p2.CollidingObj = true;
  889. break;
  890. case (int)ActorTypes.Prim:
  891. if (p1 != null && p1 is OdePrim)
  892. p1ExpectedPoints = ((OdePrim) p1).ExpectedCollisionContacts;
  893. if (p2.Velocity.LengthSquared() > 0.0f)
  894. p2.CollidingObj = true;
  895. break;
  896. case (int)ActorTypes.Unknown:
  897. p2.CollidingGround = true;
  898. break;
  899. default:
  900. p2.CollidingGround = true;
  901. break;
  902. }
  903. // we don't want prim or avatar to explode
  904. #region InterPenetration Handling - Unintended physics explosions
  905. if (curContact.depth >= 0.08f)
  906. {
  907. if (curContact.depth >= 1.00f)
  908. {
  909. //m_log.Info("[P]: " + contact.depth.ToString());
  910. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  911. p1.PhysicsActorType == (int) ActorTypes.Unknown) ||
  912. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  913. p2.PhysicsActorType == (int) ActorTypes.Unknown))
  914. {
  915. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  916. {
  917. if (p2 is OdeCharacter)
  918. {
  919. OdeCharacter character = (OdeCharacter) p2;
  920. //p2.CollidingObj = true;
  921. curContact.depth = 0.00000003f;
  922. p2.Velocity = p2.Velocity + new Vector3(0f, 0f, 0.5f);
  923. curContact.pos =
  924. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  925. curContact.pos.Y + (p1.Size.Y/2),
  926. curContact.pos.Z + (p1.Size.Z/2));
  927. character.SetPidStatus(true);
  928. }
  929. }
  930. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  931. {
  932. if (p1 is OdeCharacter)
  933. {
  934. OdeCharacter character = (OdeCharacter) p1;
  935. //p2.CollidingObj = true;
  936. curContact.depth = 0.00000003f;
  937. p1.Velocity = p1.Velocity + new Vector3(0f, 0f, 0.5f);
  938. curContact.pos =
  939. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  940. curContact.pos.Y + (p1.Size.Y/2),
  941. curContact.pos.Z + (p1.Size.Z/2));
  942. character.SetPidStatus(true);
  943. }
  944. }
  945. }
  946. }
  947. }
  948. #endregion
  949. // Logic for collision handling
  950. // Note, that if *all* contacts are skipped (VolumeDetect)
  951. // The prim still detects (and forwards) collision events but
  952. // appears to be phantom for the world
  953. Boolean skipThisContact = false;
  954. if ((p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect))
  955. skipThisContact = true; // No collision on volume detect prims
  956. if (av_av_collisions_off)
  957. if ((p1 is OdeCharacter) && (p2 is OdeCharacter))
  958. skipThisContact = true;
  959. if (!skipThisContact && (p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect))
  960. skipThisContact = true; // No collision on volume detect prims
  961. if (!skipThisContact && curContact.depth < 0f)
  962. skipThisContact = true;
  963. if (!skipThisContact && checkDupe(curContact, p2.PhysicsActorType))
  964. skipThisContact = true;
  965. const int maxContactsbeforedeath = 4000;
  966. joint = IntPtr.Zero;
  967. if (!skipThisContact)
  968. {
  969. _perloopContact.Add(curContact);
  970. if (name1 == "Terrain" || name2 == "Terrain")
  971. {
  972. if ((p2.PhysicsActorType == (int) ActorTypes.Agent) &&
  973. (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  974. {
  975. p2ExpectedPoints = avatarExpectedContacts;
  976. // Avatar is moving on terrain, use the movement terrain contact
  977. AvatarMovementTerrainContact.geom = curContact;
  978. if (m_global_contactcount < maxContactsbeforedeath)
  979. {
  980. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementTerrainContact);
  981. m_global_contactcount++;
  982. }
  983. }
  984. else
  985. {
  986. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  987. {
  988. p2ExpectedPoints = avatarExpectedContacts;
  989. // Avatar is standing on terrain, use the non moving terrain contact
  990. TerrainContact.geom = curContact;
  991. if (m_global_contactcount < maxContactsbeforedeath)
  992. {
  993. joint = d.JointCreateContact(world, contactgroup, ref TerrainContact);
  994. m_global_contactcount++;
  995. }
  996. }
  997. else
  998. {
  999. if (p2.PhysicsActorType == (int)ActorTypes.Prim && p1.PhysicsActorType == (int)ActorTypes.Prim)
  1000. {
  1001. // prim prim contact
  1002. // int pj294950 = 0;
  1003. int movintYN = 0;
  1004. int material = (int) Material.Wood;
  1005. // prim terrain contact
  1006. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1007. {
  1008. movintYN = 1;
  1009. }
  1010. if (p2 is OdePrim)
  1011. {
  1012. material = ((OdePrim) p2).m_material;
  1013. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1014. }
  1015. // Unnessesary because p1 is defined above
  1016. //if (p1 is OdePrim)
  1017. // {
  1018. // p1ExpectedPoints = ((OdePrim)p1).ExpectedCollisionContacts;
  1019. // }
  1020. //m_log.DebugFormat("Material: {0}", material);
  1021. m_materialContacts[material, movintYN].geom = curContact;
  1022. if (m_global_contactcount < maxContactsbeforedeath)
  1023. {
  1024. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1025. m_global_contactcount++;
  1026. }
  1027. }
  1028. else
  1029. {
  1030. int movintYN = 0;
  1031. // prim terrain contact
  1032. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1033. {
  1034. movintYN = 1;
  1035. }
  1036. int material = (int)Material.Wood;
  1037. if (p2 is OdePrim)
  1038. {
  1039. material = ((OdePrim)p2).m_material;
  1040. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1041. }
  1042. //m_log.DebugFormat("Material: {0}", material);
  1043. m_materialContacts[material, movintYN].geom = curContact;
  1044. if (m_global_contactcount < maxContactsbeforedeath)
  1045. {
  1046. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1047. m_global_contactcount++;
  1048. }
  1049. }
  1050. }
  1051. }
  1052. //if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1053. //{
  1054. //m_log.Debug("[PHYSICS]: prim contacting with ground");
  1055. //}
  1056. }
  1057. else if (name1 == "Water" || name2 == "Water")
  1058. {
  1059. /*
  1060. if ((p2.PhysicsActorType == (int) ActorTypes.Prim))
  1061. {
  1062. }
  1063. else
  1064. {
  1065. }
  1066. */
  1067. //WaterContact.surface.soft_cfm = 0.0000f;
  1068. //WaterContact.surface.soft_erp = 0.00000f;
  1069. if (curContact.depth > 0.1f)
  1070. {
  1071. curContact.depth *= 52;
  1072. //contact.normal = new d.Vector3(0, 0, 1);
  1073. //contact.pos = new d.Vector3(0, 0, contact.pos.Z - 5f);
  1074. }
  1075. WaterContact.geom = curContact;
  1076. if (m_global_contactcount < maxContactsbeforedeath)
  1077. {
  1078. joint = d.JointCreateContact(world, contactgroup, ref WaterContact);
  1079. m_global_contactcount++;
  1080. }
  1081. //m_log.Info("[PHYSICS]: Prim Water Contact" + contact.depth);
  1082. }
  1083. else
  1084. {
  1085. if ((p2.PhysicsActorType == (int)ActorTypes.Agent))
  1086. {
  1087. p2ExpectedPoints = avatarExpectedContacts;
  1088. if ((Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  1089. {
  1090. // Avatar is moving on a prim, use the Movement prim contact
  1091. AvatarMovementprimContact.geom = curContact;
  1092. if (m_global_contactcount < maxContactsbeforedeath)
  1093. {
  1094. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementprimContact);
  1095. m_global_contactcount++;
  1096. }
  1097. }
  1098. else
  1099. {
  1100. // Avatar is standing still on a prim, use the non movement contact
  1101. contact.geom = curContact;
  1102. if (m_global_contactcount < maxContactsbeforedeath)
  1103. {
  1104. joint = d.JointCreateContact(world, contactgroup, ref contact);
  1105. m_global_contactcount++;
  1106. }
  1107. }
  1108. }
  1109. else if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1110. {
  1111. //p1.PhysicsActorType
  1112. int material = (int)Material.Wood;
  1113. if (p2 is OdePrim)
  1114. {
  1115. material = ((OdePrim)p2).m_material;
  1116. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1117. }
  1118. //m_log.DebugFormat("Material: {0}", material);
  1119. m_materialContacts[material, 0].geom = curContact;
  1120. if (m_global_contactcount < maxContactsbeforedeath)
  1121. {
  1122. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, 0]);
  1123. m_global_contactcount++;
  1124. }
  1125. }
  1126. }
  1127. if (m_global_contactcount < maxContactsbeforedeath && joint != IntPtr.Zero) // stack collide!
  1128. {
  1129. d.JointAttach(joint, b1, b2);
  1130. m_global_contactcount++;
  1131. }
  1132. }
  1133. collision_accounting_events(p1, p2, maxDepthContact);
  1134. if (count > ((p1ExpectedPoints + p2ExpectedPoints) * 0.25) + (geomContactPointsStartthrottle))
  1135. {
  1136. // If there are more then 3 contact points, it's likely
  1137. // that we've got a pile of objects, so ...
  1138. // We don't want to send out hundreds of terse updates over and over again
  1139. // so lets throttle them and send them again after it's somewhat sorted out.
  1140. p2.ThrottleUpdates = true;
  1141. }
  1142. //m_log.Debug(count.ToString());
  1143. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  1144. }
  1145. }
  1146. private bool checkDupe(d.ContactGeom contactGeom, int atype)
  1147. {
  1148. if (!m_filterCollisions)
  1149. return false;
  1150. bool result = false;
  1151. ActorTypes at = (ActorTypes)atype;
  1152. foreach (d.ContactGeom contact in _perloopContact)
  1153. {
  1154. //if ((contact.g1 == contactGeom.g1 && contact.g2 == contactGeom.g2))
  1155. //{
  1156. // || (contact.g2 == contactGeom.g1 && contact.g1 == contactGeom.g2)
  1157. if (at == ActorTypes.Agent)
  1158. {
  1159. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f)
  1160. && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f)
  1161. && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1162. {
  1163. if (Math.Abs(contact.depth - contactGeom.depth) < 0.052f)
  1164. {
  1165. result = true;
  1166. break;
  1167. }
  1168. }
  1169. }
  1170. else if (at == ActorTypes.Prim)
  1171. {
  1172. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f) && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f) && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1173. {
  1174. if (contactGeom.normal.X == contact.normal.X && contactGeom.normal.Y == contact.normal.Y && contactGeom.normal.Z == contact.normal.Z)
  1175. {
  1176. if (Math.Abs(contact.depth - contactGeom.depth) < 0.272f)
  1177. {
  1178. result = true;
  1179. break;
  1180. }
  1181. }
  1182. //m_log.DebugFormat("[Collision]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1183. //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1184. }
  1185. }
  1186. }
  1187. return result;
  1188. }
  1189. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  1190. {
  1191. // obj1LocalID = 0;
  1192. //returncollisions = false;
  1193. obj2LocalID = 0;
  1194. //ctype = 0;
  1195. //cStartStop = 0;
  1196. // if (!p2.SubscribedEvents() && !p1.SubscribedEvents())
  1197. // return;
  1198. bool p1events = p1.SubscribedEvents();
  1199. bool p2events = p2.SubscribedEvents();
  1200. if (p1.IsVolumeDtc)
  1201. p2events = false;
  1202. if (p2.IsVolumeDtc)
  1203. p1events = false;
  1204. if (!p2events && !p1events)
  1205. return;
  1206. Vector3 vel = Vector3.Zero;
  1207. if (p2 != null && p2.IsPhysical)
  1208. vel = p2.Velocity;
  1209. if (p1 != null && p1.IsPhysical)
  1210. vel -= p1.Velocity;
  1211. contact.RelativeSpeed = Vector3.Dot(vel, contact.SurfaceNormal);
  1212. switch ((ActorTypes)p2.PhysicsActorType)
  1213. {
  1214. case ActorTypes.Agent:
  1215. cc2 = (OdeCharacter)p2;
  1216. // obj1LocalID = cc2.m_localID;
  1217. switch ((ActorTypes)p1.PhysicsActorType)
  1218. {
  1219. case ActorTypes.Agent:
  1220. cc1 = (OdeCharacter)p1;
  1221. obj2LocalID = cc1.LocalID;
  1222. cc1.AddCollisionEvent(cc2.LocalID, contact);
  1223. break;
  1224. case ActorTypes.Prim:
  1225. if (p1 is OdePrim)
  1226. {
  1227. cp1 = (OdePrim) p1;
  1228. obj2LocalID = cp1.LocalID;
  1229. cp1.AddCollisionEvent(cc2.LocalID, contact);
  1230. }
  1231. break;
  1232. case ActorTypes.Ground:
  1233. case ActorTypes.Unknown:
  1234. obj2LocalID = 0;
  1235. break;
  1236. }
  1237. cc2.AddCollisionEvent(obj2LocalID, contact);
  1238. break;
  1239. case ActorTypes.Prim:
  1240. if (p2 is OdePrim)
  1241. {
  1242. cp2 = (OdePrim) p2;
  1243. // obj1LocalID = cp2.m_localID;
  1244. switch ((ActorTypes) p1.PhysicsActorType)
  1245. {
  1246. case ActorTypes.Agent:
  1247. if (p1 is OdeCharacter)
  1248. {
  1249. cc1 = (OdeCharacter) p1;
  1250. obj2LocalID = cc1.LocalID;
  1251. cc1.AddCollisionEvent(cp2.LocalID, contact);
  1252. }
  1253. break;
  1254. case ActorTypes.Prim:
  1255. if (p1 is OdePrim)
  1256. {
  1257. cp1 = (OdePrim) p1;
  1258. obj2LocalID = cp1.LocalID;
  1259. cp1.AddCollisionEvent(cp2.LocalID, contact);
  1260. }
  1261. break;
  1262. case ActorTypes.Ground:
  1263. case ActorTypes.Unknown:
  1264. obj2LocalID = 0;
  1265. break;
  1266. }
  1267. cp2.AddCollisionEvent(obj2LocalID, contact);
  1268. }
  1269. break;
  1270. }
  1271. }
  1272. /// <summary>
  1273. /// This is our collision testing routine in ODE
  1274. /// </summary>
  1275. private void collision_optimized()
  1276. {
  1277. _perloopContact.Clear();
  1278. foreach (OdeCharacter chr in _characters)
  1279. {
  1280. // Reset the collision values to false
  1281. // since we don't know if we're colliding yet
  1282. if (chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero)
  1283. continue;
  1284. chr.IsColliding = false;
  1285. chr.CollidingGround = false;
  1286. chr.CollidingObj = false;
  1287. // Test the avatar's geometry for collision with the space
  1288. // This will return near and the space that they are the closest to
  1289. // And we'll run this again against the avatar and the space segment
  1290. // This will return with a bunch of possible objects in the space segment
  1291. // and we'll run it again on all of them.
  1292. try
  1293. {
  1294. CollideSpaces(space, chr.Shell, IntPtr.Zero);
  1295. }
  1296. catch (AccessViolationException)
  1297. {
  1298. m_log.ErrorFormat("[ODE SCENE]: Unable to space collide {0}", PhysicsSceneName);
  1299. }
  1300. //float terrainheight = GetTerrainHeightAtXY(chr.Position.X, chr.Position.Y);
  1301. //if (chr.Position.Z + (chr.Velocity.Z * timeStep) < terrainheight + 10)
  1302. //{
  1303. //chr.Position.Z = terrainheight + 10.0f;
  1304. //forcedZ = true;
  1305. //}
  1306. }
  1307. if (CollectStats)
  1308. {
  1309. m_tempAvatarCollisionsThisFrame = _perloopContact.Count;
  1310. m_stats[ODEAvatarContactsStatsName] += m_tempAvatarCollisionsThisFrame;
  1311. }
  1312. List<OdePrim> removeprims = null;
  1313. foreach (OdePrim chr in _activeprims)
  1314. {
  1315. if (chr.Body != IntPtr.Zero && d.BodyIsEnabled(chr.Body) && (!chr.m_disabled))
  1316. {
  1317. try
  1318. {
  1319. lock (chr)
  1320. {
  1321. if (space != IntPtr.Zero && chr.prim_geom != IntPtr.Zero && chr.m_taintremove == false)
  1322. {
  1323. CollideSpaces(space, chr.prim_geom, IntPtr.Zero);
  1324. }
  1325. else
  1326. {
  1327. if (removeprims == null)
  1328. {
  1329. removeprims = new List<OdePrim>();
  1330. }
  1331. removeprims.Add(chr);
  1332. m_log.Error(
  1333. "[ODE SCENE]: unable to collide test active prim against space. The space was zero, the geom was zero or it was in the process of being removed. Removed it from the active prim list. This needs to be fixed!");
  1334. }
  1335. }
  1336. }
  1337. catch (AccessViolationException)
  1338. {
  1339. m_log.Error("[ODE SCENE]: Unable to space collide");
  1340. }
  1341. }
  1342. }
  1343. if (CollectStats)
  1344. m_stats[ODEPrimContactsStatName] += _perloopContact.Count - m_tempAvatarCollisionsThisFrame;
  1345. if (removeprims != null)
  1346. {
  1347. foreach (OdePrim chr in removeprims)
  1348. {
  1349. _activeprims.Remove(chr);
  1350. }
  1351. }
  1352. }
  1353. #endregion
  1354. // Recovered for use by fly height. Kitto Flora
  1355. internal float GetTerrainHeightAtXY(float x, float y)
  1356. {
  1357. IntPtr heightFieldGeom = IntPtr.Zero;
  1358. int offsetX = 0;
  1359. int offsetY = 0;
  1360. if(RegionTerrain.TryGetValue(new Vector3(offsetX,offsetY,0), out heightFieldGeom))
  1361. {
  1362. if (heightFieldGeom != IntPtr.Zero)
  1363. {
  1364. if (TerrainHeightFieldHeights.ContainsKey(heightFieldGeom))
  1365. {
  1366. int index;
  1367. if ((int)x > WorldExtents.X || (int)y > WorldExtents.Y ||
  1368. (int)x < 0.001f || (int)y < 0.001f)
  1369. return 0;
  1370. x = x - offsetX + 1f;
  1371. y = y - offsetY + 1f;
  1372. // map is rotated
  1373. index = (int)x * ((int)m_regionHeight + 3) + (int)y;
  1374. if (index < TerrainHeightFieldHeights[heightFieldGeom].Length)
  1375. {
  1376. //m_log.DebugFormat("x{0} y{1} = {2}", x, y, (float)TerrainHeightFieldHeights[heightFieldGeom][index]);
  1377. return (float)TerrainHeightFieldHeights[heightFieldGeom][index];
  1378. }
  1379. else
  1380. return 0f;
  1381. }
  1382. else
  1383. {
  1384. return 0f;
  1385. }
  1386. }
  1387. else
  1388. {
  1389. return 0f;
  1390. }
  1391. }
  1392. else
  1393. {
  1394. return 0f;
  1395. }
  1396. }
  1397. // End recovered. Kitto Flora
  1398. /// <summary>
  1399. /// Add actor to the list that should receive collision events in the simulate loop.
  1400. /// </summary>
  1401. /// <param name="obj"></param>
  1402. internal void AddCollisionEventReporting(PhysicsActor obj)
  1403. {
  1404. // m_log.DebugFormat("[PHYSICS]: Adding {0} {1} to collision event reporting", obj.SOPName, obj.LocalID);
  1405. lock (m_collisionEventActorsChanges)
  1406. m_collisionEventActorsChanges[obj.LocalID] = obj;
  1407. }
  1408. /// <summary>
  1409. /// Remove actor from the list that should receive collision events in the simulate loop.
  1410. /// </summary>
  1411. /// <param name="obj"></param>
  1412. internal void RemoveCollisionEventReporting(PhysicsActor obj)
  1413. {
  1414. // m_log.DebugFormat("[PHYSICS]: Removing {0} {1} from collision event reporting", obj.SOPName, obj.LocalID);
  1415. lock (m_collisionEventActorsChanges)
  1416. m_collisionEventActorsChanges[obj.LocalID] = null;
  1417. }
  1418. #region Add/Remove Entities
  1419. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  1420. {
  1421. d.AllocateODEDataForThread(0);
  1422. OdeCharacter newAv
  1423. = new OdeCharacter(
  1424. avName, this, position, velocity, size, avPIDD, avPIDP,
  1425. avCapRadius, avStandupTensor, avDensity,
  1426. avMovementDivisorWalk, avMovementDivisorRun);
  1427. newAv.Flying = isFlying;
  1428. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1429. newAv.m_avatarplanted = avplanted;
  1430. return newAv;
  1431. }
  1432. public override void RemoveAvatar(PhysicsActor actor)
  1433. {
  1434. // m_log.DebugFormat(
  1435. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}",
  1436. // actor.Name, actor.LocalID, Name);
  1437. lock (OdeLock)
  1438. {
  1439. d.AllocateODEDataForThread(0);
  1440. ((OdeCharacter) actor).Destroy();
  1441. }
  1442. }
  1443. internal void AddCharacter(OdeCharacter chr)
  1444. {
  1445. chr.m_avatarplanted = avplanted;
  1446. if (!_characters.Contains(chr))
  1447. {
  1448. _characters.Add(chr);
  1449. // m_log.DebugFormat(
  1450. // "[ODE SCENE]: Adding physics character {0} {1} to physics scene {2}. Count now {3}",
  1451. // chr.Name, chr.LocalID, Name, _characters.Count);
  1452. if (chr.bad)
  1453. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to characters list", chr.m_uuid);
  1454. }
  1455. else
  1456. {
  1457. m_log.ErrorFormat(
  1458. "[ODE SCENE]: Tried to add character {0} {1} but they are already in the set!",
  1459. chr.Name, chr.LocalID);
  1460. }
  1461. }
  1462. internal void RemoveCharacter(OdeCharacter chr)
  1463. {
  1464. if (_characters.Contains(chr))
  1465. {
  1466. _characters.Remove(chr);
  1467. // m_log.DebugFormat(
  1468. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}. Count now {3}",
  1469. // chr.Name, chr.LocalID, Name, _characters.Count);
  1470. }
  1471. else
  1472. {
  1473. m_log.ErrorFormat(
  1474. "[ODE SCENE]: Tried to remove character {0} {1} but they are not in the list!",
  1475. chr.Name, chr.LocalID);
  1476. }
  1477. }
  1478. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1479. PrimitiveBaseShape pbs, bool isphysical, uint localID)
  1480. {
  1481. Vector3 pos = position;
  1482. Vector3 siz = size;
  1483. Quaternion rot = rotation;
  1484. OdePrim newPrim;
  1485. lock (OdeLock)
  1486. {
  1487. d.AllocateODEDataForThread(0);
  1488. newPrim = new OdePrim(name, this, pos, siz, rot, pbs, isphysical);
  1489. lock (_prims)
  1490. _prims.Add(newPrim);
  1491. }
  1492. newPrim.LocalID = localID;
  1493. return newPrim;
  1494. }
  1495. /// <summary>
  1496. /// Make this prim subject to physics.
  1497. /// </summary>
  1498. /// <param name="prim"></param>
  1499. internal void ActivatePrim(OdePrim prim)
  1500. {
  1501. // adds active prim.. (ones that should be iterated over in collisions_optimized
  1502. if (!_activeprims.Contains(prim))
  1503. _activeprims.Add(prim);
  1504. //else
  1505. // m_log.Warn("[PHYSICS]: Double Entry in _activeprims detected, potential crash immenent");
  1506. }
  1507. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1508. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1509. {
  1510. // m_log.DebugFormat("[ODE SCENE]: Adding physics prim {0} {1} to physics scene {2}", primName, localid, Name);
  1511. return AddPrim(primName, position, size, rotation, pbs, isPhysical, localid);
  1512. }
  1513. public override float TimeDilation
  1514. {
  1515. get { return m_timeDilation; }
  1516. }
  1517. public override bool SupportsNINJAJoints
  1518. {
  1519. get { return m_NINJA_physics_joints_enabled; }
  1520. }
  1521. // internal utility function: must be called within a lock (OdeLock)
  1522. private void InternalAddActiveJoint(PhysicsJoint joint)
  1523. {
  1524. activeJoints.Add(joint);
  1525. SOPName_to_activeJoint.Add(joint.ObjectNameInScene, joint);
  1526. }
  1527. // internal utility function: must be called within a lock (OdeLock)
  1528. private void InternalAddPendingJoint(OdePhysicsJoint joint)
  1529. {
  1530. pendingJoints.Add(joint);
  1531. SOPName_to_pendingJoint.Add(joint.ObjectNameInScene, joint);
  1532. }
  1533. // internal utility function: must be called within a lock (OdeLock)
  1534. private void InternalRemovePendingJoint(PhysicsJoint joint)
  1535. {
  1536. pendingJoints.Remove(joint);
  1537. SOPName_to_pendingJoint.Remove(joint.ObjectNameInScene);
  1538. }
  1539. // internal utility function: must be called within a lock (OdeLock)
  1540. private void InternalRemoveActiveJoint(PhysicsJoint joint)
  1541. {
  1542. activeJoints.Remove(joint);
  1543. SOPName_to_activeJoint.Remove(joint.ObjectNameInScene);
  1544. }
  1545. public override void DumpJointInfo()
  1546. {
  1547. string hdr = "[NINJA] JOINTINFO: ";
  1548. foreach (PhysicsJoint j in pendingJoints)
  1549. {
  1550. m_log.Debug(hdr + " pending joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1551. }
  1552. m_log.Debug(hdr + pendingJoints.Count + " total pending joints");
  1553. foreach (string jointName in SOPName_to_pendingJoint.Keys)
  1554. {
  1555. m_log.Debug(hdr + " pending joints dict contains Name: " + jointName);
  1556. }
  1557. m_log.Debug(hdr + SOPName_to_pendingJoint.Keys.Count + " total pending joints dict entries");
  1558. foreach (PhysicsJoint j in activeJoints)
  1559. {
  1560. m_log.Debug(hdr + " active joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1561. }
  1562. m_log.Debug(hdr + activeJoints.Count + " total active joints");
  1563. foreach (string jointName in SOPName_to_activeJoint.Keys)
  1564. {
  1565. m_log.Debug(hdr + " active joints dict contains Name: " + jointName);
  1566. }
  1567. m_log.Debug(hdr + SOPName_to_activeJoint.Keys.Count + " total active joints dict entries");
  1568. m_log.Debug(hdr + " Per-body joint connectivity information follows.");
  1569. m_log.Debug(hdr + joints_connecting_actor.Keys.Count + " bodies are connected by joints.");
  1570. foreach (string actorName in joints_connecting_actor.Keys)
  1571. {
  1572. m_log.Debug(hdr + " Actor " + actorName + " has the following joints connecting it");
  1573. foreach (PhysicsJoint j in joints_connecting_actor[actorName])
  1574. {
  1575. m_log.Debug(hdr + " * joint Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1576. }
  1577. m_log.Debug(hdr + joints_connecting_actor[actorName].Count + " connecting joints total for this actor");
  1578. }
  1579. }
  1580. public override void RequestJointDeletion(string ObjectNameInScene)
  1581. {
  1582. lock (externalJointRequestsLock)
  1583. {
  1584. if (!requestedJointsToBeDeleted.Contains(ObjectNameInScene)) // forbid same deletion request from entering twice to prevent spurious deletions processed asynchronously
  1585. {
  1586. requestedJointsToBeDeleted.Add(ObjectNameInScene);
  1587. }
  1588. }
  1589. }
  1590. private void DeleteRequestedJoints()
  1591. {
  1592. List<string> myRequestedJointsToBeDeleted;
  1593. lock (externalJointRequestsLock)
  1594. {
  1595. // make a local copy of the shared list for processing (threading issues)
  1596. myRequestedJointsToBeDeleted = new List<string>(requestedJointsToBeDeleted);
  1597. }
  1598. foreach (string jointName in myRequestedJointsToBeDeleted)
  1599. {
  1600. lock (OdeLock)
  1601. {
  1602. //m_log.Debug("[NINJA] trying to deleting requested joint " + jointName);
  1603. if (SOPName_to_activeJoint.ContainsKey(jointName) || SOPName_to_pendingJoint.ContainsKey(jointName))
  1604. {
  1605. OdePhysicsJoint joint = null;
  1606. if (SOPName_to_activeJoint.ContainsKey(jointName))
  1607. {
  1608. joint = SOPName_to_activeJoint[jointName] as OdePhysicsJoint;
  1609. InternalRemoveActiveJoint(joint);
  1610. }
  1611. else if (SOPName_to_pendingJoint.ContainsKey(jointName))
  1612. {
  1613. joint = SOPName_to_pendingJoint[jointName] as OdePhysicsJoint;
  1614. InternalRemovePendingJoint(joint);
  1615. }
  1616. if (joint != null)
  1617. {
  1618. //m_log.Debug("joint.BodyNames.Count is " + joint.BodyNames.Count + " and contents " + joint.BodyNames);
  1619. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1620. {
  1621. string bodyName = joint.BodyNames[iBodyName];
  1622. if (bodyName != "NULL")
  1623. {
  1624. joints_connecting_actor[bodyName].Remove(joint);
  1625. if (joints_connecting_actor[bodyName].Count == 0)
  1626. {
  1627. joints_connecting_actor.Remove(bodyName);
  1628. }
  1629. }
  1630. }
  1631. DoJointDeactivated(joint);
  1632. if (joint.jointID != IntPtr.Zero)
  1633. {
  1634. d.JointDestroy(joint.jointID);
  1635. joint.jointID = IntPtr.Zero;
  1636. //DoJointErrorMessage(joint, "successfully destroyed joint " + jointName);
  1637. }
  1638. else
  1639. {
  1640. //m_log.Warn("[NINJA] Ignoring re-request to destroy joint " + jointName);
  1641. }
  1642. }
  1643. else
  1644. {
  1645. // DoJointErrorMessage(joint, "coult not find joint to destroy based on name " + jointName);
  1646. }
  1647. }
  1648. else
  1649. {
  1650. // DoJointErrorMessage(joint, "WARNING - joint removal failed, joint " + jointName);
  1651. }
  1652. }
  1653. }
  1654. // remove processed joints from the shared list
  1655. lock (externalJointRequestsLock)
  1656. {
  1657. foreach (string jointName in myRequestedJointsToBeDeleted)
  1658. {
  1659. requestedJointsToBeDeleted.Remove(jointName);
  1660. }
  1661. }
  1662. }
  1663. // for pending joints we don't know if their associated bodies exist yet or not.
  1664. // the joint is actually created during processing of the taints
  1665. private void CreateRequestedJoints()
  1666. {
  1667. List<PhysicsJoint> myRequestedJointsToBeCreated;
  1668. lock (externalJointRequestsLock)
  1669. {
  1670. // make a local copy of the shared list for processing (threading issues)
  1671. myRequestedJointsToBeCreated = new List<PhysicsJoint>(requestedJointsToBeCreated);
  1672. }
  1673. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1674. {
  1675. lock (OdeLock)
  1676. {
  1677. if (SOPName_to_pendingJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_pendingJoint[joint.ObjectNameInScene] != null)
  1678. {
  1679. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already pending joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  1680. continue;
  1681. }
  1682. if (SOPName_to_activeJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_activeJoint[joint.ObjectNameInScene] != null)
  1683. {
  1684. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already active joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  1685. continue;
  1686. }
  1687. InternalAddPendingJoint(joint as OdePhysicsJoint);
  1688. if (joint.BodyNames.Count >= 2)
  1689. {
  1690. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1691. {
  1692. string bodyName = joint.BodyNames[iBodyName];
  1693. if (bodyName != "NULL")
  1694. {
  1695. if (!joints_connecting_actor.ContainsKey(bodyName))
  1696. {
  1697. joints_connecting_actor.Add(bodyName, new List<PhysicsJoint>());
  1698. }
  1699. joints_connecting_actor[bodyName].Add(joint);
  1700. }
  1701. }
  1702. }
  1703. }
  1704. }
  1705. // remove processed joints from shared list
  1706. lock (externalJointRequestsLock)
  1707. {
  1708. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  1709. {
  1710. requestedJointsToBeCreated.Remove(joint);
  1711. }
  1712. }
  1713. }
  1714. /// <summary>
  1715. /// Add a request for joint creation.
  1716. /// </summary>
  1717. /// <remarks>
  1718. /// this joint will just be added to a waiting list that is NOT processed during the main
  1719. /// Simulate() loop (to avoid deadlocks). After Simulate() is finished, we handle unprocessed joint requests.
  1720. /// </remarks>
  1721. /// <param name="objectNameInScene"></param>
  1722. /// <param name="jointType"></param>
  1723. /// <param name="position"></param>
  1724. /// <param name="rotation"></param>
  1725. /// <param name="parms"></param>
  1726. /// <param name="bodyNames"></param>
  1727. /// <param name="trackedBodyName"></param>
  1728. /// <param name="localRotation"></param>
  1729. /// <returns></returns>
  1730. public override PhysicsJoint RequestJointCreation(
  1731. string objectNameInScene, PhysicsJointType jointType, Vector3 position,
  1732. Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation)
  1733. {
  1734. OdePhysicsJoint joint = new OdePhysicsJoint();
  1735. joint.ObjectNameInScene = objectNameInScene;
  1736. joint.Type = jointType;
  1737. joint.Position = position;
  1738. joint.Rotation = rotation;
  1739. joint.RawParams = parms;
  1740. joint.BodyNames = new List<string>(bodyNames);
  1741. joint.TrackedBodyName = trackedBodyName;
  1742. joint.LocalRotation = localRotation;
  1743. joint.jointID = IntPtr.Zero;
  1744. joint.ErrorMessageCount = 0;
  1745. lock (externalJointRequestsLock)
  1746. {
  1747. if (!requestedJointsToBeCreated.Contains(joint)) // forbid same creation request from entering twice
  1748. {
  1749. requestedJointsToBeCreated.Add(joint);
  1750. }
  1751. }
  1752. return joint;
  1753. }
  1754. private void RemoveAllJointsConnectedToActor(PhysicsActor actor)
  1755. {
  1756. //m_log.Debug("RemoveAllJointsConnectedToActor: start");
  1757. if (actor.SOPName != null && joints_connecting_actor.ContainsKey(actor.SOPName) && joints_connecting_actor[actor.SOPName] != null)
  1758. {
  1759. List<PhysicsJoint> jointsToRemove = new List<PhysicsJoint>();
  1760. //TODO: merge these 2 loops (originally it was needed to avoid altering a list being iterated over, but it is no longer needed due to the joint request queue mechanism)
  1761. foreach (PhysicsJoint j in joints_connecting_actor[actor.SOPName])
  1762. {
  1763. jointsToRemove.Add(j);
  1764. }
  1765. foreach (PhysicsJoint j in jointsToRemove)
  1766. {
  1767. //m_log.Debug("RemoveAllJointsConnectedToActor: about to request deletion of " + j.ObjectNameInScene);
  1768. RequestJointDeletion(j.ObjectNameInScene);
  1769. //m_log.Debug("RemoveAllJointsConnectedToActor: done request deletion of " + j.ObjectNameInScene);
  1770. j.TrackedBodyName = null; // *IMMEDIATELY* prevent any further movement of this joint (else a deleted actor might cause spurious tracking motion of the joint for a few frames, leading to the joint proxy object disappearing)
  1771. }
  1772. }
  1773. }
  1774. public override void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor)
  1775. {
  1776. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: start");
  1777. lock (OdeLock)
  1778. {
  1779. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: got lock");
  1780. RemoveAllJointsConnectedToActor(actor);
  1781. }
  1782. }
  1783. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  1784. public override Vector3 GetJointAnchor(PhysicsJoint joint)
  1785. {
  1786. Debug.Assert(joint.IsInPhysicsEngine);
  1787. d.Vector3 pos = new d.Vector3();
  1788. if (!(joint is OdePhysicsJoint))
  1789. {
  1790. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  1791. }
  1792. else
  1793. {
  1794. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  1795. switch (odeJoint.Type)
  1796. {
  1797. case PhysicsJointType.Ball:
  1798. d.JointGetBallAnchor(odeJoint.jointID, out pos);
  1799. break;
  1800. case PhysicsJointType.Hinge:
  1801. d.JointGetHingeAnchor(odeJoint.jointID, out pos);
  1802. break;
  1803. }
  1804. }
  1805. return new Vector3(pos.X, pos.Y, pos.Z);
  1806. }
  1807. /// <summary>
  1808. /// Get joint axis.
  1809. /// </summary>
  1810. /// <remarks>
  1811. /// normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  1812. /// WARNING: ODE sometimes returns <0,0,0> as the joint axis! Therefore this function
  1813. /// appears to be unreliable. Fortunately we can compute the joint axis ourselves by
  1814. /// keeping track of the joint's original orientation relative to one of the involved bodies.
  1815. /// </remarks>
  1816. /// <param name="joint"></param>
  1817. /// <returns></returns>
  1818. public override Vector3 GetJointAxis(PhysicsJoint joint)
  1819. {
  1820. Debug.Assert(joint.IsInPhysicsEngine);
  1821. d.Vector3 axis = new d.Vector3();
  1822. if (!(joint is OdePhysicsJoint))
  1823. {
  1824. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  1825. }
  1826. else
  1827. {
  1828. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  1829. switch (odeJoint.Type)
  1830. {
  1831. case PhysicsJointType.Ball:
  1832. DoJointErrorMessage(joint, "warning - axis requested for ball joint: " + joint.ObjectNameInScene);
  1833. break;
  1834. case PhysicsJointType.Hinge:
  1835. d.JointGetHingeAxis(odeJoint.jointID, out axis);
  1836. break;
  1837. }
  1838. }
  1839. return new Vector3(axis.X, axis.Y, axis.Z);
  1840. }
  1841. /// <summary>
  1842. /// Stop this prim being subject to physics
  1843. /// </summary>
  1844. /// <param name="prim"></param>
  1845. internal void DeactivatePrim(OdePrim prim)
  1846. {
  1847. _activeprims.Remove(prim);
  1848. }
  1849. public override void RemovePrim(PhysicsActor prim)
  1850. {
  1851. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  1852. // removed in the next physics simulate pass.
  1853. if (prim is OdePrim)
  1854. {
  1855. lock (OdeLock)
  1856. {
  1857. OdePrim p = (OdePrim) prim;
  1858. p.setPrimForRemoval();
  1859. AddPhysicsActorTaint(prim);
  1860. }
  1861. }
  1862. }
  1863. /// <summary>
  1864. /// This is called from within simulate but outside the locked portion
  1865. /// We need to do our own locking here
  1866. /// (Note: As of 20110801 this no longer appears to be true - this is being called within lock (odeLock) in
  1867. /// Simulate() -- justincc).
  1868. ///
  1869. /// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
  1870. ///
  1871. /// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
  1872. /// that the space was using.
  1873. /// </summary>
  1874. /// <param name="prim"></param>
  1875. internal void RemovePrimThreadLocked(OdePrim prim)
  1876. {
  1877. // m_log.DebugFormat("[ODE SCENE]: Removing physical prim {0} {1}", prim.Name, prim.LocalID);
  1878. lock (prim)
  1879. {
  1880. RemoveCollisionEventReporting(prim);
  1881. if (prim.prim_geom != IntPtr.Zero)
  1882. {
  1883. prim.ResetTaints();
  1884. if (prim.IsPhysical)
  1885. {
  1886. prim.disableBody();
  1887. if (prim.childPrim)
  1888. {
  1889. prim.childPrim = false;
  1890. prim.Body = IntPtr.Zero;
  1891. prim.m_disabled = true;
  1892. prim.IsPhysical = false;
  1893. }
  1894. }
  1895. prim.m_targetSpace = IntPtr.Zero;
  1896. if (!prim.RemoveGeom())
  1897. m_log.Warn("[ODE SCENE]: Unable to remove prim from physics scene");
  1898. lock (_prims)
  1899. _prims.Remove(prim);
  1900. if (SupportsNINJAJoints)
  1901. RemoveAllJointsConnectedToActorThreadLocked(prim);
  1902. }
  1903. }
  1904. }
  1905. #endregion
  1906. #region Space Separation Calculation
  1907. /// <summary>
  1908. /// Takes a space pointer and zeros out the array we're using to hold the spaces
  1909. /// </summary>
  1910. /// <param name="pSpace"></param>
  1911. private void resetSpaceArrayItemToZero(IntPtr pSpace)
  1912. {
  1913. for (int x = 0; x < staticPrimspace.GetLength(0); x++)
  1914. {
  1915. for (int y = 0; y < staticPrimspace.GetLength(1); y++)
  1916. {
  1917. if (staticPrimspace[x, y] == pSpace)
  1918. staticPrimspace[x, y] = IntPtr.Zero;
  1919. }
  1920. }
  1921. }
  1922. // private void resetSpaceArrayItemToZero(int arrayitemX, int arrayitemY)
  1923. // {
  1924. // staticPrimspace[arrayitemX, arrayitemY] = IntPtr.Zero;
  1925. // }
  1926. /// <summary>
  1927. /// Called when a static prim moves. Allocates a space for the prim based on its position
  1928. /// </summary>
  1929. /// <param name="geom">the pointer to the geom that moved</param>
  1930. /// <param name="pos">the position that the geom moved to</param>
  1931. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1932. /// <returns>a pointer to the new space it's in</returns>
  1933. internal IntPtr recalculateSpaceForGeom(IntPtr geom, Vector3 pos, IntPtr currentspace)
  1934. {
  1935. // Called from setting the Position and Size of an ODEPrim so
  1936. // it's already in locked space.
  1937. // we don't want to remove the main space
  1938. // we don't need to test physical here because this function should
  1939. // never be called if the prim is physical(active)
  1940. // All physical prim end up in the root space
  1941. //Thread.Sleep(20);
  1942. if (currentspace != space)
  1943. {
  1944. //m_log.Info("[SPACE]: C:" + currentspace.ToString() + " g:" + geom.ToString());
  1945. //if (currentspace == IntPtr.Zero)
  1946. //{
  1947. //int adfadf = 0;
  1948. //}
  1949. if (d.SpaceQuery(currentspace, geom) && currentspace != IntPtr.Zero)
  1950. {
  1951. if (d.GeomIsSpace(currentspace))
  1952. {
  1953. // waitForSpaceUnlock(currentspace);
  1954. d.SpaceRemove(currentspace, geom);
  1955. }
  1956. else
  1957. {
  1958. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" + currentspace +
  1959. " Geom:" + geom);
  1960. }
  1961. }
  1962. else
  1963. {
  1964. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  1965. if (sGeomIsIn != IntPtr.Zero)
  1966. {
  1967. if (d.GeomIsSpace(currentspace))
  1968. {
  1969. // waitForSpaceUnlock(sGeomIsIn);
  1970. d.SpaceRemove(sGeomIsIn, geom);
  1971. }
  1972. else
  1973. {
  1974. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  1975. sGeomIsIn + " Geom:" + geom);
  1976. }
  1977. }
  1978. }
  1979. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  1980. if (d.SpaceGetNumGeoms(currentspace) == 0)
  1981. {
  1982. if (currentspace != IntPtr.Zero)
  1983. {
  1984. if (d.GeomIsSpace(currentspace))
  1985. {
  1986. d.SpaceRemove(space, currentspace);
  1987. // free up memory used by the space.
  1988. resetSpaceArrayItemToZero(currentspace);
  1989. }
  1990. else
  1991. {
  1992. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  1993. currentspace + " Geom:" + geom);
  1994. }
  1995. }
  1996. }
  1997. }
  1998. else
  1999. {
  2000. // this is a physical object that got disabled. ;.;
  2001. if (currentspace != IntPtr.Zero && geom != IntPtr.Zero)
  2002. {
  2003. if (d.SpaceQuery(currentspace, geom))
  2004. {
  2005. if (d.GeomIsSpace(currentspace))
  2006. {
  2007. // waitForSpaceUnlock(currentspace);
  2008. d.SpaceRemove(currentspace, geom);
  2009. }
  2010. else
  2011. {
  2012. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2013. currentspace + " Geom:" + geom);
  2014. }
  2015. }
  2016. else
  2017. {
  2018. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2019. if (sGeomIsIn != IntPtr.Zero)
  2020. {
  2021. if (d.GeomIsSpace(sGeomIsIn))
  2022. {
  2023. // waitForSpaceUnlock(sGeomIsIn);
  2024. d.SpaceRemove(sGeomIsIn, geom);
  2025. }
  2026. else
  2027. {
  2028. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2029. sGeomIsIn + " Geom:" + geom);
  2030. }
  2031. }
  2032. }
  2033. }
  2034. }
  2035. // The routines in the Position and Size sections do the 'inserting' into the space,
  2036. // so all we have to do is make sure that the space that we're putting the prim into
  2037. // is in the 'main' space.
  2038. int[] iprimspaceArrItem = calculateSpaceArrayItemFromPos(pos);
  2039. IntPtr newspace = calculateSpaceForGeom(pos);
  2040. if (newspace == IntPtr.Zero)
  2041. {
  2042. newspace = createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  2043. d.HashSpaceSetLevels(newspace, HashspaceLow, HashspaceHigh);
  2044. }
  2045. return newspace;
  2046. }
  2047. /// <summary>
  2048. /// Creates a new space at X Y
  2049. /// </summary>
  2050. /// <param name="iprimspaceArrItemX"></param>
  2051. /// <param name="iprimspaceArrItemY"></param>
  2052. /// <returns>A pointer to the created space</returns>
  2053. internal IntPtr createprimspace(int iprimspaceArrItemX, int iprimspaceArrItemY)
  2054. {
  2055. // creating a new space for prim and inserting it into main space.
  2056. staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY] = d.HashSpaceCreate(IntPtr.Zero);
  2057. d.GeomSetCategoryBits(staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY], (int)CollisionCategories.Space);
  2058. // waitForSpaceUnlock(space);
  2059. d.SpaceSetSublevel(space, 1);
  2060. d.SpaceAdd(space, staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY]);
  2061. return staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY];
  2062. }
  2063. /// <summary>
  2064. /// Calculates the space the prim should be in by its position
  2065. /// </summary>
  2066. /// <param name="pos"></param>
  2067. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  2068. internal IntPtr calculateSpaceForGeom(Vector3 pos)
  2069. {
  2070. int[] xyspace = calculateSpaceArrayItemFromPos(pos);
  2071. //m_log.Info("[Physics]: Attempting to use arrayItem: " + xyspace[0].ToString() + "," + xyspace[1].ToString());
  2072. return staticPrimspace[xyspace[0], xyspace[1]];
  2073. }
  2074. /// <summary>
  2075. /// Holds the space allocation logic
  2076. /// </summary>
  2077. /// <param name="pos"></param>
  2078. /// <returns>an array item based on the position</returns>
  2079. internal int[] calculateSpaceArrayItemFromPos(Vector3 pos)
  2080. {
  2081. int[] returnint = new int[2];
  2082. returnint[0] = (int) (pos.X * spacesPerMeterX);
  2083. if (returnint[0] > spaceGridMaxX)
  2084. returnint[0] = spaceGridMaxX;
  2085. if (returnint[0] < 0)
  2086. returnint[0] = 0;
  2087. returnint[1] = (int)(pos.Y * spacesPerMeterY);
  2088. if (returnint[1] > spaceGridMaxY)
  2089. returnint[1] = spaceGridMaxY;
  2090. if (returnint[1] < 0)
  2091. returnint[1] = 0;
  2092. return returnint;
  2093. }
  2094. #endregion
  2095. /// <summary>
  2096. /// Routine to figure out if we need to mesh this prim with our mesher
  2097. /// </summary>
  2098. /// <param name="pbs"></param>
  2099. /// <returns></returns>
  2100. internal bool needsMeshing(PrimitiveBaseShape pbs)
  2101. {
  2102. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  2103. // but we still need to check for sculptie meshing being enabled so this is the most
  2104. // convenient place to do it for now...
  2105. // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
  2106. // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
  2107. int iPropertiesNotSupportedDefault = 0;
  2108. if (pbs.SculptEntry && !meshSculptedPrim)
  2109. {
  2110. #if SPAM
  2111. m_log.Warn("NonMesh");
  2112. #endif
  2113. return false;
  2114. }
  2115. // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim
  2116. if (!forceSimplePrimMeshing && !pbs.SculptEntry)
  2117. {
  2118. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  2119. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  2120. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  2121. {
  2122. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  2123. && pbs.ProfileHollow == 0
  2124. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  2125. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  2126. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  2127. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  2128. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  2129. {
  2130. #if SPAM
  2131. m_log.Warn("NonMesh");
  2132. #endif
  2133. return false;
  2134. }
  2135. }
  2136. }
  2137. if (pbs.ProfileHollow != 0)
  2138. iPropertiesNotSupportedDefault++;
  2139. if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
  2140. iPropertiesNotSupportedDefault++;
  2141. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  2142. iPropertiesNotSupportedDefault++;
  2143. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  2144. iPropertiesNotSupportedDefault++;
  2145. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  2146. iPropertiesNotSupportedDefault++;
  2147. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  2148. iPropertiesNotSupportedDefault++;
  2149. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  2150. iPropertiesNotSupportedDefault++;
  2151. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
  2152. iPropertiesNotSupportedDefault++;
  2153. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  2154. iPropertiesNotSupportedDefault++;
  2155. // test for torus
  2156. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  2157. {
  2158. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2159. {
  2160. iPropertiesNotSupportedDefault++;
  2161. }
  2162. }
  2163. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  2164. {
  2165. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2166. {
  2167. iPropertiesNotSupportedDefault++;
  2168. }
  2169. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  2170. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2171. {
  2172. iPropertiesNotSupportedDefault++;
  2173. }
  2174. }
  2175. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  2176. {
  2177. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  2178. {
  2179. iPropertiesNotSupportedDefault++;
  2180. }
  2181. }
  2182. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  2183. {
  2184. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2185. {
  2186. iPropertiesNotSupportedDefault++;
  2187. }
  2188. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2189. {
  2190. iPropertiesNotSupportedDefault++;
  2191. }
  2192. }
  2193. if (pbs.SculptEntry && meshSculptedPrim)
  2194. iPropertiesNotSupportedDefault++;
  2195. if (iPropertiesNotSupportedDefault == 0)
  2196. {
  2197. #if SPAM
  2198. m_log.Warn("NonMesh");
  2199. #endif
  2200. return false;
  2201. }
  2202. #if SPAM
  2203. m_log.Debug("Mesh");
  2204. #endif
  2205. return true;
  2206. }
  2207. /// <summary>
  2208. /// Called after our prim properties are set Scale, position etc.
  2209. /// </summary>
  2210. /// <remarks>
  2211. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  2212. /// This assures us that we have no race conditions
  2213. /// </remarks>
  2214. /// <param name="actor"></param>
  2215. public override void AddPhysicsActorTaint(PhysicsActor actor)
  2216. {
  2217. if (actor is OdePrim)
  2218. {
  2219. OdePrim taintedprim = ((OdePrim)actor);
  2220. lock (_taintedPrims)
  2221. _taintedPrims.Add(taintedprim);
  2222. }
  2223. else if (actor is OdeCharacter)
  2224. {
  2225. OdeCharacter taintedchar = ((OdeCharacter)actor);
  2226. lock (_taintedActors)
  2227. {
  2228. _taintedActors.Add(taintedchar);
  2229. if (taintedchar.bad)
  2230. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
  2231. }
  2232. }
  2233. }
  2234. // does all pending changes generated during region load process
  2235. public override void ProcessPreSimulation()
  2236. {
  2237. lock (OdeLock)
  2238. {
  2239. if (world == IntPtr.Zero)
  2240. {
  2241. _taintedPrims.Clear();;
  2242. return;
  2243. }
  2244. int donechanges = 0;
  2245. if (_taintedPrims.Count > 0)
  2246. {
  2247. m_log.InfoFormat("[Ode] start processing pending actor operations");
  2248. int tstart = Util.EnvironmentTickCount();
  2249. d.AllocateODEDataForThread(0);
  2250. lock (_taintedPrims)
  2251. {
  2252. foreach (OdePrim prim in _taintedPrims)
  2253. {
  2254. if (prim.m_taintremove)
  2255. RemovePrimThreadLocked(prim);
  2256. else
  2257. prim.ProcessTaints();
  2258. prim.m_collisionscore = 0;
  2259. donechanges++;
  2260. }
  2261. _taintedPrims.Clear();
  2262. }
  2263. int time = Util.EnvironmentTickCountSubtract(tstart);
  2264. m_log.InfoFormat("[Ode] finished {0} operations in {1}ms", donechanges, time);
  2265. }
  2266. m_log.InfoFormat("[Ode] {0} prim actors loaded",_prims.Count);
  2267. }
  2268. }
  2269. /// <summary>
  2270. /// This is our main simulate loop
  2271. /// </summary>
  2272. /// <remarks>
  2273. /// It's thread locked by a Mutex in the scene.
  2274. /// It holds Collisions, it instructs ODE to step through the physical reactions
  2275. /// It moves the objects around in memory
  2276. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  2277. /// </remarks>
  2278. /// <param name="timeStep"></param>
  2279. /// <returns>The number of frames simulated over that period.</returns>
  2280. public override float Simulate(float timeStep)
  2281. {
  2282. if (!_worldInitialized)
  2283. return 1.0f;
  2284. int startFrameTick = CollectStats ? Util.EnvironmentTickCount() : 0;
  2285. int tempTick = 0, tempTick2 = 0;
  2286. if (framecount >= int.MaxValue)
  2287. framecount = 0;
  2288. framecount++;
  2289. float fps = 0;
  2290. step_time += timeStep;
  2291. float HalfOdeStep = ODE_STEPSIZE * 0.5f;
  2292. if (step_time < HalfOdeStep)
  2293. return 0;
  2294. // We change _collisionEventPrimChanges to avoid locking _collisionEventPrim itself and causing potential
  2295. // deadlock if the collision event tries to lock something else later on which is already locked by a
  2296. // caller that is adding or removing the collision event.
  2297. lock (m_collisionEventActorsChanges)
  2298. {
  2299. foreach (KeyValuePair<uint, PhysicsActor> kvp in m_collisionEventActorsChanges)
  2300. {
  2301. if (kvp.Value == null)
  2302. m_collisionEventActors.Remove(kvp.Key);
  2303. else
  2304. m_collisionEventActors[kvp.Key] = kvp.Value;
  2305. }
  2306. m_collisionEventActorsChanges.Clear();
  2307. }
  2308. if (SupportsNINJAJoints)
  2309. {
  2310. DeleteRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2311. CreateRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2312. }
  2313. lock (OdeLock)
  2314. {
  2315. d.AllocateODEDataForThread(~0U);
  2316. while (step_time > HalfOdeStep)
  2317. {
  2318. try
  2319. {
  2320. if (CollectStats)
  2321. tempTick = Util.EnvironmentTickCount();
  2322. lock (_taintedActors)
  2323. {
  2324. foreach (OdeCharacter character in _taintedActors)
  2325. character.ProcessTaints();
  2326. _taintedActors.Clear();
  2327. }
  2328. if (CollectStats)
  2329. {
  2330. tempTick2 = Util.EnvironmentTickCount();
  2331. m_stats[ODEAvatarTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2332. tempTick = tempTick2;
  2333. }
  2334. lock (_taintedPrims)
  2335. {
  2336. foreach (OdePrim prim in _taintedPrims)
  2337. {
  2338. if (prim.m_taintremove)
  2339. {
  2340. // Console.WriteLine("Simulate calls RemovePrimThreadLocked for {0}", prim.Name);
  2341. RemovePrimThreadLocked(prim);
  2342. }
  2343. else
  2344. {
  2345. // Console.WriteLine("Simulate calls ProcessTaints for {0}", prim.Name);
  2346. prim.ProcessTaints();
  2347. }
  2348. prim.m_collisionscore = 0;
  2349. // This loop can block up the Heartbeat for a very long time on large regions.
  2350. // We need to let the Watchdog know that the Heartbeat is not dead
  2351. // NOTE: This is currently commented out, but if things like OAR loading are
  2352. // timing the heartbeat out we will need to uncomment it
  2353. //Watchdog.UpdateThread();
  2354. }
  2355. if (SupportsNINJAJoints)
  2356. SimulatePendingNINJAJoints();
  2357. _taintedPrims.Clear();
  2358. }
  2359. if (CollectStats)
  2360. {
  2361. tempTick2 = Util.EnvironmentTickCount();
  2362. m_stats[ODEPrimTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2363. tempTick = tempTick2;
  2364. }
  2365. // Move characters
  2366. foreach (OdeCharacter actor in _characters)
  2367. actor.Move(defects);
  2368. if (defects.Count != 0)
  2369. {
  2370. foreach (OdeCharacter actor in defects)
  2371. {
  2372. m_log.ErrorFormat(
  2373. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when moving",
  2374. actor.Name, actor.LocalID, PhysicsSceneName);
  2375. RemoveCharacter(actor);
  2376. actor.DestroyOdeStructures();
  2377. }
  2378. defects.Clear();
  2379. }
  2380. if (CollectStats)
  2381. {
  2382. tempTick2 = Util.EnvironmentTickCount();
  2383. m_stats[ODEAvatarForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2384. tempTick = tempTick2;
  2385. }
  2386. // Move other active objects
  2387. foreach (OdePrim prim in _activeprims)
  2388. {
  2389. prim.m_collisionscore = 0;
  2390. prim.Move(timeStep);
  2391. }
  2392. if (CollectStats)
  2393. {
  2394. tempTick2 = Util.EnvironmentTickCount();
  2395. m_stats[ODEPrimForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2396. tempTick = tempTick2;
  2397. }
  2398. m_rayCastManager.ProcessQueuedRequests();
  2399. if (CollectStats)
  2400. {
  2401. tempTick2 = Util.EnvironmentTickCount();
  2402. m_stats[ODERaycastingFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2403. tempTick = tempTick2;
  2404. }
  2405. collision_optimized();
  2406. if (CollectStats)
  2407. {
  2408. tempTick2 = Util.EnvironmentTickCount();
  2409. m_stats[ODEOtherCollisionFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2410. tempTick = tempTick2;
  2411. }
  2412. foreach (PhysicsActor obj in m_collisionEventActors.Values)
  2413. {
  2414. // m_log.DebugFormat("[PHYSICS]: Assessing {0} {1} for collision events", obj.SOPName, obj.LocalID);
  2415. switch ((ActorTypes)obj.PhysicsActorType)
  2416. {
  2417. case ActorTypes.Agent:
  2418. OdeCharacter cobj = (OdeCharacter)obj;
  2419. cobj.AddCollisionFrameTime(100);
  2420. cobj.SendCollisions();
  2421. break;
  2422. case ActorTypes.Prim:
  2423. OdePrim pobj = (OdePrim)obj;
  2424. pobj.SendCollisions();
  2425. break;
  2426. }
  2427. }
  2428. // if (m_global_contactcount > 0)
  2429. // m_log.DebugFormat(
  2430. // "[PHYSICS]: Collision contacts to process this frame = {0}", m_global_contactcount);
  2431. m_global_contactcount = 0;
  2432. if (CollectStats)
  2433. {
  2434. tempTick2 = Util.EnvironmentTickCount();
  2435. m_stats[ODECollisionNotificationFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2436. tempTick = tempTick2;
  2437. }
  2438. lock(SimulationLock)
  2439. d.WorldQuickStep(world, ODE_STEPSIZE);
  2440. if (CollectStats)
  2441. m_stats[ODENativeStepFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2442. d.JointGroupEmpty(contactgroup);
  2443. }
  2444. catch (Exception e)
  2445. {
  2446. m_log.ErrorFormat("[ODE SCENE]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  2447. }
  2448. step_time -= ODE_STEPSIZE;
  2449. fps += ODE_STEPSIZE;
  2450. }
  2451. if (CollectStats)
  2452. tempTick = Util.EnvironmentTickCount();
  2453. foreach (OdeCharacter actor in _characters)
  2454. {
  2455. if (actor.bad)
  2456. m_log.ErrorFormat("[ODE SCENE]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  2457. actor.UpdatePositionAndVelocity(defects);
  2458. }
  2459. if (defects.Count != 0)
  2460. {
  2461. foreach (OdeCharacter actor in defects)
  2462. {
  2463. m_log.ErrorFormat(
  2464. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when updating position and velocity",
  2465. actor.Name, actor.LocalID, PhysicsSceneName);
  2466. RemoveCharacter(actor);
  2467. actor.DestroyOdeStructures();
  2468. }
  2469. defects.Clear();
  2470. }
  2471. if (CollectStats)
  2472. {
  2473. tempTick2 = Util.EnvironmentTickCount();
  2474. m_stats[ODEAvatarUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2475. tempTick = tempTick2;
  2476. }
  2477. //if (timeStep < 0.2f)
  2478. foreach (OdePrim prim in _activeprims)
  2479. {
  2480. if (prim.IsPhysical && (d.BodyIsEnabled(prim.Body) || !prim._zeroFlag))
  2481. {
  2482. prim.UpdatePositionAndVelocity();
  2483. if (SupportsNINJAJoints)
  2484. SimulateActorPendingJoints(prim);
  2485. }
  2486. }
  2487. if (CollectStats)
  2488. m_stats[ODEPrimUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2489. //DumpJointInfo();
  2490. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  2491. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  2492. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  2493. if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
  2494. {
  2495. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  2496. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  2497. if (physics_logging_append_existing_logfile)
  2498. {
  2499. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  2500. TextWriter fwriter = File.AppendText(fname);
  2501. fwriter.WriteLine(header);
  2502. fwriter.Close();
  2503. }
  2504. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  2505. }
  2506. latertickcount = Util.EnvironmentTickCountSubtract(tickCountFrameRun);
  2507. // OpenSimulator above does 10 fps. 10 fps = means that the main thread loop and physics
  2508. // has a max of 100 ms to run theoretically.
  2509. // If the main loop stalls, it calls Simulate later which makes the tick count ms larger.
  2510. // If Physics stalls, it takes longer which makes the tick count ms larger.
  2511. if (latertickcount < 100)
  2512. {
  2513. m_timeDilation = 1.0f;
  2514. }
  2515. else
  2516. {
  2517. m_timeDilation = 100f / latertickcount;
  2518. //m_timeDilation = Math.Min((Math.Max(100 - (Util.EnvironmentTickCount() - tickCountFrameRun), 1) / 100f), 1.0f);
  2519. }
  2520. tickCountFrameRun = Util.EnvironmentTickCount();
  2521. if (CollectStats)
  2522. m_stats[ODETotalFrameMsStatName] += Util.EnvironmentTickCountSubtract(startFrameTick);
  2523. }
  2524. fps *= 1.0f/timeStep;
  2525. return fps;
  2526. }
  2527. /// <summary>
  2528. /// Simulate pending NINJA joints.
  2529. /// </summary>
  2530. /// <remarks>
  2531. /// Called by the main Simulate() loop if NINJA joints are active. Should not be called from anywhere else.
  2532. /// </remarks>
  2533. private void SimulatePendingNINJAJoints()
  2534. {
  2535. // Create pending joints, if possible
  2536. // joints can only be processed after ALL bodies are processed (and exist in ODE), since creating
  2537. // a joint requires specifying the body id of both involved bodies
  2538. if (pendingJoints.Count > 0)
  2539. {
  2540. List<PhysicsJoint> successfullyProcessedPendingJoints = new List<PhysicsJoint>();
  2541. //DoJointErrorMessage(joints_connecting_actor, "taint: " + pendingJoints.Count + " pending joints");
  2542. foreach (PhysicsJoint joint in pendingJoints)
  2543. {
  2544. //DoJointErrorMessage(joint, "taint: time to create joint with parms: " + joint.RawParams);
  2545. string[] jointParams = joint.RawParams.Split(" ".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
  2546. List<IntPtr> jointBodies = new List<IntPtr>();
  2547. bool allJointBodiesAreReady = true;
  2548. foreach (string jointParam in jointParams)
  2549. {
  2550. if (jointParam == "NULL")
  2551. {
  2552. //DoJointErrorMessage(joint, "attaching NULL joint to world");
  2553. jointBodies.Add(IntPtr.Zero);
  2554. }
  2555. else
  2556. {
  2557. //DoJointErrorMessage(joint, "looking for prim name: " + jointParam);
  2558. bool foundPrim = false;
  2559. lock (_prims)
  2560. {
  2561. foreach (OdePrim prim in _prims) // FIXME: inefficient
  2562. {
  2563. if (prim.SOPName == jointParam)
  2564. {
  2565. //DoJointErrorMessage(joint, "found for prim name: " + jointParam);
  2566. if (prim.IsPhysical && prim.Body != IntPtr.Zero)
  2567. {
  2568. jointBodies.Add(prim.Body);
  2569. foundPrim = true;
  2570. break;
  2571. }
  2572. else
  2573. {
  2574. DoJointErrorMessage(joint, "prim name " + jointParam +
  2575. " exists but is not (yet) physical; deferring joint creation. " +
  2576. "IsPhysical property is " + prim.IsPhysical +
  2577. " and body is " + prim.Body);
  2578. foundPrim = false;
  2579. break;
  2580. }
  2581. }
  2582. }
  2583. }
  2584. if (foundPrim)
  2585. {
  2586. // all is fine
  2587. }
  2588. else
  2589. {
  2590. allJointBodiesAreReady = false;
  2591. break;
  2592. }
  2593. }
  2594. }
  2595. if (allJointBodiesAreReady)
  2596. {
  2597. //DoJointErrorMessage(joint, "allJointBodiesAreReady for " + joint.ObjectNameInScene + " with parms " + joint.RawParams);
  2598. if (jointBodies[0] == jointBodies[1])
  2599. {
  2600. DoJointErrorMessage(joint, "ERROR: joint cannot be created; the joint bodies are the same, body1==body2. Raw body is " + jointBodies[0] + ". raw parms: " + joint.RawParams);
  2601. }
  2602. else
  2603. {
  2604. switch (joint.Type)
  2605. {
  2606. case PhysicsJointType.Ball:
  2607. {
  2608. IntPtr odeJoint;
  2609. //DoJointErrorMessage(joint, "ODE creating ball joint ");
  2610. odeJoint = d.JointCreateBall(world, IntPtr.Zero);
  2611. //DoJointErrorMessage(joint, "ODE attaching ball joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2612. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2613. //DoJointErrorMessage(joint, "ODE setting ball anchor: " + odeJoint + " to vec:" + joint.Position);
  2614. d.JointSetBallAnchor(odeJoint,
  2615. joint.Position.X,
  2616. joint.Position.Y,
  2617. joint.Position.Z);
  2618. //DoJointErrorMessage(joint, "ODE joint setting OK");
  2619. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b0: ");
  2620. //DoJointErrorMessage(joint, "" + (jointBodies[0] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[0]) : "fixed environment"));
  2621. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b1: ");
  2622. //DoJointErrorMessage(joint, "" + (jointBodies[1] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[1]) : "fixed environment"));
  2623. if (joint is OdePhysicsJoint)
  2624. {
  2625. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2626. }
  2627. else
  2628. {
  2629. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2630. }
  2631. }
  2632. break;
  2633. case PhysicsJointType.Hinge:
  2634. {
  2635. IntPtr odeJoint;
  2636. //DoJointErrorMessage(joint, "ODE creating hinge joint ");
  2637. odeJoint = d.JointCreateHinge(world, IntPtr.Zero);
  2638. //DoJointErrorMessage(joint, "ODE attaching hinge joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2639. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2640. //DoJointErrorMessage(joint, "ODE setting hinge anchor: " + odeJoint + " to vec:" + joint.Position);
  2641. d.JointSetHingeAnchor(odeJoint,
  2642. joint.Position.X,
  2643. joint.Position.Y,
  2644. joint.Position.Z);
  2645. // We use the orientation of the x-axis of the joint's coordinate frame
  2646. // as the axis for the hinge.
  2647. // Therefore, we must get the joint's coordinate frame based on the
  2648. // joint.Rotation field, which originates from the orientation of the
  2649. // joint's proxy object in the scene.
  2650. // The joint's coordinate frame is defined as the transformation matrix
  2651. // that converts a vector from joint-local coordinates into world coordinates.
  2652. // World coordinates are defined as the XYZ coordinate system of the sim,
  2653. // as shown in the top status-bar of the viewer.
  2654. // Once we have the joint's coordinate frame, we extract its X axis (AtAxis)
  2655. // and use that as the hinge axis.
  2656. //joint.Rotation.Normalize();
  2657. Matrix4 proxyFrame = Matrix4.CreateFromQuaternion(joint.Rotation);
  2658. // Now extract the X axis of the joint's coordinate frame.
  2659. // Do not try to use proxyFrame.AtAxis or you will become mired in the
  2660. // tar pit of transposed, inverted, and generally messed-up orientations.
  2661. // (In other words, Matrix4.AtAxis() is borked.)
  2662. // Vector3 jointAxis = proxyFrame.AtAxis; <--- this path leadeth to madness
  2663. // Instead, compute the X axis of the coordinate frame by transforming
  2664. // the (1,0,0) vector. At least that works.
  2665. //m_log.Debug("PHY: making axis: complete matrix is " + proxyFrame);
  2666. Vector3 jointAxis = Vector3.Transform(Vector3.UnitX, proxyFrame);
  2667. //m_log.Debug("PHY: making axis: hinge joint axis is " + jointAxis);
  2668. //DoJointErrorMessage(joint, "ODE setting hinge axis: " + odeJoint + " to vec:" + jointAxis);
  2669. d.JointSetHingeAxis(odeJoint,
  2670. jointAxis.X,
  2671. jointAxis.Y,
  2672. jointAxis.Z);
  2673. //d.JointSetHingeParam(odeJoint, (int)dParam.CFM, 0.1f);
  2674. if (joint is OdePhysicsJoint)
  2675. {
  2676. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2677. }
  2678. else
  2679. {
  2680. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  2681. }
  2682. }
  2683. break;
  2684. }
  2685. successfullyProcessedPendingJoints.Add(joint);
  2686. }
  2687. }
  2688. else
  2689. {
  2690. DoJointErrorMessage(joint, "joint could not yet be created; still pending");
  2691. }
  2692. }
  2693. foreach (PhysicsJoint successfullyProcessedJoint in successfullyProcessedPendingJoints)
  2694. {
  2695. //DoJointErrorMessage(successfullyProcessedJoint, "finalizing succesfully procsssed joint " + successfullyProcessedJoint.ObjectNameInScene + " parms " + successfullyProcessedJoint.RawParams);
  2696. //DoJointErrorMessage(successfullyProcessedJoint, "removing from pending");
  2697. InternalRemovePendingJoint(successfullyProcessedJoint);
  2698. //DoJointErrorMessage(successfullyProcessedJoint, "adding to active");
  2699. InternalAddActiveJoint(successfullyProcessedJoint);
  2700. //DoJointErrorMessage(successfullyProcessedJoint, "done");
  2701. }
  2702. }
  2703. }
  2704. /// <summary>
  2705. /// Simulate the joint proxies of a NINJA actor.
  2706. /// </summary>
  2707. /// <remarks>
  2708. /// Called as part of the Simulate() loop if NINJA physics is active. Must only be called from there.
  2709. /// </remarks>
  2710. /// <param name="actor"></param>
  2711. private void SimulateActorPendingJoints(OdePrim actor)
  2712. {
  2713. // If an actor moved, move its joint proxy objects as well.
  2714. // There seems to be an event PhysicsActor.OnPositionUpdate that could be used
  2715. // for this purpose but it is never called! So we just do the joint
  2716. // movement code here.
  2717. if (actor.SOPName != null &&
  2718. joints_connecting_actor.ContainsKey(actor.SOPName) &&
  2719. joints_connecting_actor[actor.SOPName] != null &&
  2720. joints_connecting_actor[actor.SOPName].Count > 0)
  2721. {
  2722. foreach (PhysicsJoint affectedJoint in joints_connecting_actor[actor.SOPName])
  2723. {
  2724. if (affectedJoint.IsInPhysicsEngine)
  2725. {
  2726. DoJointMoved(affectedJoint);
  2727. }
  2728. else
  2729. {
  2730. DoJointErrorMessage(affectedJoint, "a body connected to a joint was moved, but the joint doesn't exist yet! this will lead to joint error. joint was: " + affectedJoint.ObjectNameInScene + " parms:" + affectedJoint.RawParams);
  2731. }
  2732. }
  2733. }
  2734. }
  2735. public override void GetResults()
  2736. {
  2737. }
  2738. public override bool IsThreaded
  2739. {
  2740. // for now we won't be multithreaded
  2741. get { return false; }
  2742. }
  2743. public override void SetTerrain(float[] heightMap)
  2744. {
  2745. if (m_worldOffset != Vector3.Zero && m_parentScene != null)
  2746. {
  2747. if (m_parentScene is OdeScene)
  2748. {
  2749. ((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
  2750. }
  2751. }
  2752. else
  2753. {
  2754. SetTerrain(heightMap, m_worldOffset);
  2755. }
  2756. }
  2757. private void SetTerrain(float[] heightMap, Vector3 pOffset)
  2758. {
  2759. int startTime = Util.EnvironmentTickCount();
  2760. m_log.DebugFormat("[ODE SCENE]: Setting terrain for {0} with offset {1}", PhysicsSceneName, pOffset);
  2761. float[] _heightmap;
  2762. // ok im lasy this are just a aliases
  2763. uint regionsizeX = m_regionWidth;
  2764. uint regionsizeY = m_regionHeight;
  2765. // map is rotated
  2766. uint heightmapWidth = regionsizeY + 2;
  2767. uint heightmapHeight = regionsizeX + 2;
  2768. uint heightmapWidthSamples = heightmapWidth + 1;
  2769. uint heightmapHeightSamples = heightmapHeight + 1;
  2770. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  2771. const float scale = 1.0f;
  2772. const float offset = 0.0f;
  2773. const float thickness = 10f;
  2774. const int wrap = 0;
  2775. float hfmin = float.MaxValue;
  2776. float hfmax = float.MinValue;
  2777. float val;
  2778. uint xx;
  2779. uint yy;
  2780. uint maxXX = regionsizeX - 1;
  2781. uint maxYY = regionsizeY - 1;
  2782. // flipping map adding one margin all around so things don't fall in edges
  2783. uint xt = 0;
  2784. xx = 0;
  2785. for (uint x = 0; x < heightmapWidthSamples; x++)
  2786. {
  2787. if (x > 1 && xx < maxXX)
  2788. xx++;
  2789. yy = 0;
  2790. for (uint y = 0; y < heightmapHeightSamples; y++)
  2791. {
  2792. if (y > 1 && y < maxYY)
  2793. yy += regionsizeX;
  2794. val = heightMap[yy + xx];
  2795. if (val < 0.0f)
  2796. val = 0.0f;
  2797. _heightmap[xt + y] = val;
  2798. if (hfmin > val)
  2799. hfmin = val;
  2800. if (hfmax < val)
  2801. hfmax = val;
  2802. }
  2803. xt += heightmapHeightSamples;
  2804. }
  2805. lock (OdeLock)
  2806. {
  2807. d.AllocateODEDataForThread(~0U);
  2808. IntPtr GroundGeom = IntPtr.Zero;
  2809. if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
  2810. {
  2811. RegionTerrain.Remove(pOffset);
  2812. if (GroundGeom != IntPtr.Zero)
  2813. {
  2814. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  2815. {
  2816. TerrainHeightFieldHeights.Remove(GroundGeom);
  2817. }
  2818. d.SpaceRemove(space, GroundGeom);
  2819. d.GeomDestroy(GroundGeom);
  2820. }
  2821. }
  2822. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  2823. d.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmap, 0,
  2824. heightmapWidth, heightmapHeight,
  2825. (int)heightmapWidthSamples,
  2826. (int)heightmapHeightSamples,
  2827. scale, offset, thickness, wrap);
  2828. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  2829. GroundGeom = d.CreateHeightfield(space, HeightmapData, 1);
  2830. if (GroundGeom != IntPtr.Zero)
  2831. {
  2832. d.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
  2833. d.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
  2834. }
  2835. geom_name_map[GroundGeom] = "Terrain";
  2836. d.Matrix3 R = new d.Matrix3();
  2837. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  2838. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  2839. q1 = q1 * q2;
  2840. Vector3 v3;
  2841. float angle;
  2842. q1.GetAxisAngle(out v3, out angle);
  2843. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  2844. d.GeomSetRotation(GroundGeom, ref R);
  2845. d.GeomSetPosition(GroundGeom, pOffset.X + regionsizeX * 0.5f, pOffset.Y + regionsizeY * 0.5f, 0.0f);
  2846. IntPtr testGround = IntPtr.Zero;
  2847. if (RegionTerrain.TryGetValue(pOffset, out testGround))
  2848. {
  2849. RegionTerrain.Remove(pOffset);
  2850. }
  2851. RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
  2852. TerrainHeightFieldHeights.Add(GroundGeom,_heightmap);
  2853. }
  2854. m_log.DebugFormat(
  2855. "[ODE SCENE]: Setting terrain for {0} took {1}ms", PhysicsSceneName, Util.EnvironmentTickCountSubtract(startTime));
  2856. }
  2857. public override void DeleteTerrain()
  2858. {
  2859. }
  2860. internal float GetWaterLevel()
  2861. {
  2862. return waterlevel;
  2863. }
  2864. public override void SetWaterLevel(float baseheight)
  2865. {
  2866. waterlevel = baseheight;
  2867. }
  2868. [HandleProcessCorruptedStateExceptions]
  2869. public override void Dispose()
  2870. {
  2871. lock(SimulationLock)
  2872. lock(OdeLock)
  2873. {
  2874. if(world == IntPtr.Zero)
  2875. return;
  2876. _worldInitialized = false;
  2877. d.AllocateODEDataForThread(~0U);
  2878. if (m_rayCastManager != null)
  2879. {
  2880. m_rayCastManager.Dispose();
  2881. m_rayCastManager = null;
  2882. }
  2883. lock (_prims)
  2884. {
  2885. foreach (OdePrim prm in _prims)
  2886. {
  2887. RemovePrim(prm);
  2888. }
  2889. }
  2890. //foreach (OdeCharacter act in _characters)
  2891. //{
  2892. //RemoveAvatar(act);
  2893. //}
  2894. IntPtr GroundGeom = IntPtr.Zero;
  2895. if (RegionTerrain.TryGetValue(m_worldOffset, out GroundGeom))
  2896. {
  2897. RegionTerrain.Remove(m_worldOffset);
  2898. if (GroundGeom != IntPtr.Zero)
  2899. {
  2900. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  2901. TerrainHeightFieldHeights.Remove(GroundGeom);
  2902. d.GeomDestroy(GroundGeom);
  2903. }
  2904. }
  2905. try
  2906. {
  2907. d.WorldDestroy(world);
  2908. world = IntPtr.Zero;
  2909. }
  2910. catch (AccessViolationException e)
  2911. {
  2912. m_log.ErrorFormat("[ODE SCENE]: exception {0}", e.Message);
  2913. }
  2914. }
  2915. }
  2916. private int compareByCollisionsDesc(OdePrim A, OdePrim B)
  2917. {
  2918. return -A.CollisionScore.CompareTo(B.CollisionScore);
  2919. }
  2920. public override Dictionary<uint, float> GetTopColliders()
  2921. {
  2922. Dictionary<uint, float> topColliders;
  2923. lock (_prims)
  2924. {
  2925. List<OdePrim> orderedPrims = new List<OdePrim>(_prims);
  2926. orderedPrims.Sort(compareByCollisionsDesc);
  2927. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  2928. foreach (OdePrim p in _prims)
  2929. p.CollisionScore = 0;
  2930. }
  2931. return topColliders;
  2932. }
  2933. public override bool SupportsRayCast()
  2934. {
  2935. return true;
  2936. }
  2937. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  2938. {
  2939. if (retMethod != null)
  2940. {
  2941. m_rayCastManager.QueueRequest(position, direction, length, retMethod);
  2942. }
  2943. }
  2944. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  2945. {
  2946. if (retMethod != null)
  2947. {
  2948. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  2949. }
  2950. }
  2951. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  2952. {
  2953. ContactResult[] ourResults = null;
  2954. RayCallback retMethod = delegate(List<ContactResult> results)
  2955. {
  2956. ourResults = new ContactResult[results.Count];
  2957. results.CopyTo(ourResults, 0);
  2958. };
  2959. int waitTime = 0;
  2960. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  2961. while (ourResults == null && waitTime < 1000)
  2962. {
  2963. Thread.Sleep(1);
  2964. waitTime++;
  2965. }
  2966. if (ourResults == null)
  2967. return new List<ContactResult> ();
  2968. return new List<ContactResult>(ourResults);
  2969. }
  2970. public override Dictionary<string, float> GetStats()
  2971. {
  2972. if (!CollectStats)
  2973. return null;
  2974. Dictionary<string, float> returnStats;
  2975. lock (OdeLock)
  2976. {
  2977. returnStats = new Dictionary<string, float>(m_stats);
  2978. // FIXME: This is a SUPER DUMB HACK until we can establish stats that aren't subject to a division by
  2979. // 3 from the SimStatsReporter.
  2980. returnStats[ODETotalAvatarsStatName] = _characters.Count * 3;
  2981. returnStats[ODETotalPrimsStatName] = _prims.Count * 3;
  2982. returnStats[ODEActivePrimsStatName] = _activeprims.Count * 3;
  2983. InitializeExtraStats();
  2984. }
  2985. returnStats[ODEOtherCollisionFrameMsStatName]
  2986. = returnStats[ODEOtherCollisionFrameMsStatName]
  2987. - returnStats[ODENativeSpaceCollisionFrameMsStatName]
  2988. - returnStats[ODENativeGeomCollisionFrameMsStatName];
  2989. return returnStats;
  2990. }
  2991. private void InitializeExtraStats()
  2992. {
  2993. m_stats[ODETotalFrameMsStatName] = 0;
  2994. m_stats[ODEAvatarTaintMsStatName] = 0;
  2995. m_stats[ODEPrimTaintMsStatName] = 0;
  2996. m_stats[ODEAvatarForcesFrameMsStatName] = 0;
  2997. m_stats[ODEPrimForcesFrameMsStatName] = 0;
  2998. m_stats[ODERaycastingFrameMsStatName] = 0;
  2999. m_stats[ODENativeStepFrameMsStatName] = 0;
  3000. m_stats[ODENativeSpaceCollisionFrameMsStatName] = 0;
  3001. m_stats[ODENativeGeomCollisionFrameMsStatName] = 0;
  3002. m_stats[ODEOtherCollisionFrameMsStatName] = 0;
  3003. m_stats[ODECollisionNotificationFrameMsStatName] = 0;
  3004. m_stats[ODEAvatarContactsStatsName] = 0;
  3005. m_stats[ODEPrimContactsStatName] = 0;
  3006. m_stats[ODEAvatarUpdateFrameMsStatName] = 0;
  3007. m_stats[ODEPrimUpdateFrameMsStatName] = 0;
  3008. }
  3009. }
  3010. }