BSScene.cs 56 KB

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