ODERayCastRequestManager.cs 16 KB

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