BSScene.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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.Linq;
  30. using System.Reflection;
  31. using System.Runtime.InteropServices;
  32. using System.Text;
  33. using System.Threading;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework;
  36. using OpenSim.Region.CoreModules;
  37. using Logging = OpenSim.Region.CoreModules.Framework.Statistics.Logging;
  38. using OpenSim.Region.Physics.Manager;
  39. using Nini.Config;
  40. using log4net;
  41. using OpenMetaverse;
  42. namespace OpenSim.Region.Physics.BulletSPlugin
  43. {
  44. public sealed class BSScene : PhysicsScene, IPhysicsParameters
  45. {
  46. internal static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  47. internal static readonly string LogHeader = "[BULLETS SCENE]";
  48. // The name of the region we're working for.
  49. public string RegionName { get; private set; }
  50. public string BulletSimVersion = "?";
  51. // The handle to the underlying managed or unmanaged version of Bullet being used.
  52. public string BulletEngineName { get; private set; }
  53. public BSAPITemplate PE;
  54. // If the physics engine is running on a separate thread
  55. public Thread m_physicsThread;
  56. public Dictionary<uint, BSPhysObject> PhysObjects;
  57. public BSShapeCollection Shapes;
  58. // Keeping track of the objects with collisions so we can report begin and end of a collision
  59. public HashSet<BSPhysObject> ObjectsWithCollisions = new HashSet<BSPhysObject>();
  60. public HashSet<BSPhysObject> ObjectsWithNoMoreCollisions = new HashSet<BSPhysObject>();
  61. // All the collision processing is protected with this lock object
  62. public Object CollisionLock = new Object();
  63. // Properties are updated here
  64. public Object UpdateLock = new Object();
  65. public HashSet<BSPhysObject> ObjectsWithUpdates = new HashSet<BSPhysObject>();
  66. // Keep track of all the avatars so we can send them a collision event
  67. // every tick so OpenSim will update its animation.
  68. private HashSet<BSPhysObject> m_avatars = new HashSet<BSPhysObject>();
  69. // let my minuions use my logger
  70. public ILog Logger { get { return m_log; } }
  71. public IMesher mesher;
  72. public uint WorldID { get; private set; }
  73. public BulletWorld World { get; private set; }
  74. // All the constraints that have been allocated in this instance.
  75. public BSConstraintCollection Constraints { get; private set; }
  76. // Simulation parameters
  77. internal float m_physicsStepTime; // if running independently, the interval simulated by default
  78. internal int m_maxSubSteps;
  79. internal float m_fixedTimeStep;
  80. internal float m_simulatedTime; // the time simulated previously. Used for physics framerate calc.
  81. internal long m_simulationStep = 0; // The current simulation step.
  82. public long SimulationStep { get { return m_simulationStep; } }
  83. // A number to use for SimulationStep that is probably not any step value
  84. // Used by the collision code (which remembers the step when a collision happens) to remember not any simulation step.
  85. public static long NotASimulationStep = -1234;
  86. internal float LastTimeStep { get; private set; } // The simulation time from the last invocation of Simulate()
  87. internal float NominalFrameRate { get; set; } // Parameterized ideal frame rate that simulation is scaled to
  88. // Physical objects can register for prestep or poststep events
  89. public delegate void PreStepAction(float timeStep);
  90. public delegate void PostStepAction(float timeStep);
  91. public event PreStepAction BeforeStep;
  92. public event PostStepAction AfterStep;
  93. // A value of the time 'now' so all the collision and update routines do not have to get their own
  94. // Set to 'now' just before all the prims and actors are called for collisions and updates
  95. public int SimulationNowTime { get; private set; }
  96. // True if initialized and ready to do simulation steps
  97. private bool m_initialized = false;
  98. // Flag which is true when processing taints.
  99. // Not guaranteed to be correct all the time (don't depend on this) but good for debugging.
  100. public bool InTaintTime { get; private set; }
  101. // Pinned memory used to pass step information between managed and unmanaged
  102. internal int m_maxCollisionsPerFrame;
  103. internal CollisionDesc[] m_collisionArray;
  104. internal int m_maxUpdatesPerFrame;
  105. internal EntityProperties[] m_updateArray;
  106. public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
  107. public const uint GROUNDPLANE_ID = 1;
  108. public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here
  109. public float SimpleWaterLevel { get; set; }
  110. public BSTerrainManager TerrainManager { get; private set; }
  111. public ConfigurationParameters Params
  112. {
  113. get { return UnmanagedParams[0]; }
  114. }
  115. public Vector3 DefaultGravity
  116. {
  117. get { return new Vector3(0f, 0f, Params.gravity); }
  118. }
  119. // Just the Z value of the gravity
  120. public float DefaultGravityZ
  121. {
  122. get { return Params.gravity; }
  123. }
  124. // When functions in the unmanaged code must be called, it is only
  125. // done at a known time just before the simulation step. The taint
  126. // system saves all these function calls and executes them in
  127. // order before the simulation.
  128. public delegate void TaintCallback();
  129. private struct TaintCallbackEntry
  130. {
  131. public String originator;
  132. public String ident;
  133. public TaintCallback callback;
  134. public TaintCallbackEntry(string pIdent, TaintCallback pCallBack)
  135. {
  136. originator = BSScene.DetailLogZero;
  137. ident = pIdent;
  138. callback = pCallBack;
  139. }
  140. public TaintCallbackEntry(string pOrigin, string pIdent, TaintCallback pCallBack)
  141. {
  142. originator = pOrigin;
  143. ident = pIdent;
  144. callback = pCallBack;
  145. }
  146. }
  147. private Object _taintLock = new Object(); // lock for using the next object
  148. private List<TaintCallbackEntry> _taintOperations;
  149. private Dictionary<string, TaintCallbackEntry> _postTaintOperations;
  150. private List<TaintCallbackEntry> _postStepOperations;
  151. // A pointer to an instance if this structure is passed to the C++ code
  152. // Used to pass basic configuration values to the unmanaged code.
  153. internal ConfigurationParameters[] UnmanagedParams;
  154. // Sometimes you just have to log everything.
  155. public Logging.LogWriter PhysicsLogging;
  156. private bool m_physicsLoggingEnabled;
  157. private string m_physicsLoggingDir;
  158. private string m_physicsLoggingPrefix;
  159. private int m_physicsLoggingFileMinutes;
  160. private bool m_physicsLoggingDoFlush;
  161. private bool m_physicsPhysicalDumpEnabled;
  162. public int PhysicsMetricDumpFrames { get; set; }
  163. // 'true' of the vehicle code is to log lots of details
  164. public bool VehicleLoggingEnabled { get; private set; }
  165. public bool VehiclePhysicalLoggingEnabled { get; private set; }
  166. #region Construction and Initialization
  167. public BSScene(string engineType, string identifier)
  168. {
  169. m_initialized = false;
  170. // The name of the region we're working for is passed to us. Keep for identification.
  171. RegionName = identifier;
  172. // Set identifying variables in the PhysicsScene interface.
  173. EngineType = engineType;
  174. Name = EngineType + "/" + RegionName;
  175. }
  176. // Old version of initialization that assumes legacy sized regions (256x256)
  177. public override void Initialise(IMesher meshmerizer, IConfigSource config)
  178. {
  179. m_log.ErrorFormat("{0} WARNING WARNING WARNING! BulletSim initialized without region extent specification. Terrain will be messed up.");
  180. Vector3 regionExtent = new Vector3( Constants.RegionSize, Constants.RegionSize, Constants.RegionSize);
  181. Initialise(meshmerizer, config, regionExtent);
  182. }
  183. public override void Initialise(IMesher meshmerizer, IConfigSource config, Vector3 regionExtent)
  184. {
  185. mesher = meshmerizer;
  186. _taintOperations = new List<TaintCallbackEntry>();
  187. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  188. _postStepOperations = new List<TaintCallbackEntry>();
  189. PhysObjects = new Dictionary<uint, BSPhysObject>();
  190. Shapes = new BSShapeCollection(this);
  191. m_simulatedTime = 0f;
  192. LastTimeStep = 0.1f;
  193. // Allocate pinned memory to pass parameters.
  194. UnmanagedParams = new ConfigurationParameters[1];
  195. // Set default values for physics parameters plus any overrides from the ini file
  196. GetInitialParameterValues(config);
  197. // Force some parameters to values depending on other configurations
  198. // Only use heightmap terrain implementation if terrain larger than legacy size
  199. if ((uint)regionExtent.X > Constants.RegionSize || (uint)regionExtent.Y > Constants.RegionSize)
  200. {
  201. m_log.WarnFormat("{0} Forcing terrain implementation to heightmap for large region", LogHeader);
  202. BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap;
  203. }
  204. // Get the connection to the physics engine (could be native or one of many DLLs)
  205. PE = SelectUnderlyingBulletEngine(BulletEngineName);
  206. // Enable very detailed logging.
  207. // By creating an empty logger when not logging, the log message invocation code
  208. // can be left in and every call doesn't have to check for null.
  209. if (m_physicsLoggingEnabled)
  210. {
  211. PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush);
  212. PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output its own error messages.
  213. }
  214. else
  215. {
  216. PhysicsLogging = new Logging.LogWriter();
  217. }
  218. // Allocate memory for returning of the updates and collisions from the physics engine
  219. m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
  220. m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
  221. // The bounding box for the simulated world. The origin is 0,0,0 unless we're
  222. // a child in a mega-region.
  223. // Bullet actually doesn't care about the extents of the simulated
  224. // area. It tracks active objects no matter where they are.
  225. Vector3 worldExtent = regionExtent;
  226. World = PE.Initialize(worldExtent, Params, m_maxCollisionsPerFrame, ref m_collisionArray, m_maxUpdatesPerFrame, ref m_updateArray);
  227. Constraints = new BSConstraintCollection(World);
  228. TerrainManager = new BSTerrainManager(this, worldExtent);
  229. TerrainManager.CreateInitialGroundPlaneAndTerrain();
  230. // Put some informational messages into the log file.
  231. m_log.InfoFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation);
  232. InTaintTime = false;
  233. m_initialized = true;
  234. // If the physics engine runs on its own thread, start same.
  235. if (BSParam.UseSeparatePhysicsThread)
  236. {
  237. // The physics simulation should happen independently of the heartbeat loop
  238. m_physicsThread = new Thread(BulletSPluginPhysicsThread);
  239. m_physicsThread.Name = BulletEngineName;
  240. m_physicsThread.Start();
  241. }
  242. }
  243. // All default parameter values are set here. There should be no values set in the
  244. // variable definitions.
  245. private void GetInitialParameterValues(IConfigSource config)
  246. {
  247. ConfigurationParameters parms = new ConfigurationParameters();
  248. UnmanagedParams[0] = parms;
  249. BSParam.SetParameterDefaultValues(this);
  250. if (config != null)
  251. {
  252. // If there are specifications in the ini file, use those values
  253. IConfig pConfig = config.Configs["BulletSim"];
  254. if (pConfig != null)
  255. {
  256. BSParam.SetParameterConfigurationValues(this, pConfig);
  257. // There are two Bullet implementations to choose from
  258. BulletEngineName = pConfig.GetString("BulletEngine", "BulletUnmanaged");
  259. // Very detailed logging for physics debugging
  260. // TODO: the boolean values can be moved to the normal parameter processing.
  261. m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false);
  262. m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", ".");
  263. m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-");
  264. m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
  265. m_physicsLoggingDoFlush = pConfig.GetBoolean("PhysicsLoggingDoFlush", false);
  266. m_physicsPhysicalDumpEnabled = pConfig.GetBoolean("PhysicsPhysicalDumpEnabled", false);
  267. // Very detailed logging for vehicle debugging
  268. VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
  269. VehiclePhysicalLoggingEnabled = pConfig.GetBoolean("VehiclePhysicalLoggingEnabled", false);
  270. // Do any replacements in the parameters
  271. m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName);
  272. }
  273. else
  274. {
  275. // Nothing in the configuration INI file so assume unmanaged and other defaults.
  276. BulletEngineName = "BulletUnmanaged";
  277. m_physicsLoggingEnabled = false;
  278. VehicleLoggingEnabled = false;
  279. }
  280. // The material characteristics.
  281. BSMaterials.InitializeFromDefaults(Params);
  282. if (pConfig != null)
  283. {
  284. // Let the user add new and interesting material property values.
  285. BSMaterials.InitializefromParameters(pConfig);
  286. }
  287. }
  288. }
  289. // A helper function that handles a true/false parameter and returns the proper float number encoding
  290. float ParamBoolean(IConfig config, string parmName, float deflt)
  291. {
  292. float ret = deflt;
  293. if (config.Contains(parmName))
  294. {
  295. ret = ConfigurationParameters.numericFalse;
  296. if (config.GetBoolean(parmName, false))
  297. {
  298. ret = ConfigurationParameters.numericTrue;
  299. }
  300. }
  301. return ret;
  302. }
  303. // Select the connection to the actual Bullet implementation.
  304. // The main engine selection is the engineName up to the first hypen.
  305. // So "Bullet-2.80-OpenCL-Intel" specifies the 'bullet' class here and the whole name
  306. // is passed to the engine to do its special selection, etc.
  307. private BSAPITemplate SelectUnderlyingBulletEngine(string engineName)
  308. {
  309. // For the moment, do a simple switch statement.
  310. // Someday do fancyness with looking up the interfaces in the assembly.
  311. BSAPITemplate ret = null;
  312. string selectionName = engineName.ToLower();
  313. int hyphenIndex = engineName.IndexOf("-");
  314. if (hyphenIndex > 0)
  315. selectionName = engineName.ToLower().Substring(0, hyphenIndex - 1);
  316. switch (selectionName)
  317. {
  318. case "bullet":
  319. case "bulletunmanaged":
  320. ret = new BSAPIUnman(engineName, this);
  321. break;
  322. case "bulletxna":
  323. ret = new BSAPIXNA(engineName, this);
  324. // Disable some features that are not implemented in BulletXNA
  325. m_log.InfoFormat("{0} Disabling some physics features not implemented by BulletXNA", LogHeader);
  326. m_log.InfoFormat("{0} Disabling ShouldUseBulletHACD", LogHeader);
  327. BSParam.ShouldUseBulletHACD = false;
  328. m_log.InfoFormat("{0} Disabling ShouldUseSingleConvexHullForPrims", LogHeader);
  329. BSParam.ShouldUseSingleConvexHullForPrims = false;
  330. m_log.InfoFormat("{0} Disabling ShouldUseGImpactShapeForPrims", LogHeader);
  331. BSParam.ShouldUseGImpactShapeForPrims = false;
  332. m_log.InfoFormat("{0} Setting terrain implimentation to Heightmap", LogHeader);
  333. BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap;
  334. break;
  335. }
  336. if (ret == null)
  337. {
  338. m_log.ErrorFormat("{0) COULD NOT SELECT BULLET ENGINE: '[BulletSim]PhysicsEngine' must be either 'BulletUnmanaged-*' or 'BulletXNA-*'", LogHeader);
  339. }
  340. else
  341. {
  342. m_log.InfoFormat("{0} Selected bullet engine {1} -> {2}/{3}", LogHeader, engineName, ret.BulletEngineName, ret.BulletEngineVersion);
  343. }
  344. return ret;
  345. }
  346. public override void Dispose()
  347. {
  348. // m_log.DebugFormat("{0}: Dispose()", LogHeader);
  349. // make sure no stepping happens while we're deleting stuff
  350. m_initialized = false;
  351. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  352. {
  353. kvp.Value.Destroy();
  354. }
  355. PhysObjects.Clear();
  356. // Now that the prims are all cleaned up, there should be no constraints left
  357. if (Constraints != null)
  358. {
  359. Constraints.Dispose();
  360. Constraints = null;
  361. }
  362. if (Shapes != null)
  363. {
  364. Shapes.Dispose();
  365. Shapes = null;
  366. }
  367. if (TerrainManager != null)
  368. {
  369. TerrainManager.ReleaseGroundPlaneAndTerrain();
  370. TerrainManager.Dispose();
  371. TerrainManager = null;
  372. }
  373. // Anything left in the unmanaged code should be cleaned out
  374. PE.Shutdown(World);
  375. // Not logging any more
  376. PhysicsLogging.Close();
  377. }
  378. #endregion // Construction and Initialization
  379. #region Prim and Avatar addition and removal
  380. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
  381. {
  382. m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
  383. return null;
  384. }
  385. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
  386. {
  387. // m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
  388. if (!m_initialized) return null;
  389. BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
  390. lock (PhysObjects)
  391. PhysObjects.Add(localID, actor);
  392. // TODO: Remove kludge someday.
  393. // We must generate a collision for avatars whether they collide or not.
  394. // This is required by OpenSim to update avatar animations, etc.
  395. lock (m_avatars)
  396. m_avatars.Add(actor);
  397. return actor;
  398. }
  399. public override void RemoveAvatar(PhysicsActor actor)
  400. {
  401. // m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
  402. if (!m_initialized) return;
  403. BSCharacter bsactor = actor as BSCharacter;
  404. if (bsactor != null)
  405. {
  406. try
  407. {
  408. lock (PhysObjects)
  409. PhysObjects.Remove(bsactor.LocalID);
  410. // Remove kludge someday
  411. lock (m_avatars)
  412. m_avatars.Remove(bsactor);
  413. }
  414. catch (Exception e)
  415. {
  416. m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
  417. }
  418. bsactor.Destroy();
  419. // bsactor.dispose();
  420. }
  421. else
  422. {
  423. m_log.ErrorFormat("{0}: Requested to remove avatar that is not a BSCharacter. ID={1}, type={2}",
  424. LogHeader, actor.LocalID, actor.GetType().Name);
  425. }
  426. }
  427. public override void RemovePrim(PhysicsActor prim)
  428. {
  429. if (!m_initialized) return;
  430. BSPhysObject bsprim = prim as BSPhysObject;
  431. if (bsprim != null)
  432. {
  433. DetailLog("{0},RemovePrim,call", bsprim.LocalID);
  434. // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
  435. try
  436. {
  437. lock (PhysObjects) PhysObjects.Remove(bsprim.LocalID);
  438. }
  439. catch (Exception e)
  440. {
  441. m_log.ErrorFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
  442. }
  443. bsprim.Destroy();
  444. // bsprim.dispose();
  445. }
  446. else
  447. {
  448. m_log.ErrorFormat("{0}: Attempt to remove prim that is not a BSPrim type.", LogHeader);
  449. }
  450. }
  451. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  452. Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
  453. {
  454. // m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
  455. if (!m_initialized) return null;
  456. // DetailLog("{0},BSScene.AddPrimShape,call", localID);
  457. BSPhysObject prim = new BSPrimLinkable(localID, primName, this, position, size, rotation, pbs, isPhysical);
  458. lock (PhysObjects) PhysObjects.Add(localID, prim);
  459. return prim;
  460. }
  461. // This is a call from the simulator saying that some physical property has been updated.
  462. // The BulletSim driver senses the changing of relevant properties so this taint
  463. // information call is not needed.
  464. public override void AddPhysicsActorTaint(PhysicsActor prim) { }
  465. #endregion // Prim and Avatar addition and removal
  466. #region Simulation
  467. // Call from the simulator to send physics information to the simulator objects.
  468. // This pushes all the collision and property update events into the objects in
  469. // the simulator and, since it is on the heartbeat thread, there is an implicit
  470. // locking of those data structures from other heartbeat events.
  471. // If the physics engine is running on a separate thread, the update information
  472. // will be in the ObjectsWithCollions and ObjectsWithUpdates structures.
  473. public override float Simulate(float timeStep)
  474. {
  475. if (!BSParam.UseSeparatePhysicsThread)
  476. {
  477. DoPhysicsStep(timeStep);
  478. }
  479. return SendUpdatesToSimulator(timeStep);
  480. }
  481. // Call the physics engine to do one 'timeStep' and collect collisions and updates
  482. // into ObjectsWithCollisions and ObjectsWithUpdates data structures.
  483. private void DoPhysicsStep(float timeStep)
  484. {
  485. // prevent simulation until we've been initialized
  486. if (!m_initialized) return;
  487. LastTimeStep = timeStep;
  488. int updatedEntityCount = 0;
  489. int collidersCount = 0;
  490. int beforeTime = Util.EnvironmentTickCount();
  491. int simTime = 0;
  492. int numTaints = _taintOperations.Count;
  493. InTaintTime = true; // Only used for debugging so locking is not necessary.
  494. // update the prim states while we know the physics engine is not busy
  495. ProcessTaints();
  496. // Some of the physical objects requre individual, pre-step calls
  497. // (vehicles and avatar movement, in particular)
  498. TriggerPreStepEvent(timeStep);
  499. // the prestep actions might have added taints
  500. numTaints += _taintOperations.Count;
  501. ProcessTaints();
  502. InTaintTime = false; // Only used for debugging so locking is not necessary.
  503. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  504. // Only enable this in a limited test world with few objects.
  505. if (m_physicsPhysicalDumpEnabled)
  506. PE.DumpAllInfo(World);
  507. // step the physical world one interval
  508. m_simulationStep++;
  509. int numSubSteps = 0;
  510. try
  511. {
  512. numSubSteps = PE.PhysicsStep(World, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out collidersCount);
  513. }
  514. catch (Exception e)
  515. {
  516. m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}",
  517. LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e);
  518. DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}",
  519. DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
  520. updatedEntityCount = 0;
  521. collidersCount = 0;
  522. }
  523. // Make the physics engine dump useful statistics periodically
  524. if (PhysicsMetricDumpFrames != 0 && ((m_simulationStep % PhysicsMetricDumpFrames) == 0))
  525. PE.DumpPhysicsStatistics(World);
  526. // Get a value for 'now' so all the collision and update routines don't have to get their own.
  527. SimulationNowTime = Util.EnvironmentTickCount();
  528. // Send collision information to the colliding objects. The objects decide if the collision
  529. // is 'real' (like linksets don't collide with themselves) and the individual objects
  530. // know if the simulator has subscribed to collisions.
  531. lock (CollisionLock)
  532. {
  533. if (collidersCount > 0)
  534. {
  535. for (int ii = 0; ii < collidersCount; ii++)
  536. {
  537. uint cA = m_collisionArray[ii].aID;
  538. uint cB = m_collisionArray[ii].bID;
  539. Vector3 point = m_collisionArray[ii].point;
  540. Vector3 normal = m_collisionArray[ii].normal;
  541. float penetration = m_collisionArray[ii].penetration;
  542. SendCollision(cA, cB, point, normal, penetration);
  543. SendCollision(cB, cA, point, -normal, penetration);
  544. }
  545. }
  546. }
  547. // If any of the objects had updated properties, tell the managed objects about the update
  548. // and remember that there was a change so it will be passed to the simulator.
  549. lock (UpdateLock)
  550. {
  551. if (updatedEntityCount > 0)
  552. {
  553. for (int ii = 0; ii < updatedEntityCount; ii++)
  554. {
  555. EntityProperties entprop = m_updateArray[ii];
  556. BSPhysObject pobj;
  557. if (PhysObjects.TryGetValue(entprop.ID, out pobj))
  558. {
  559. if (pobj.IsInitialized)
  560. pobj.UpdateProperties(entprop);
  561. }
  562. }
  563. }
  564. }
  565. // Some actors want to know when the simulation step is complete.
  566. TriggerPostStepEvent(timeStep);
  567. simTime = Util.EnvironmentTickCountSubtract(beforeTime);
  568. if (PhysicsLogging.Enabled)
  569. {
  570. DetailLog("{0},DoPhysicsStep,complete,frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}",
  571. DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps,
  572. updatedEntityCount, collidersCount, ObjectsWithCollisions.Count);
  573. }
  574. // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
  575. // Only enable this in a limited test world with few objects.
  576. if (m_physicsPhysicalDumpEnabled)
  577. PE.DumpAllInfo(World);
  578. // The physics engine returns the number of milliseconds it simulated this call.
  579. // These are summed and normalized to one second and divided by 1000 to give the reported physics FPS.
  580. // Multiply by a fixed nominal frame rate to give a rate similar to the simulator (usually 55).
  581. m_simulatedTime += (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate;
  582. }
  583. // Called by a BSPhysObject to note that it has changed properties and this information
  584. // should be passed up to the simulator at the proper time.
  585. // Note: this is called by the BSPhysObject from invocation via DoPhysicsStep() above so
  586. // this is is under UpdateLock.
  587. public void PostUpdate(BSPhysObject updatee)
  588. {
  589. ObjectsWithUpdates.Add(updatee);
  590. }
  591. // The simulator thinks it is physics time so return all the collisions and position
  592. // updates that were collected in actual physics simulation.
  593. private float SendUpdatesToSimulator(float timeStep)
  594. {
  595. if (!m_initialized) return 5.0f;
  596. DetailLog("{0},SendUpdatesToSimulator,collisions={1},updates={2},simedTime={3}",
  597. BSScene.DetailLogZero, ObjectsWithCollisions.Count, ObjectsWithUpdates.Count, m_simulatedTime);
  598. // Push the collisions into the simulator.
  599. lock (CollisionLock)
  600. {
  601. if (ObjectsWithCollisions.Count > 0)
  602. {
  603. foreach (BSPhysObject bsp in ObjectsWithCollisions)
  604. if (!bsp.SendCollisions())
  605. {
  606. // If the object is done colliding, see that it's removed from the colliding list
  607. ObjectsWithNoMoreCollisions.Add(bsp);
  608. }
  609. }
  610. // This is a kludge to get avatar movement updates.
  611. // The simulator expects collisions for avatars even if there are have been no collisions.
  612. // The event updates avatar animations and stuff.
  613. // If you fix avatar animation updates, remove this overhead and let normal collision processing happen.
  614. foreach (BSPhysObject bsp in m_avatars)
  615. if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice
  616. bsp.SendCollisions();
  617. // Objects that are done colliding are removed from the ObjectsWithCollisions list.
  618. // Not done above because it is inside an iteration of ObjectWithCollisions.
  619. // This complex collision processing is required to create an empty collision
  620. // event call after all real collisions have happened on an object. This allows
  621. // the simulator to generate the 'collision end' event.
  622. if (ObjectsWithNoMoreCollisions.Count > 0)
  623. {
  624. foreach (BSPhysObject po in ObjectsWithNoMoreCollisions)
  625. ObjectsWithCollisions.Remove(po);
  626. ObjectsWithNoMoreCollisions.Clear();
  627. }
  628. }
  629. // Call the simulator for each object that has physics property updates.
  630. HashSet<BSPhysObject> updatedObjects = null;
  631. lock (UpdateLock)
  632. {
  633. if (ObjectsWithUpdates.Count > 0)
  634. {
  635. updatedObjects = ObjectsWithUpdates;
  636. ObjectsWithUpdates = new HashSet<BSPhysObject>();
  637. }
  638. }
  639. if (updatedObjects != null)
  640. {
  641. foreach (BSPhysObject obj in updatedObjects)
  642. {
  643. obj.RequestPhysicsterseUpdate();
  644. }
  645. updatedObjects.Clear();
  646. }
  647. // Return the framerate simulated to give the above returned results.
  648. // (Race condition here but this is just bookkeeping so rare mistakes do not merit a lock).
  649. float simTime = m_simulatedTime;
  650. m_simulatedTime = 0f;
  651. return simTime;
  652. }
  653. // Something has collided
  654. private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
  655. {
  656. if (localID <= TerrainManager.HighestTerrainID)
  657. {
  658. return; // don't send collisions to the terrain
  659. }
  660. BSPhysObject collider;
  661. if (!PhysObjects.TryGetValue(localID, out collider))
  662. {
  663. // If the object that is colliding cannot be found, just ignore the collision.
  664. DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith);
  665. return;
  666. }
  667. // Note: the terrain is not in the physical object list so 'collidee' can be null when Collide() is called.
  668. BSPhysObject collidee = null;
  669. PhysObjects.TryGetValue(collidingWith, out collidee);
  670. // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
  671. if (collider.IsInitialized)
  672. {
  673. if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration))
  674. {
  675. // If a collision was 'good', remember to send it to the simulator
  676. ObjectsWithCollisions.Add(collider);
  677. }
  678. }
  679. return;
  680. }
  681. public void BulletSPluginPhysicsThread()
  682. {
  683. while (m_initialized)
  684. {
  685. int beginSimulationRealtimeMS = Util.EnvironmentTickCount();
  686. DoPhysicsStep(BSParam.PhysicsTimeStep);
  687. int simulationRealtimeMS = Util.EnvironmentTickCountSubtract(beginSimulationRealtimeMS);
  688. int simulationTimeVsRealtimeDifferenceMS = ((int)(BSParam.PhysicsTimeStep*1000f)) - simulationRealtimeMS;
  689. if (simulationTimeVsRealtimeDifferenceMS > 0)
  690. {
  691. // The simulation of the time interval took less than realtime.
  692. // Do a sleep for the rest of realtime.
  693. Thread.Sleep(simulationTimeVsRealtimeDifferenceMS);
  694. }
  695. else
  696. {
  697. // The simulation took longer than realtime.
  698. // Do some scaling of simulation time.
  699. // TODO.
  700. DetailLog("{0},BulletSPluginPhysicsThread,longerThanRealtime={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS);
  701. }
  702. }
  703. }
  704. #endregion // Simulation
  705. public override void GetResults() { }
  706. #region Terrain
  707. public override void SetTerrain(float[] heightMap) {
  708. TerrainManager.SetTerrain(heightMap);
  709. }
  710. public override void SetWaterLevel(float baseheight)
  711. {
  712. SimpleWaterLevel = baseheight;
  713. }
  714. public override void DeleteTerrain()
  715. {
  716. // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
  717. }
  718. // Although no one seems to check this, I do support combining.
  719. public override bool SupportsCombining()
  720. {
  721. return TerrainManager.SupportsCombining();
  722. }
  723. // This call says I am a child to region zero in a mega-region. 'pScene' is that
  724. // of region zero, 'offset' is my offset from regions zero's origin, and
  725. // 'extents' is the largest XY that is handled in my region.
  726. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  727. {
  728. TerrainManager.Combine(pScene, offset, extents);
  729. }
  730. // Unhook all the combining that I know about.
  731. public override void UnCombine(PhysicsScene pScene)
  732. {
  733. TerrainManager.UnCombine(pScene);
  734. }
  735. #endregion // Terrain
  736. public override Dictionary<uint, float> GetTopColliders()
  737. {
  738. Dictionary<uint, float> topColliders;
  739. lock (PhysObjects)
  740. {
  741. foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
  742. {
  743. kvp.Value.ComputeCollisionScore();
  744. }
  745. List<BSPhysObject> orderedPrims = new List<BSPhysObject>(PhysObjects.Values);
  746. orderedPrims.OrderByDescending(p => p.CollisionScore);
  747. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  748. }
  749. return topColliders;
  750. }
  751. public override bool IsThreaded { get { return false; } }
  752. #region Extensions
  753. public override object Extension(string pFunct, params object[] pParams)
  754. {
  755. DetailLog("{0} BSScene.Extension,op={1}", DetailLogZero, pFunct);
  756. return base.Extension(pFunct, pParams);
  757. }
  758. #endregion // Extensions
  759. #region Taints
  760. // The simulation execution order is:
  761. // Simulate()
  762. // DoOneTimeTaints
  763. // TriggerPreStepEvent
  764. // DoOneTimeTaints
  765. // Step()
  766. // ProcessAndSendToSimulatorCollisions
  767. // ProcessAndSendToSimulatorPropertyUpdates
  768. // TriggerPostStepEvent
  769. // Calls to the PhysicsActors can't directly call into the physics engine
  770. // because it might be busy. We delay changes to a known time.
  771. // We rely on C#'s closure to save and restore the context for the delegate.
  772. public void TaintedObject(string pOriginator, string pIdent, TaintCallback pCallback)
  773. {
  774. TaintedObject(false /*inTaintTime*/, pOriginator, pIdent, pCallback);
  775. }
  776. public void TaintedObject(uint pOriginator, String pIdent, TaintCallback pCallback)
  777. {
  778. TaintedObject(false /*inTaintTime*/, m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback);
  779. }
  780. public void TaintedObject(bool inTaintTime, String pIdent, TaintCallback pCallback)
  781. {
  782. TaintedObject(inTaintTime, BSScene.DetailLogZero, pIdent, pCallback);
  783. }
  784. public void TaintedObject(bool inTaintTime, uint pOriginator, String pIdent, TaintCallback pCallback)
  785. {
  786. TaintedObject(inTaintTime, m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback);
  787. }
  788. // Sometimes a potentially tainted operation can be used in and out of taint time.
  789. // This routine executes the command immediately if in taint-time otherwise it is queued.
  790. public void TaintedObject(bool inTaintTime, string pOriginator, string pIdent, TaintCallback pCallback)
  791. {
  792. if (!m_initialized) return;
  793. if (inTaintTime)
  794. pCallback();
  795. else
  796. {
  797. lock (_taintLock)
  798. {
  799. _taintOperations.Add(new TaintCallbackEntry(pOriginator, pIdent, pCallback));
  800. }
  801. }
  802. }
  803. private void TriggerPreStepEvent(float timeStep)
  804. {
  805. PreStepAction actions = BeforeStep;
  806. if (actions != null)
  807. actions(timeStep);
  808. }
  809. private void TriggerPostStepEvent(float timeStep)
  810. {
  811. PostStepAction actions = AfterStep;
  812. if (actions != null)
  813. actions(timeStep);
  814. }
  815. // When someone tries to change a property on a BSPrim or BSCharacter, the object queues
  816. // a callback into itself to do the actual property change. That callback is called
  817. // here just before the physics engine is called to step the simulation.
  818. public void ProcessTaints()
  819. {
  820. ProcessRegularTaints();
  821. ProcessPostTaintTaints();
  822. }
  823. private void ProcessRegularTaints()
  824. {
  825. if (m_initialized && _taintOperations.Count > 0) // save allocating new list if there is nothing to process
  826. {
  827. // swizzle a new list into the list location so we can process what's there
  828. List<TaintCallbackEntry> oldList;
  829. lock (_taintLock)
  830. {
  831. oldList = _taintOperations;
  832. _taintOperations = new List<TaintCallbackEntry>();
  833. }
  834. foreach (TaintCallbackEntry tcbe in oldList)
  835. {
  836. try
  837. {
  838. DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", tcbe.originator, tcbe.ident); // DEBUG DEBUG DEBUG
  839. tcbe.callback();
  840. }
  841. catch (Exception e)
  842. {
  843. m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
  844. }
  845. }
  846. oldList.Clear();
  847. }
  848. }
  849. // Schedule an update to happen after all the regular taints are processed.
  850. // Note that new requests for the same operation ("ident") for the same object ("ID")
  851. // will replace any previous operation by the same object.
  852. public void PostTaintObject(String ident, uint ID, TaintCallback callback)
  853. {
  854. string IDAsString = ID.ToString();
  855. string uniqueIdent = ident + "-" + IDAsString;
  856. lock (_taintLock)
  857. {
  858. _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(IDAsString, uniqueIdent, callback);
  859. }
  860. return;
  861. }
  862. // Taints that happen after the normal taint processing but before the simulation step.
  863. private void ProcessPostTaintTaints()
  864. {
  865. if (m_initialized && _postTaintOperations.Count > 0)
  866. {
  867. Dictionary<string, TaintCallbackEntry> oldList;
  868. lock (_taintLock)
  869. {
  870. oldList = _postTaintOperations;
  871. _postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
  872. }
  873. foreach (KeyValuePair<string,TaintCallbackEntry> kvp in oldList)
  874. {
  875. try
  876. {
  877. DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG
  878. kvp.Value.callback();
  879. }
  880. catch (Exception e)
  881. {
  882. m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e);
  883. }
  884. }
  885. oldList.Clear();
  886. }
  887. }
  888. // Only used for debugging. Does not change state of anything so locking is not necessary.
  889. public bool AssertInTaintTime(string whereFrom)
  890. {
  891. if (!InTaintTime)
  892. {
  893. DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom);
  894. m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom);
  895. // Util.PrintCallStack(DetailLog);
  896. }
  897. return InTaintTime;
  898. }
  899. #endregion // Taints
  900. #region IPhysicsParameters
  901. // Get the list of parameters this physics engine supports
  902. public PhysParameterEntry[] GetParameterList()
  903. {
  904. BSParam.BuildParameterTable();
  905. return BSParam.SettableParameters;
  906. }
  907. // Set parameter on a specific or all instances.
  908. // Return 'false' if not able to set the parameter.
  909. // Setting the value in the m_params block will change the value the physics engine
  910. // will use the next time since it's pinned and shared memory.
  911. // Some of the values require calling into the physics engine to get the new
  912. // value activated ('terrainFriction' for instance).
  913. public bool SetPhysicsParameter(string parm, string val, uint localID)
  914. {
  915. bool ret = false;
  916. BSParam.ParameterDefnBase theParam;
  917. if (BSParam.TryGetParameter(parm, out theParam))
  918. {
  919. // Set the value in the C# code
  920. theParam.SetValue(this, val);
  921. // Optionally set the parameter in the unmanaged code
  922. if (theParam.HasSetOnObject)
  923. {
  924. // update all the localIDs specified
  925. // If the local ID is APPLY_TO_NONE, just change the default value
  926. // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
  927. // If the localID is a specific object, apply the parameter change to only that object
  928. List<uint> objectIDs = new List<uint>();
  929. switch (localID)
  930. {
  931. case PhysParameterEntry.APPLY_TO_NONE:
  932. // This will cause a call into the physical world if some operation is specified (SetOnObject).
  933. objectIDs.Add(TERRAIN_ID);
  934. TaintedUpdateParameter(parm, objectIDs, val);
  935. break;
  936. case PhysParameterEntry.APPLY_TO_ALL:
  937. lock (PhysObjects) objectIDs = new List<uint>(PhysObjects.Keys);
  938. TaintedUpdateParameter(parm, objectIDs, val);
  939. break;
  940. default:
  941. // setting only one localID
  942. objectIDs.Add(localID);
  943. TaintedUpdateParameter(parm, objectIDs, val);
  944. break;
  945. }
  946. }
  947. ret = true;
  948. }
  949. return ret;
  950. }
  951. // schedule the actual updating of the paramter to when the phys engine is not busy
  952. private void TaintedUpdateParameter(string parm, List<uint> lIDs, string val)
  953. {
  954. string xval = val;
  955. List<uint> xlIDs = lIDs;
  956. string xparm = parm;
  957. TaintedObject(DetailLogZero, "BSScene.UpdateParameterSet", delegate() {
  958. BSParam.ParameterDefnBase thisParam;
  959. if (BSParam.TryGetParameter(xparm, out thisParam))
  960. {
  961. if (thisParam.HasSetOnObject)
  962. {
  963. foreach (uint lID in xlIDs)
  964. {
  965. BSPhysObject theObject = null;
  966. if (PhysObjects.TryGetValue(lID, out theObject))
  967. thisParam.SetOnObject(this, theObject);
  968. }
  969. }
  970. }
  971. });
  972. }
  973. // Get parameter.
  974. // Return 'false' if not able to get the parameter.
  975. public bool GetPhysicsParameter(string parm, out string value)
  976. {
  977. string val = String.Empty;
  978. bool ret = false;
  979. BSParam.ParameterDefnBase theParam;
  980. if (BSParam.TryGetParameter(parm, out theParam))
  981. {
  982. val = theParam.GetValue(this);
  983. ret = true;
  984. }
  985. value = val;
  986. return ret;
  987. }
  988. #endregion IPhysicsParameters
  989. // Invoke the detailed logger and output something if it's enabled.
  990. public void DetailLog(string msg, params Object[] args)
  991. {
  992. PhysicsLogging.Write(msg, args);
  993. }
  994. // Used to fill in the LocalID when there isn't one. It's the correct number of characters.
  995. public const string DetailLogZero = "0000000000";
  996. }
  997. }