BSScene.cs 63 KB

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