clockwerk-opensim – Blame information for rev 1

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