ODERayCastRequestManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using System.Runtime.InteropServices;
  31. using System.Text;
  32. using OpenMetaverse;
  33. using OpenSim.Region.PhysicsModules.SharedBase;
  34. using Ode.NET;
  35. using log4net;
  36. namespace OpenSim.Region.PhysicsModule.ODE
  37. {
  38. /// <summary>
  39. /// Processes raycast requests as ODE is in a state to be able to do them.
  40. /// This ensures that it's thread safe and there will be no conflicts.
  41. /// Requests get returned by a different thread then they were requested by.
  42. /// </summary>
  43. public class ODERayCastRequestManager
  44. {
  45. /// <summary>
  46. /// Pending raycast requests
  47. /// </summary>
  48. protected List<ODERayCastRequest> m_PendingRequests = new List<ODERayCastRequest>();
  49. /// <summary>
  50. /// Pending ray requests
  51. /// </summary>
  52. protected List<ODERayRequest> m_PendingRayRequests = new List<ODERayRequest>();
  53. /// <summary>
  54. /// Scene that created this object.
  55. /// </summary>
  56. private OdeScene m_scene;
  57. /// <summary>
  58. /// ODE contact array to be filled by the collision testing
  59. /// </summary>
  60. d.ContactGeom[] contacts = new d.ContactGeom[5];
  61. /// <summary>
  62. /// ODE near callback delegate
  63. /// </summary>
  64. private d.NearCallback nearCallback;
  65. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  66. private List<ContactResult> m_contactResults = new List<ContactResult>();
  67. public ODERayCastRequestManager(OdeScene pScene)
  68. {
  69. m_scene = pScene;
  70. nearCallback = near;
  71. }
  72. /// <summary>
  73. /// Queues a raycast
  74. /// </summary>
  75. /// <param name="position">Origin of Ray</param>
  76. /// <param name="direction">Ray normal</param>
  77. /// <param name="length">Ray length</param>
  78. /// <param name="retMethod">Return method to send the results</param>
  79. public void QueueRequest(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  80. {
  81. lock (m_PendingRequests)
  82. {
  83. ODERayCastRequest req = new ODERayCastRequest();
  84. req.callbackMethod = retMethod;
  85. req.length = length;
  86. req.Normal = direction;
  87. req.Origin = position;
  88. m_PendingRequests.Add(req);
  89. }
  90. }
  91. /// <summary>
  92. /// Queues a raycast
  93. /// </summary>
  94. /// <param name="position">Origin of Ray</param>
  95. /// <param name="direction">Ray normal</param>
  96. /// <param name="length">Ray length</param>
  97. /// <param name="count"></param>
  98. /// <param name="retMethod">Return method to send the results</param>
  99. public void QueueRequest(Vector3 position, Vector3 direction, float length, int count, RayCallback retMethod)
  100. {
  101. lock (m_PendingRequests)
  102. {
  103. ODERayRequest req = new ODERayRequest();
  104. req.callbackMethod = retMethod;
  105. req.length = length;
  106. req.Normal = direction;
  107. req.Origin = position;
  108. req.Count = count;
  109. m_PendingRayRequests.Add(req);
  110. }
  111. }
  112. /// <summary>
  113. /// Process all queued raycast requests
  114. /// </summary>
  115. /// <returns>Time in MS the raycasts took to process.</returns>
  116. public int ProcessQueuedRequests()
  117. {
  118. int time = System.Environment.TickCount;
  119. lock (m_PendingRequests)
  120. {
  121. if (m_PendingRequests.Count > 0)
  122. {
  123. ODERayCastRequest[] reqs = m_PendingRequests.ToArray();
  124. for (int i = 0; i < reqs.Length; i++)
  125. {
  126. if (reqs[i].callbackMethod != null) // quick optimization here, don't raycast
  127. RayCast(reqs[i]); // if there isn't anyone to send results
  128. }
  129. m_PendingRequests.Clear();
  130. }
  131. }
  132. lock (m_PendingRayRequests)
  133. {
  134. if (m_PendingRayRequests.Count > 0)
  135. {
  136. ODERayRequest[] reqs = m_PendingRayRequests.ToArray();
  137. for (int i = 0; i < reqs.Length; i++)
  138. {
  139. if (reqs[i].callbackMethod != null) // quick optimization here, don't raycast
  140. RayCast(reqs[i]); // if there isn't anyone to send results
  141. }
  142. m_PendingRayRequests.Clear();
  143. }
  144. }
  145. lock (m_contactResults)
  146. m_contactResults.Clear();
  147. return System.Environment.TickCount - time;
  148. }
  149. /// <summary>
  150. /// Method that actually initiates the raycast
  151. /// </summary>
  152. /// <param name="req"></param>
  153. private void RayCast(ODERayCastRequest req)
  154. {
  155. // NOTE: limit ray length or collisions will take all avaiable stack space
  156. // this value may still be too large, depending on machine configuration
  157. // of maximum stack
  158. float len = req.length;
  159. if (len > 250f)
  160. len = 250f;
  161. // Create the ray
  162. IntPtr ray = d.CreateRay(m_scene.space, req.length);
  163. d.GeomRaySet(ray, req.Origin.X, req.Origin.Y, req.Origin.Z, req.Normal.X, req.Normal.Y, req.Normal.Z);
  164. // Collide test
  165. d.SpaceCollide2(m_scene.space, ray, IntPtr.Zero, nearCallback);
  166. // Remove Ray
  167. d.GeomDestroy(ray);
  168. // Define default results
  169. bool hitYN = false;
  170. uint hitConsumerID = 0;
  171. float distance = 999999999999f;
  172. Vector3 closestcontact = new Vector3(99999f, 99999f, 99999f);
  173. Vector3 snormal = Vector3.Zero;
  174. // Find closest contact and object.
  175. lock (m_contactResults)
  176. {
  177. foreach (ContactResult cResult in m_contactResults)
  178. {
  179. if (Vector3.Distance(req.Origin, cResult.Pos) < Vector3.Distance(req.Origin, closestcontact))
  180. {
  181. closestcontact = cResult.Pos;
  182. hitConsumerID = cResult.ConsumerID;
  183. distance = cResult.Depth;
  184. hitYN = true;
  185. snormal = cResult.Normal;
  186. }
  187. }
  188. m_contactResults.Clear();
  189. }
  190. // Return results
  191. if (req.callbackMethod != null)
  192. req.callbackMethod(hitYN, closestcontact, hitConsumerID, distance, snormal);
  193. }
  194. /// <summary>
  195. /// Method that actually initiates the raycast
  196. /// </summary>
  197. /// <param name="req"></param>
  198. private void RayCast(ODERayRequest req)
  199. {
  200. // Create the ray
  201. IntPtr ray = d.CreateRay(m_scene.space, req.length);
  202. d.GeomRaySet(ray, req.Origin.X, req.Origin.Y, req.Origin.Z, req.Normal.X, req.Normal.Y, req.Normal.Z);
  203. // Collide test
  204. d.SpaceCollide2(m_scene.space, ray, IntPtr.Zero, nearCallback);
  205. // Remove Ray
  206. d.GeomDestroy(ray);
  207. // Find closest contact and object.
  208. lock (m_contactResults)
  209. {
  210. // Return results
  211. if (req.callbackMethod != null)
  212. req.callbackMethod(m_contactResults);
  213. }
  214. }
  215. // This is the standard Near. Uses space AABBs to speed up detection.
  216. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  217. {
  218. //Don't test against heightfield Geom, or you'll be sorry!
  219. /*
  220. terminate called after throwing an instance of 'std::bad_alloc'
  221. what(): std::bad_alloc
  222. Stacktrace:
  223. at (wrapper managed-to-native) Ode.NET.d.Collide (intptr,intptr,int,Ode.NET.d/ContactGeom[],int) <0x00004>
  224. at (wrapper managed-to-native) Ode.NET.d.Collide (intptr,intptr,int,Ode.NET.d/ContactGeom[],int) <0xffffffff>
  225. at OpenSim.Region.Physics.OdePlugin.ODERayCastRequestManager.near (intptr,intptr,intptr) <0x00280>
  226. at (wrapper native-to-managed) OpenSim.Region.Physics.OdePlugin.ODERayCastRequestManager.near (intptr,intptr,intptr) <0xfff
  227. fffff>
  228. at (wrapper managed-to-native) Ode.NET.d.SpaceCollide2 (intptr,intptr,intptr,Ode.NET.d/NearCallback) <0x00004>
  229. at (wrapper managed-to-native) Ode.NET.d.SpaceCollide2 (intptr,intptr,intptr,Ode.NET.d/NearCallback) <0xffffffff>
  230. at OpenSim.Region.Physics.OdePlugin.ODERayCastRequestManager.RayCast (OpenSim.Region.Physics.OdePlugin.ODERayCastRequest) <
  231. 0x00114>
  232. at OpenSim.Region.Physics.OdePlugin.ODERayCastRequestManager.ProcessQueuedRequests () <0x000eb>
  233. at OpenSim.Region.Physics.OdePlugin.OdeScene.Simulate (single) <0x017e6>
  234. at OpenSim.Region.Framework.Scenes.SceneGraph.UpdatePhysics (double) <0x00042>
  235. at OpenSim.Region.Framework.Scenes.Scene.Update () <0x0039e>
  236. at OpenSim.Region.Framework.Scenes.Scene.Heartbeat (object) <0x00019>
  237. at (wrapper runtime-invoke) object.runtime_invoke_void__this___object (object,intptr,intptr,intptr) <0xffffffff>
  238. Native stacktrace:
  239. mono [0x80d2a42]
  240. [0xb7f5840c]
  241. /lib/i686/cmov/libc.so.6(abort+0x188) [0xb7d1a018]
  242. /usr/lib/libstdc++.so.6(_ZN9__gnu_cxx27__verbose_terminate_handlerEv+0x158) [0xb45fc988]
  243. /usr/lib/libstdc++.so.6 [0xb45fa865]
  244. /usr/lib/libstdc++.so.6 [0xb45fa8a2]
  245. /usr/lib/libstdc++.so.6 [0xb45fa9da]
  246. /usr/lib/libstdc++.so.6(_Znwj+0x83) [0xb45fb033]
  247. /usr/lib/libstdc++.so.6(_Znaj+0x1d) [0xb45fb11d]
  248. libode.so(_ZN13dxHeightfield23dCollideHeightfieldZoneEiiiiP6dxGeomiiP12dContactGeomi+0xd04) [0xb46678e4]
  249. libode.so(_Z19dCollideHeightfieldP6dxGeomS0_iP12dContactGeomi+0x54b) [0xb466832b]
  250. libode.so(dCollide+0x102) [0xb46571b2]
  251. [0x95cfdec9]
  252. [0x8ea07fe1]
  253. [0xab260146]
  254. libode.so [0xb465a5c4]
  255. libode.so(_ZN11dxHashSpace8collide2EPvP6dxGeomPFvS0_S2_S2_E+0x75) [0xb465bcf5]
  256. libode.so(dSpaceCollide2+0x177) [0xb465ac67]
  257. [0x95cf978e]
  258. [0x8ea07945]
  259. [0x95cf2bbc]
  260. [0xab2787e7]
  261. [0xab419fb3]
  262. [0xab416657]
  263. [0xab415bda]
  264. [0xb609b08e]
  265. mono(mono_runtime_delegate_invoke+0x34) [0x8192534]
  266. mono [0x81a2f0f]
  267. mono [0x81d28b6]
  268. mono [0x81ea2c6]
  269. /lib/i686/cmov/libpthread.so.0 [0xb7e744c0]
  270. /lib/i686/cmov/libc.so.6(clone+0x5e) [0xb7dcd6de]
  271. */
  272. // Exclude heightfield geom
  273. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  274. return;
  275. if (d.GeomGetClass(g1) == d.GeomClassID.HeightfieldClass || d.GeomGetClass(g2) == d.GeomClassID.HeightfieldClass)
  276. return;
  277. // Raytest against AABBs of spaces first, then dig into the spaces it hits for actual geoms.
  278. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  279. {
  280. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  281. return;
  282. // Separating static prim geometry spaces.
  283. // We'll be calling near recursivly if one
  284. // of them is a space to find all of the
  285. // contact points in the space
  286. try
  287. {
  288. d.SpaceCollide2(g1, g2, IntPtr.Zero, nearCallback);
  289. }
  290. catch (AccessViolationException)
  291. {
  292. m_log.Warn("[PHYSICS]: Unable to collide test a space");
  293. return;
  294. }
  295. //Colliding a space or a geom with a space or a geom. so drill down
  296. //Collide all geoms in each space..
  297. //if (d.GeomIsSpace(g1)) d.SpaceCollide(g1, IntPtr.Zero, nearCallback);
  298. //if (d.GeomIsSpace(g2)) d.SpaceCollide(g2, IntPtr.Zero, nearCallback);
  299. return;
  300. }
  301. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  302. return;
  303. int count = 0;
  304. try
  305. {
  306. if (g1 == g2)
  307. return; // Can't collide with yourself
  308. lock (contacts)
  309. {
  310. count = d.Collide(g1, g2, contacts.GetLength(0), contacts, d.ContactGeom.SizeOf);
  311. }
  312. }
  313. catch (SEHException)
  314. {
  315. m_log.Error("[PHYSICS]: The Operating system shut down ODE because of corrupt memory. This could be a result of really irregular terrain. If this repeats continuously, restart using Basic Physics and terrain fill your terrain. Restarting the sim.");
  316. }
  317. catch (Exception e)
  318. {
  319. m_log.WarnFormat("[PHYSICS]: Unable to collide test an object: {0}", e.Message);
  320. return;
  321. }
  322. PhysicsActor p1 = null;
  323. PhysicsActor p2 = null;
  324. if (g1 != IntPtr.Zero)
  325. m_scene.actor_name_map.TryGetValue(g1, out p1);
  326. if (g2 != IntPtr.Zero)
  327. m_scene.actor_name_map.TryGetValue(g1, out p2);
  328. // Loop over contacts, build results.
  329. for (int i = 0; i < count; i++)
  330. {
  331. if (p1 != null)
  332. {
  333. if (p1 is OdePrim)
  334. {
  335. ContactResult collisionresult = new ContactResult();
  336. collisionresult.ConsumerID = p1.LocalID;
  337. collisionresult.Pos = new Vector3(contacts[i].pos.X, contacts[i].pos.Y, contacts[i].pos.Z);
  338. collisionresult.Depth = contacts[i].depth;
  339. collisionresult.Normal = new Vector3(contacts[i].normal.X, contacts[i].normal.Y,
  340. contacts[i].normal.Z);
  341. lock (m_contactResults)
  342. m_contactResults.Add(collisionresult);
  343. }
  344. }
  345. if (p2 != null)
  346. {
  347. if (p2 is OdePrim)
  348. {
  349. ContactResult collisionresult = new ContactResult();
  350. collisionresult.ConsumerID = p2.LocalID;
  351. collisionresult.Pos = new Vector3(contacts[i].pos.X, contacts[i].pos.Y, contacts[i].pos.Z);
  352. collisionresult.Depth = contacts[i].depth;
  353. collisionresult.Normal = new Vector3(contacts[i].normal.X, contacts[i].normal.Y,
  354. contacts[i].normal.Z);
  355. lock (m_contactResults)
  356. m_contactResults.Add(collisionresult);
  357. }
  358. }
  359. }
  360. }
  361. /// <summary>
  362. /// Dereference the creator scene so that it can be garbage collected if needed.
  363. /// </summary>
  364. internal void Dispose()
  365. {
  366. m_scene = null;
  367. }
  368. }
  369. public struct ODERayCastRequest
  370. {
  371. public Vector3 Origin;
  372. public Vector3 Normal;
  373. public float length;
  374. public RaycastCallback callbackMethod;
  375. }
  376. public struct ODERayRequest
  377. {
  378. public Vector3 Origin;
  379. public Vector3 Normal;
  380. public int Count;
  381. public float length;
  382. public RayCallback callbackMethod;
  383. }
  384. }