BSScene.cs 46 KB

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