BSScene.cs 51 KB

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