BSScene.cs 44 KB

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