PageRenderTime 78ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs

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