BSScene.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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 copyrightD
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Runtime.InteropServices;
  30. using System.Text;
  31. using System.Threading;
  32. using Nini.Config;
  33. using log4net;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Physics.Manager;
  36. using OpenMetaverse;
  37. using OpenSim.Region.Framework;
  38. // TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim)
  39. // Adjust character capsule size when height is adjusted (ScenePresence.SetHeight)
  40. // Test sculpties
  41. // Compute physics FPS reasonably
  42. // Based on material, set density and friction
  43. // More efficient memory usage in passing hull information from BSPrim to BulletSim
  44. // Four states of prim: Physical, regular, phantom and selected. Are we modeling these correctly?
  45. // In SL one can set both physical and phantom (gravity, does not effect others, makes collisions with ground)
  46. // At the moment, physical and phantom causes object to drop through the terrain
  47. // Should prim.link() and prim.delink() membership checking happen at taint time?
  48. // Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once
  49. // Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect
  50. // Implement the genCollisions feature in BulletSim::SetObjectProperties (don't pass up unneeded collisions)
  51. // Implement LockAngularMotion
  52. // Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation)
  53. // Does NeedsMeshing() really need to exclude all the different shapes?
  54. //
  55. namespace OpenSim.Region.Physics.BulletSPlugin
  56. {
  57. public class BSScene : PhysicsScene, IPhysicsParameters
  58. {
  59. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  60. private static readonly string LogHeader = "[BULLETS SCENE]";
  61. public string BulletSimVersion = "?";
  62. private Dictionary<uint, BSCharacter> m_avatars = new Dictionary<uint, BSCharacter>();
  63. private Dictionary<uint, BSPrim> m_prims = new Dictionary<uint, BSPrim>();
  64. private List<BSPrim> m_vehicles = new List<BSPrim>();
  65. private float[] m_heightMap;
  66. private float m_waterLevel;
  67. private uint m_worldID;
  68. public uint WorldID { get { return m_worldID; } }
  69. private bool m_initialized = false;
  70. private int m_detailedStatsStep = 0;
  71. public IMesher mesher;
  72. private float m_meshLOD;
  73. public float MeshLOD
  74. {
  75. get { return m_meshLOD; }
  76. }
  77. private float m_sculptLOD;
  78. public float SculptLOD
  79. {
  80. get { return m_sculptLOD; }
  81. }
  82. private int m_maxSubSteps;
  83. private float m_fixedTimeStep;
  84. private long m_simulationStep = 0;
  85. public long SimulationStep { get { return m_simulationStep; } }
  86. // A value of the time now so all the collision and update routines do not have to get their own
  87. // Set to 'now' just before all the prims and actors are called for collisions and updates
  88. private int m_simulationNowTime;
  89. public int SimulationNowTime { get { return m_simulationNowTime; } }
  90. private int m_maxCollisionsPerFrame;
  91. private CollisionDesc[] m_collisionArray;
  92. private GCHandle m_collisionArrayPinnedHandle;
  93. private int m_maxUpdatesPerFrame;
  94. private EntityProperties[] m_updateArray;
  95. private GCHandle m_updateArrayPinnedHandle;
  96. private bool _meshSculptedPrim = true; // cause scuplted prims to get meshed
  97. private bool _forceSimplePrimMeshing = false; // if a cube or sphere, let Bullet do internal shapes
  98. public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
  99. public const uint GROUNDPLANE_ID = 1;
  100. public ConfigurationParameters Params
  101. {
  102. get { return m_params[0]; }
  103. }
  104. public Vector3 DefaultGravity
  105. {
  106. get { return new Vector3(0f, 0f, Params.gravity); }
  107. }
  108. private float m_maximumObjectMass;
  109. public float MaximumObjectMass
  110. {
  111. get { return m_maximumObjectMass; }
  112. }
  113. public delegate void TaintCallback();
  114. private List<TaintCallback> _taintedObjects;
  115. private Object _taintLock = new Object();
  116. // A pointer to an instance if this structure is passed to the C++ code
  117. ConfigurationParameters[] m_params;
  118. GCHandle m_paramsHandle;
  119. private BulletSimAPI.DebugLogCallback m_DebugLogCallbackHandle;
  120. public BSScene(string identifier)
  121. {
  122. m_initialized = false;
  123. }
  124. public override void Initialise(IMesher meshmerizer, IConfigSource config)
  125. {
  126. // Allocate pinned memory to pass parameters.
  127. m_params = new ConfigurationParameters[1];
  128. m_paramsHandle = GCHandle.Alloc(m_params, GCHandleType.Pinned);
  129. // Set default values for physics parameters plus any overrides from the ini file
  130. GetInitialParameterValues(config);
  131. // allocate more pinned memory close to the above in an attempt to get the memory all together
  132. m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
  133. m_collisionArrayPinnedHandle = GCHandle.Alloc(m_collisionArray, GCHandleType.Pinned);
  134. m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
  135. m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned);
  136. // Get the version of the DLL
  137. // TODO: this doesn't work yet. Something wrong with marshaling the returned string.
  138. // BulletSimVersion = BulletSimAPI.GetVersion();
  139. // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion);
  140. // if Debug, enable logging from the unmanaged code
  141. if (m_log.IsDebugEnabled)
  142. {
  143. m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader);
  144. m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger);
  145. BulletSimAPI.SetDebugLogCallback(m_DebugLogCallbackHandle);
  146. }
  147. _taintedObjects = new List<TaintCallback>();
  148. mesher = meshmerizer;
  149. // The bounding box for the simulated world
  150. Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 4096f);
  151. // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader);
  152. m_worldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(),
  153. m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(),
  154. m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject());
  155. m_initialized = true;
  156. }
  157. // All default parameter values are set here. There should be no values set in the
  158. // variable definitions.
  159. private void GetInitialParameterValues(IConfigSource config)
  160. {
  161. ConfigurationParameters parms = new ConfigurationParameters();
  162. _meshSculptedPrim = true; // mesh sculpted prims
  163. _forceSimplePrimMeshing = false; // use complex meshing if called for
  164. m_meshLOD = 8f;
  165. m_sculptLOD = 32f;
  166. m_detailedStatsStep = 0; // disabled
  167. m_maxSubSteps = 10;
  168. m_fixedTimeStep = 1f / 60f;
  169. m_maxCollisionsPerFrame = 2048;
  170. m_maxUpdatesPerFrame = 2048;
  171. m_maximumObjectMass = 10000.01f;
  172. parms.defaultFriction = 0.5f;
  173. parms.defaultDensity = 10.000006836f; // Aluminum g/cm3
  174. parms.defaultRestitution = 0f;
  175. parms.collisionMargin = 0.0f;
  176. parms.gravity = -9.80665f;
  177. parms.linearDamping = 0.0f;
  178. parms.angularDamping = 0.0f;
  179. parms.deactivationTime = 0.2f;
  180. parms.linearSleepingThreshold = 0.8f;
  181. parms.angularSleepingThreshold = 1.0f;
  182. parms.ccdMotionThreshold = 0.0f; // set to zero to disable
  183. parms.ccdSweptSphereRadius = 0.0f;
  184. parms.contactProcessingThreshold = 0.1f;
  185. parms.terrainFriction = 0.5f;
  186. parms.terrainHitFraction = 0.8f;
  187. parms.terrainRestitution = 0f;
  188. parms.avatarFriction = 0.0f;
  189. parms.avatarDensity = 60f;
  190. parms.avatarCapsuleRadius = 0.37f;
  191. parms.avatarCapsuleHeight = 1.5f; // 2.140599f
  192. if (config != null)
  193. {
  194. // If there are specifications in the ini file, use those values
  195. // WHEN ADDING OR UPDATING THIS SECTION, BE SURE TO UPDATE OpenSimDefaults.ini
  196. // ALSO REMEMBER TO UPDATE THE RUNTIME SETTING OF THE PARAMETERS.
  197. IConfig pConfig = config.Configs["BulletSim"];
  198. if (pConfig != null)
  199. {
  200. _meshSculptedPrim = pConfig.GetBoolean("MeshSculptedPrim", _meshSculptedPrim);
  201. _forceSimplePrimMeshing = pConfig.GetBoolean("ForceSimplePrimMeshing", _forceSimplePrimMeshing);
  202. m_detailedStatsStep = pConfig.GetInt("DetailedStatsStep", m_detailedStatsStep);
  203. m_meshLOD = pConfig.GetFloat("MeshLevelOfDetail", m_meshLOD);
  204. m_sculptLOD = pConfig.GetFloat("SculptLevelOfDetail", m_sculptLOD);
  205. m_maxSubSteps = pConfig.GetInt("MaxSubSteps", m_maxSubSteps);
  206. m_fixedTimeStep = pConfig.GetFloat("FixedTimeStep", m_fixedTimeStep);
  207. m_maxCollisionsPerFrame = pConfig.GetInt("MaxCollisionsPerFrame", m_maxCollisionsPerFrame);
  208. m_maxUpdatesPerFrame = pConfig.GetInt("MaxUpdatesPerFrame", m_maxUpdatesPerFrame);
  209. m_maximumObjectMass = pConfig.GetFloat("MaxObjectMass", m_maximumObjectMass);
  210. parms.defaultFriction = pConfig.GetFloat("DefaultFriction", parms.defaultFriction);
  211. parms.defaultDensity = pConfig.GetFloat("DefaultDensity", parms.defaultDensity);
  212. parms.defaultRestitution = pConfig.GetFloat("DefaultRestitution", parms.defaultRestitution);
  213. parms.collisionMargin = pConfig.GetFloat("CollisionMargin", parms.collisionMargin);
  214. parms.gravity = pConfig.GetFloat("Gravity", parms.gravity);
  215. parms.linearDamping = pConfig.GetFloat("LinearDamping", parms.linearDamping);
  216. parms.angularDamping = pConfig.GetFloat("AngularDamping", parms.angularDamping);
  217. parms.deactivationTime = pConfig.GetFloat("DeactivationTime", parms.deactivationTime);
  218. parms.linearSleepingThreshold = pConfig.GetFloat("LinearSleepingThreshold", parms.linearSleepingThreshold);
  219. parms.angularSleepingThreshold = pConfig.GetFloat("AngularSleepingThreshold", parms.angularSleepingThreshold);
  220. parms.ccdMotionThreshold = pConfig.GetFloat("CcdMotionThreshold", parms.ccdMotionThreshold);
  221. parms.ccdSweptSphereRadius = pConfig.GetFloat("CcdSweptSphereRadius", parms.ccdSweptSphereRadius);
  222. parms.contactProcessingThreshold = pConfig.GetFloat("ContactProcessingThreshold", parms.contactProcessingThreshold);
  223. parms.terrainFriction = pConfig.GetFloat("TerrainFriction", parms.terrainFriction);
  224. parms.terrainHitFraction = pConfig.GetFloat("TerrainHitFraction", parms.terrainHitFraction);
  225. parms.terrainRestitution = pConfig.GetFloat("TerrainRestitution", parms.terrainRestitution);
  226. parms.avatarFriction = pConfig.GetFloat("AvatarFriction", parms.avatarFriction);
  227. parms.avatarDensity = pConfig.GetFloat("AvatarDensity", parms.avatarDensity);
  228. parms.avatarCapsuleRadius = pConfig.GetFloat("AvatarCapsuleRadius", parms.avatarCapsuleRadius);
  229. parms.avatarCapsuleHeight = pConfig.GetFloat("AvatarCapsuleHeight", parms.avatarCapsuleHeight);
  230. }
  231. }
  232. m_params[0] = parms;
  233. }
  234. // Called directly from unmanaged code so don't do much
  235. private void BulletLogger(string msg)
  236. {
  237. m_log.Debug("[BULLETS UNMANAGED]:" + msg);
  238. }
  239. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
  240. {
  241. m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
  242. return null;
  243. }
  244. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
  245. {
  246. // m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
  247. BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
  248. lock (m_avatars) m_avatars.Add(localID, actor);
  249. return actor;
  250. }
  251. public override void RemoveAvatar(PhysicsActor actor)
  252. {
  253. // m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
  254. if (actor is BSCharacter)
  255. {
  256. ((BSCharacter)actor).Destroy();
  257. }
  258. try
  259. {
  260. lock (m_avatars) m_avatars.Remove(actor.LocalID);
  261. }
  262. catch (Exception e)
  263. {
  264. m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
  265. }
  266. }
  267. public override void RemovePrim(PhysicsActor prim)
  268. {
  269. // m_log.DebugFormat("{0}: RemovePrim", LogHeader);
  270. if (prim is BSPrim)
  271. {
  272. ((BSPrim)prim).Destroy();
  273. }
  274. try
  275. {
  276. lock (m_prims) m_prims.Remove(prim.LocalID);
  277. }
  278. catch (Exception e)
  279. {
  280. m_log.WarnFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
  281. }
  282. }
  283. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  284. Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
  285. {
  286. // m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
  287. BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical);
  288. lock (m_prims) m_prims.Add(localID, prim);
  289. return prim;
  290. }
  291. // This is a call from the simulator saying that some physical property has been updated.
  292. // The BulletSim driver senses the changing of relevant properties so this taint
  293. // information call is not needed.
  294. public override void AddPhysicsActorTaint(PhysicsActor prim) { }
  295. // Simulate one timestep
  296. public override float Simulate(float timeStep)
  297. {
  298. int updatedEntityCount;
  299. IntPtr updatedEntitiesPtr;
  300. int collidersCount;
  301. IntPtr collidersPtr;
  302. // prevent simulation until we've been initialized
  303. if (!m_initialized) return 10.0f;
  304. // update the prim states while we know the physics engine is not busy
  305. ProcessTaints();
  306. // Some of the prims operate with special vehicle properties
  307. ProcessVehicles(timeStep);
  308. ProcessTaints(); // the vehicles might have added taints
  309. // step the physical world one interval
  310. m_simulationStep++;
  311. int numSubSteps = BulletSimAPI.PhysicsStep(m_worldID, timeStep, m_maxSubSteps, m_fixedTimeStep,
  312. out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr);
  313. // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in
  314. // Get a value for 'now' so all the collision and update routines don't have to get their own
  315. m_simulationNowTime = Util.EnvironmentTickCount();
  316. // If there were collisions, process them by sending the event to the prim.
  317. // Collisions must be processed before updates.
  318. if (collidersCount > 0)
  319. {
  320. for (int ii = 0; ii < collidersCount; ii++)
  321. {
  322. uint cA = m_collisionArray[ii].aID;
  323. uint cB = m_collisionArray[ii].bID;
  324. Vector3 point = m_collisionArray[ii].point;
  325. Vector3 normal = m_collisionArray[ii].normal;
  326. SendCollision(cA, cB, point, normal, 0.01f);
  327. SendCollision(cB, cA, point, -normal, 0.01f);
  328. }
  329. }
  330. // If any of the objects had updated properties, tell the object it has been changed by the physics engine
  331. if (updatedEntityCount > 0)
  332. {
  333. for (int ii = 0; ii < updatedEntityCount; ii++)
  334. {
  335. EntityProperties entprop = m_updateArray[ii];
  336. // m_log.DebugFormat("{0}: entprop[{1}]: id={2}, pos={3}", LogHeader, ii, entprop.ID, entprop.Position);
  337. BSCharacter actor;
  338. if (m_avatars.TryGetValue(entprop.ID, out actor))
  339. {
  340. actor.UpdateProperties(entprop);
  341. continue;
  342. }
  343. BSPrim prim;
  344. if (m_prims.TryGetValue(entprop.ID, out prim))
  345. {
  346. prim.UpdateProperties(entprop);
  347. }
  348. }
  349. }
  350. if (m_detailedStatsStep > 0)
  351. {
  352. if ((m_simulationStep % m_detailedStatsStep) == 0)
  353. {
  354. BulletSimAPI.DumpBulletStatistics();
  355. }
  356. }
  357. // TODO: FIX THIS: fps calculation wrong. This calculation always returns about 1 in normal operation.
  358. return timeStep / (numSubSteps * m_fixedTimeStep) * 1000f;
  359. }
  360. // Something has collided
  361. private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penitration)
  362. {
  363. if (localID == TERRAIN_ID || localID == GROUNDPLANE_ID)
  364. {
  365. return; // don't send collisions to the terrain
  366. }
  367. ActorTypes type = ActorTypes.Prim;
  368. if (collidingWith == TERRAIN_ID || collidingWith == GROUNDPLANE_ID)
  369. type = ActorTypes.Ground;
  370. else if (m_avatars.ContainsKey(collidingWith))
  371. type = ActorTypes.Agent;
  372. BSPrim prim;
  373. if (m_prims.TryGetValue(localID, out prim)) {
  374. prim.Collide(collidingWith, type, collidePoint, collideNormal, penitration);
  375. return;
  376. }
  377. BSCharacter actor;
  378. if (m_avatars.TryGetValue(localID, out actor)) {
  379. actor.Collide(collidingWith, type, collidePoint, collideNormal, penitration);
  380. return;
  381. }
  382. return;
  383. }
  384. public override void GetResults() { }
  385. public override void SetTerrain(float[] heightMap) {
  386. m_heightMap = heightMap;
  387. this.TaintedObject(delegate()
  388. {
  389. BulletSimAPI.SetHeightmap(m_worldID, m_heightMap);
  390. });
  391. }
  392. public float GetTerrainHeightAtXY(float tX, float tY)
  393. {
  394. return m_heightMap[((int)tX) * Constants.RegionSize + ((int)tY)];
  395. }
  396. public override void SetWaterLevel(float baseheight)
  397. {
  398. m_waterLevel = baseheight;
  399. }
  400. public float GetWaterLevel()
  401. {
  402. return m_waterLevel;
  403. }
  404. public override void DeleteTerrain()
  405. {
  406. m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
  407. }
  408. public override void Dispose()
  409. {
  410. m_log.DebugFormat("{0}: Dispose()", LogHeader);
  411. }
  412. public override Dictionary<uint, float> GetTopColliders()
  413. {
  414. return new Dictionary<uint, float>();
  415. }
  416. public override bool IsThreaded { get { return false; } }
  417. /// <summary>
  418. /// Routine to figure out if we need to mesh this prim with our mesher
  419. /// </summary>
  420. /// <param name="pbs"></param>
  421. /// <returns>true if the prim needs meshing</returns>
  422. public bool NeedsMeshing(PrimitiveBaseShape pbs)
  423. {
  424. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  425. // but we still need to check for sculptie meshing being enabled so this is the most
  426. // convenient place to do it for now...
  427. // int iPropertiesNotSupportedDefault = 0;
  428. if (pbs.SculptEntry && !_meshSculptedPrim)
  429. {
  430. // Render sculpties as boxes
  431. return false;
  432. }
  433. // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since Bullet
  434. // can use an internal representation for the prim
  435. if (!_forceSimplePrimMeshing)
  436. {
  437. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  438. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  439. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  440. {
  441. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  442. && pbs.ProfileHollow == 0
  443. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  444. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  445. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  446. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  447. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  448. {
  449. return false;
  450. }
  451. }
  452. }
  453. /* TODO: verify that the mesher will now do all these shapes
  454. if (pbs.ProfileHollow != 0)
  455. iPropertiesNotSupportedDefault++;
  456. if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
  457. iPropertiesNotSupportedDefault++;
  458. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  459. iPropertiesNotSupportedDefault++;
  460. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  461. iPropertiesNotSupportedDefault++;
  462. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  463. iPropertiesNotSupportedDefault++;
  464. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  465. iPropertiesNotSupportedDefault++;
  466. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  467. iPropertiesNotSupportedDefault++;
  468. 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))
  469. iPropertiesNotSupportedDefault++;
  470. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  471. iPropertiesNotSupportedDefault++;
  472. // test for torus
  473. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  474. {
  475. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  476. {
  477. iPropertiesNotSupportedDefault++;
  478. }
  479. }
  480. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  481. {
  482. if (pbs.PathCurve == (byte)Extrusion.Straight)
  483. {
  484. iPropertiesNotSupportedDefault++;
  485. }
  486. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  487. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  488. {
  489. iPropertiesNotSupportedDefault++;
  490. }
  491. }
  492. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  493. {
  494. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  495. {
  496. iPropertiesNotSupportedDefault++;
  497. }
  498. }
  499. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  500. {
  501. if (pbs.PathCurve == (byte)Extrusion.Straight)
  502. {
  503. iPropertiesNotSupportedDefault++;
  504. }
  505. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  506. {
  507. iPropertiesNotSupportedDefault++;
  508. }
  509. }
  510. if (iPropertiesNotSupportedDefault == 0)
  511. {
  512. return false;
  513. }
  514. */
  515. return true;
  516. }
  517. // The calls to the PhysicsActors can't directly call into the physics engine
  518. // because it might be busy. We we delay changes to a known time.
  519. // We rely on C#'s closure to save and restore the context for the delegate.
  520. public void TaintedObject(TaintCallback callback)
  521. {
  522. lock (_taintLock)
  523. _taintedObjects.Add(callback);
  524. return;
  525. }
  526. // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
  527. // a callback into itself to do the actual property change. That callback is called
  528. // here just before the physics engine is called to step the simulation.
  529. public void ProcessTaints()
  530. {
  531. if (_taintedObjects.Count > 0) // save allocating new list if there is nothing to process
  532. {
  533. // swizzle a new list into the list location so we can process what's there
  534. List<TaintCallback> oldList;
  535. lock (_taintLock)
  536. {
  537. oldList = _taintedObjects;
  538. _taintedObjects = new List<TaintCallback>();
  539. }
  540. foreach (TaintCallback callback in oldList)
  541. {
  542. try
  543. {
  544. callback();
  545. }
  546. catch (Exception e)
  547. {
  548. m_log.ErrorFormat("{0}: ProcessTaints: Exception: {1}", LogHeader, e);
  549. }
  550. }
  551. oldList.Clear();
  552. }
  553. }
  554. #region Vehicles
  555. // Make so the scene will call this prim for vehicle actions each tick.
  556. // Safe to call if prim is already in the vehicle list.
  557. public void AddVehiclePrim(BSPrim vehicle)
  558. {
  559. lock (m_vehicles)
  560. {
  561. if (!m_vehicles.Contains(vehicle))
  562. {
  563. m_vehicles.Add(vehicle);
  564. }
  565. }
  566. }
  567. // Remove a prim from our list of vehicles.
  568. // Safe to call if the prim is not in the vehicle list.
  569. public void RemoveVehiclePrim(BSPrim vehicle)
  570. {
  571. lock (m_vehicles)
  572. {
  573. if (m_vehicles.Contains(vehicle))
  574. {
  575. m_vehicles.Remove(vehicle);
  576. }
  577. }
  578. }
  579. // Some prims have extra vehicle actions
  580. // no locking because only called when physics engine is not busy
  581. private void ProcessVehicles(float timeStep)
  582. {
  583. foreach (BSPrim prim in m_vehicles)
  584. {
  585. prim.StepVehicle(timeStep);
  586. }
  587. }
  588. #endregion Vehicles
  589. #region Runtime settable parameters
  590. public static PhysParameterEntry[] SettableParameters = new PhysParameterEntry[]
  591. {
  592. new PhysParameterEntry("MeshLOD", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)"),
  593. new PhysParameterEntry("SculptLOD", "Level of detail to render sculpties (32, 16, 8 or 4. 32=most detailed)"),
  594. new PhysParameterEntry("MaxSubStep", "In simulation step, maximum number of substeps"),
  595. new PhysParameterEntry("FixedTimeStep", "In simulation step, seconds of one substep (1/60)"),
  596. new PhysParameterEntry("MaxObjectMass", "Maximum object mass (10000.01)"),
  597. new PhysParameterEntry("DetailedStats", "Frames between outputting detailed phys stats. Zero is off"),
  598. new PhysParameterEntry("DefaultFriction", "Friction factor used on new objects"),
  599. new PhysParameterEntry("DefaultDensity", "Density for new objects" ),
  600. new PhysParameterEntry("DefaultRestitution", "Bouncyness of an object" ),
  601. // new PhysParameterEntry("CollisionMargin", "Margin around objects before collisions are calculated (must be zero!!)" ),
  602. new PhysParameterEntry("Gravity", "Vertical force of gravity (negative means down)" ),
  603. new PhysParameterEntry("LinearDamping", "Factor to damp linear movement per second (0.0 - 1.0)" ),
  604. new PhysParameterEntry("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)" ),
  605. new PhysParameterEntry("DeactivationTime", "Seconds before considering an object potentially static" ),
  606. new PhysParameterEntry("LinearSleepingThreshold", "Seconds to measure linear movement before considering static" ),
  607. new PhysParameterEntry("AngularSleepingThreshold", "Seconds to measure angular movement before considering static" ),
  608. // new PhysParameterEntry("CcdMotionThreshold", "" ),
  609. // new PhysParameterEntry("CcdSweptSphereRadius", "" ),
  610. new PhysParameterEntry("ContactProcessingThreshold", "Distance between contacts before doing collision check" ),
  611. new PhysParameterEntry("TerrainFriction", "Factor to reduce movement against terrain surface" ),
  612. new PhysParameterEntry("TerrainHitFraction", "Distance to measure hit collisions" ),
  613. new PhysParameterEntry("TerrainRestitution", "Bouncyness" ),
  614. new PhysParameterEntry("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation." ),
  615. new PhysParameterEntry("AvatarDensity", "Density of an avatar. Changed on avatar recreation." ),
  616. new PhysParameterEntry("AvatarRestitution", "Bouncyness. Changed on avatar recreation." ),
  617. new PhysParameterEntry("AvatarCapsuleRadius", "Radius of space around an avatar" ),
  618. new PhysParameterEntry("AvatarCapsuleHeight", "Default height of space around avatar" )
  619. };
  620. #region IPhysicsParameters
  621. // Get the list of parameters this physics engine supports
  622. public PhysParameterEntry[] GetParameterList()
  623. {
  624. return SettableParameters;
  625. }
  626. // Set parameter on a specific or all instances.
  627. // Return 'false' if not able to set the parameter.
  628. // Setting the value in the m_params block will change the value the physics engine
  629. // will use the next time since it's pinned and shared memory.
  630. // Some of the values require calling into the physics engine to get the new
  631. // value activated ('terrainFriction' for instance).
  632. public bool SetPhysicsParameter(string parm, float val, uint localID)
  633. {
  634. bool ret = true;
  635. string lparm = parm.ToLower();
  636. switch (lparm)
  637. {
  638. case "detailedstats": m_detailedStatsStep = (int)val; break;
  639. case "meshlod": m_meshLOD = (int)val; break;
  640. case "sculptlod": m_sculptLOD = (int)val; break;
  641. case "maxsubstep": m_maxSubSteps = (int)val; break;
  642. case "fixedtimestep": m_fixedTimeStep = val; break;
  643. case "maxobjectmass": m_maximumObjectMass = val; break;
  644. case "defaultfriction": m_params[0].defaultFriction = val; break;
  645. case "defaultdensity": m_params[0].defaultDensity = val; break;
  646. case "defaultrestitution": m_params[0].defaultRestitution = val; break;
  647. case "collisionmargin": m_params[0].collisionMargin = val; break;
  648. case "gravity": m_params[0].gravity = val; TaintedUpdateParameter(lparm, PhysParameterEntry.APPLY_TO_NONE, val); break;
  649. case "lineardamping": UpdateParameterPrims(ref m_params[0].linearDamping, lparm, localID, val); break;
  650. case "angulardamping": UpdateParameterPrims(ref m_params[0].angularDamping, lparm, localID, val); break;
  651. case "deactivationtime": UpdateParameterPrims(ref m_params[0].deactivationTime, lparm, localID, val); break;
  652. case "linearsleepingthreshold": UpdateParameterPrims(ref m_params[0].linearSleepingThreshold, lparm, localID, val); break;
  653. case "angularsleepingthreshold": UpdateParameterPrims(ref m_params[0].angularDamping, lparm, localID, val); break;
  654. case "ccdmotionthreshold": UpdateParameterPrims(ref m_params[0].ccdMotionThreshold, lparm, localID, val); break;
  655. case "ccdsweptsphereradius": UpdateParameterPrims(ref m_params[0].ccdSweptSphereRadius, lparm, localID, val); break;
  656. case "contactprocessingthreshold": UpdateParameterPrims(ref m_params[0].contactProcessingThreshold, lparm, localID, val); break;
  657. // set a terrain physical feature and cause terrain to be recalculated
  658. case "terrainfriction": m_params[0].terrainFriction = val; TaintedUpdateParameter("terrain", 0, val); break;
  659. case "terrainhitfraction": m_params[0].terrainHitFraction = val; TaintedUpdateParameter("terrain", 0, val); break;
  660. case "terrainrestitution": m_params[0].terrainRestitution = val; TaintedUpdateParameter("terrain", 0, val); break;
  661. // set an avatar physical feature and cause avatar(s) to be recalculated
  662. case "avatarfriction": UpdateParameterAvatars(ref m_params[0].avatarFriction, "avatar", localID, val); break;
  663. case "avatardensity": UpdateParameterAvatars(ref m_params[0].avatarDensity, "avatar", localID, val); break;
  664. case "avatarrestitution": UpdateParameterAvatars(ref m_params[0].avatarRestitution, "avatar", localID, val); break;
  665. case "avatarcapsuleradius": UpdateParameterAvatars(ref m_params[0].avatarCapsuleRadius, "avatar", localID, val); break;
  666. case "avatarcapsuleheight": UpdateParameterAvatars(ref m_params[0].avatarCapsuleHeight, "avatar", localID, val); break;
  667. default: ret = false; break;
  668. }
  669. return ret;
  670. }
  671. // check to see if we are updating a parameter for a particular or all of the prims
  672. private void UpdateParameterPrims(ref float loc, string parm, uint localID, float val)
  673. {
  674. List<uint> operateOn;
  675. lock (m_prims) operateOn = new List<uint>(m_prims.Keys);
  676. UpdateParameterSet(operateOn, ref loc, parm, localID, val);
  677. }
  678. // check to see if we are updating a parameter for a particular or all of the avatars
  679. private void UpdateParameterAvatars(ref float loc, string parm, uint localID, float val)
  680. {
  681. List<uint> operateOn;
  682. lock (m_avatars) operateOn = new List<uint>(m_avatars.Keys);
  683. UpdateParameterSet(operateOn, ref loc, parm, localID, val);
  684. }
  685. // update all the localIDs specified
  686. // If the local ID is APPLY_TO_NONE, just change the default value
  687. // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
  688. // If the localID is a specific object, apply the parameter change to only that object
  689. private void UpdateParameterSet(List<uint> lIDs, ref float defaultLoc, string parm, uint localID, float val)
  690. {
  691. switch (localID)
  692. {
  693. case PhysParameterEntry.APPLY_TO_NONE:
  694. defaultLoc = val; // setting only the default value
  695. break;
  696. case PhysParameterEntry.APPLY_TO_ALL:
  697. defaultLoc = val; // setting ALL also sets the default value
  698. List<uint> objectIDs = lIDs;
  699. string xparm = parm.ToLower();
  700. float xval = val;
  701. TaintedObject(delegate() {
  702. foreach (uint lID in objectIDs)
  703. {
  704. BulletSimAPI.UpdateParameter(m_worldID, lID, xparm, xval);
  705. }
  706. });
  707. break;
  708. default:
  709. // setting only one localID
  710. TaintedUpdateParameter(parm, localID, val);
  711. break;
  712. }
  713. }
  714. // schedule the actual updating of the paramter to when the phys engine is not busy
  715. private void TaintedUpdateParameter(string parm, uint localID, float val)
  716. {
  717. uint xlocalID = localID;
  718. string xparm = parm.ToLower();
  719. float xval = val;
  720. TaintedObject(delegate() {
  721. BulletSimAPI.UpdateParameter(m_worldID, xlocalID, xparm, xval);
  722. });
  723. }
  724. // Get parameter.
  725. // Return 'false' if not able to get the parameter.
  726. public bool GetPhysicsParameter(string parm, out float value)
  727. {
  728. float val = 0f;
  729. bool ret = true;
  730. switch (parm.ToLower())
  731. {
  732. case "detailedstats": val = (int)m_detailedStatsStep; break;
  733. case "meshlod": val = (float)m_meshLOD; break;
  734. case "sculptlod": val = (float)m_sculptLOD; break;
  735. case "maxsubstep": val = (float)m_maxSubSteps; break;
  736. case "fixedtimestep": val = m_fixedTimeStep; break;
  737. case "maxobjectmass": val = m_maximumObjectMass; break;
  738. case "defaultfriction": val = m_params[0].defaultFriction; break;
  739. case "defaultdensity": val = m_params[0].defaultDensity; break;
  740. case "defaultrestitution": val = m_params[0].defaultRestitution; break;
  741. case "collisionmargin": val = m_params[0].collisionMargin; break;
  742. case "gravity": val = m_params[0].gravity; break;
  743. case "lineardamping": val = m_params[0].linearDamping; break;
  744. case "angulardamping": val = m_params[0].angularDamping; break;
  745. case "deactivationtime": val = m_params[0].deactivationTime; break;
  746. case "linearsleepingthreshold": val = m_params[0].linearSleepingThreshold; break;
  747. case "angularsleepingthreshold": val = m_params[0].angularDamping; break;
  748. case "ccdmotionthreshold": val = m_params[0].ccdMotionThreshold; break;
  749. case "ccdsweptsphereradius": val = m_params[0].ccdSweptSphereRadius; break;
  750. case "contactprocessingthreshold": val = m_params[0].contactProcessingThreshold; break;
  751. case "terrainfriction": val = m_params[0].terrainFriction; break;
  752. case "terrainhitfraction": val = m_params[0].terrainHitFraction; break;
  753. case "terrainrestitution": val = m_params[0].terrainRestitution; break;
  754. case "avatarfriction": val = m_params[0].avatarFriction; break;
  755. case "avatardensity": val = m_params[0].avatarDensity; break;
  756. case "avatarrestitution": val = m_params[0].avatarRestitution; break;
  757. case "avatarcapsuleradius": val = m_params[0].avatarCapsuleRadius; break;
  758. case "avatarcapsuleheight": val = m_params[0].avatarCapsuleHeight; break;
  759. default: ret = false; break;
  760. }
  761. value = val;
  762. return ret;
  763. }
  764. #endregion IPhysicsParameters
  765. #endregion Runtime settable parameters
  766. }
  767. }