1
0

OdeScene.cs 154 KB

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