BSScene.cs 56 KB

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