1
0

ODERayCastRequestManager.cs 15 KB

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