| | | 1 | | //======================================================================= |
| | | 2 | | // GravitasWorldContext.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2026-present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | using System; |
| | | 9 | | using Chronicler.Hashing; |
| | | 10 | | using Chronicler.Timing; |
| | | 11 | | using FixedMathSharp; |
| | | 12 | | using Gravitas.CollisionHandling; |
| | | 13 | | using Gravitas.Diagnostics; |
| | | 14 | | using Gravitas.Queries; |
| | | 15 | | using Gravitas.Support; |
| | | 16 | | using GridForge.Grids; |
| | | 17 | | using GridForge.Grids.Topology; |
| | | 18 | | using SwiftCollections; |
| | | 19 | | |
| | | 20 | | namespace Gravitas; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Owns Gravitas runtime state for one explicit <see cref="GridWorld"/>. |
| | | 24 | | /// </summary> |
| | | 25 | | /// <remarks> |
| | | 26 | | /// Owns world lifetime, deterministic timing, physics registries, collision |
| | | 27 | | /// partitioning, queries, coroutines, and lifecycle hooks for one simulation. |
| | | 28 | | /// </remarks> |
| | | 29 | | /// <content>Owns world lifetime, context services, configuration and the host lifecycle.</content> |
| | | 30 | | public sealed partial class GravitasWorldContext : IDisposable |
| | | 31 | | { |
| | 1 | 32 | | private static readonly object _worldOwnershipLock = new(); |
| | | 33 | | |
| | 1 | 34 | | private static readonly SwiftDictionary<GridWorld, GravitasWorldContext> _worldOwners = new(); |
| | | 35 | | |
| | 10191 | 36 | | private readonly GravitasClock _clock = new(); |
| | | 37 | | |
| | 10191 | 38 | | private readonly GravitasLifecycleHooks _hooks = new(); |
| | | 39 | | |
| | | 40 | | private readonly bool _ownsWorld; |
| | | 41 | | |
| | | 42 | | private bool _disposed; |
| | | 43 | | |
| | | 44 | | private long _lateSimulateToken; |
| | | 45 | | |
| | | 46 | | private int _simulationPhaseDepth; |
| | | 47 | | |
| | | 48 | | private bool _fixedStepOpen; |
| | | 49 | | |
| | 312240 | 50 | | internal bool IsBetweenFixedSteps => !_disposed && !_fixedStepOpen && _simulationPhaseDepth == 0; |
| | | 51 | | |
| | 229157 | 52 | | internal void EnterSimulationPhase() => _simulationPhaseDepth++; |
| | | 53 | | |
| | 229157 | 54 | | internal void ExitSimulationPhase() => _simulationPhaseDepth--; |
| | | 55 | | |
| | | 56 | | internal void ThrowIfFixedStepMutationNotAllowed() |
| | | 57 | | { |
| | 11679 | 58 | | ChronicleGuard.ThrowIfTrue( |
| | 11679 | 59 | | _fixedStepOpen || _simulationPhaseDepth > 0, |
| | 11679 | 60 | | nameof(GravitasWorldContext), |
| | 11679 | 61 | | "Authoritative body roles, static poses, and loaded state can change only outside the Simulate-to-LateSimula |
| | 11649 | 62 | | } |
| | | 63 | | |
| | 10191 | 64 | | private GravitasWorldContext(GridWorld world, bool ownsWorld) |
| | | 65 | | { |
| | 10191 | 66 | | World = world; |
| | 10191 | 67 | | _ownsWorld = ownsWorld; |
| | 10191 | 68 | | Settings = PhysicsSettings.DefaultSettings(); |
| | 10191 | 69 | | Environment = PhysicsEnvironment.Default(Settings.FrameRate); |
| | 10191 | 70 | | CollisionScratch = new CollisionSatScratch(); |
| | 10191 | 71 | | Diagnostics = new GravitasDiagnosticSink(this); |
| | 10191 | 72 | | Constraints3D = new GravitasConstraint3DService(this); |
| | 10191 | 73 | | Constraints2D = new GravitasConstraint2DService(this); |
| | 10191 | 74 | | Collisions = new GravitasCollisionService(this); |
| | 10191 | 75 | | Collisions2D = new GravitasCollision2DService(this); |
| | 10191 | 76 | | Physics = new GravitasPhysicsService(this); |
| | 10191 | 77 | | Physics2D = new GravitasPhysics2DService(this); |
| | 10191 | 78 | | MixedCollisions = new GravitasMixedCollisionService(this); |
| | 10191 | 79 | | Query2D = new GravitasQuery2DService(this); |
| | 10191 | 80 | | Query3D = new GravitasQuery3DService(this); |
| | 10191 | 81 | | QueryMixed = new GravitasQueryMixedService(this); |
| | 10191 | 82 | | Coroutines = new GravitasCoroutineService(this); |
| | 10191 | 83 | | _observedGridChangeSequence = World.ChangeSequence; |
| | 10191 | 84 | | World.OnChangeCommitted += OnQueryPartitionWorldChange; |
| | 10191 | 85 | | Settings.Owner = this; |
| | 10191 | 86 | | } |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Gets the explicit GridForge world owned or referenced by this context. |
| | | 90 | | /// </summary> |
| | | 91 | | public GridWorld World { get; } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Gets this context's world-local physics settings. |
| | | 95 | | /// </summary> |
| | | 96 | | public PhysicsSettings Settings { get; private set; } |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// Gets this context's world-local physical environment values. |
| | | 100 | | /// </summary> |
| | | 101 | | public PhysicsEnvironment Environment { get; } |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Gets this context's world-local collision partitioning service. |
| | | 105 | | /// </summary> |
| | | 106 | | public GravitasCollisionService Collisions { get; } |
| | | 107 | | |
| | | 108 | | /// <summary> |
| | | 109 | | /// Gets this context's world-local pure 2D collision partitioning service. |
| | | 110 | | /// </summary> |
| | | 111 | | public GravitasCollision2DService Collisions2D { get; } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Gets this context's world-local physics registration and pair service. |
| | | 115 | | /// </summary> |
| | | 116 | | public GravitasPhysicsService Physics { get; } |
| | | 117 | | |
| | | 118 | | /// <summary> |
| | | 119 | | /// Gets this context's world-local pure 2D physics service. |
| | | 120 | | /// </summary> |
| | | 121 | | public GravitasPhysics2DService Physics2D { get; } |
| | | 122 | | |
| | | 123 | | internal GravitasMixedCollisionService MixedCollisions { get; } |
| | | 124 | | |
| | | 125 | | /// <summary> |
| | | 126 | | /// Gets this context's world-local pure 2D query service. |
| | | 127 | | /// </summary> |
| | | 128 | | public GravitasQuery2DService Query2D { get; } |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// Gets this context's world-local 3D query service. |
| | | 132 | | /// </summary> |
| | | 133 | | public GravitasQuery3DService Query3D { get; } |
| | | 134 | | |
| | | 135 | | /// <summary> |
| | | 136 | | /// Gets this context's explicit mixed 3D/2D query service. |
| | | 137 | | /// </summary> |
| | | 138 | | public GravitasQueryMixedService QueryMixed { get; } |
| | | 139 | | |
| | | 140 | | /// <summary> |
| | | 141 | | /// Gets this context's world-local lockstep coroutine service. |
| | | 142 | | /// </summary> |
| | | 143 | | public GravitasCoroutineService Coroutines { get; } |
| | | 144 | | |
| | | 145 | | /// <summary> |
| | | 146 | | /// Gets this context's deterministic diagnostic sink. |
| | | 147 | | /// </summary> |
| | | 148 | | public GravitasDiagnosticSink Diagnostics { get; } |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Gets this context's world-local 3D constraint and ragdoll service. |
| | | 152 | | /// </summary> |
| | | 153 | | public GravitasConstraint3DService Constraints3D { get; } |
| | | 154 | | |
| | | 155 | | /// <summary> |
| | | 156 | | /// Gets this context's world-local pure 2D constraint and ragdoll service. |
| | | 157 | | /// </summary> |
| | | 158 | | public GravitasConstraint2DService Constraints2D { get; } |
| | | 159 | | |
| | | 160 | | internal CollisionSatScratch CollisionScratch { get; } |
| | | 161 | | |
| | | 162 | | /// <summary> |
| | | 163 | | /// Gets whether this context has been disposed. |
| | | 164 | | /// </summary> |
| | 98 | 165 | | public bool IsDisposed => _disposed; |
| | | 166 | | |
| | | 167 | | /// <summary> |
| | | 168 | | /// Gets a representative grid cell edge for this context's world. |
| | | 169 | | /// </summary> |
| | | 170 | | public Fixed64 VoxelSize |
| | | 171 | | { |
| | | 172 | | get |
| | | 173 | | { |
| | 7 | 174 | | ThrowIfDisposed(); |
| | 7 | 175 | | return GridTopologyMetricUtility.GetRepresentativeCellEdge(World); |
| | | 176 | | } |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Gets this context's fixed simulation frame rate. |
| | | 181 | | /// </summary> |
| | | 182 | | public int FrameRate |
| | | 183 | | { |
| | | 184 | | get |
| | | 185 | | { |
| | 173199 | 186 | | ThrowIfDisposed(); |
| | 173199 | 187 | | return _clock.FrameRate; |
| | | 188 | | } |
| | | 189 | | } |
| | | 190 | | |
| | | 191 | | /// <summary> |
| | | 192 | | /// Gets this context's fixed simulation time step. |
| | | 193 | | /// </summary> |
| | | 194 | | public Fixed64 DeltaTime |
| | | 195 | | { |
| | | 196 | | get |
| | | 197 | | { |
| | 1689931 | 198 | | ThrowIfDisposed(); |
| | 1689931 | 199 | | return _clock.DeltaTime; |
| | | 200 | | } |
| | | 201 | | } |
| | | 202 | | |
| | | 203 | | /// <summary> |
| | | 204 | | /// Gets the reciprocal of this context's fixed simulation time step. |
| | | 205 | | /// </summary> |
| | | 206 | | public Fixed64 InvDeltaTime |
| | | 207 | | { |
| | | 208 | | get |
| | | 209 | | { |
| | 19262 | 210 | | ThrowIfDisposed(); |
| | 19262 | 211 | | return _clock.InvDeltaTime; |
| | | 212 | | } |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | /// <summary> |
| | | 216 | | /// Gets this context's simulated frame count. |
| | | 217 | | /// </summary> |
| | | 218 | | public long FrameCount |
| | | 219 | | { |
| | | 220 | | get |
| | | 221 | | { |
| | 926976 | 222 | | ThrowIfDisposed(); |
| | 926976 | 223 | | return _clock.FrameCount; |
| | | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | /// <summary> |
| | | 228 | | /// Gets elapsed simulation time, preserving the history of step-size changes. |
| | | 229 | | /// </summary> |
| | | 230 | | public ChronicleTimestamp ElapsedTime |
| | | 231 | | { |
| | | 232 | | get |
| | | 233 | | { |
| | 8438 | 234 | | ThrowIfDisposed(); |
| | 8438 | 235 | | return _clock.ElapsedTime; |
| | | 236 | | } |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Gets this context's accumulated visualization time. |
| | | 241 | | /// </summary> |
| | | 242 | | public Fixed64 AccumulatedTime |
| | | 243 | | { |
| | | 244 | | get |
| | | 245 | | { |
| | 1 | 246 | | ThrowIfDisposed(); |
| | 1 | 247 | | return _clock.AccumulatedTime; |
| | | 248 | | } |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | /// <summary> |
| | | 252 | | /// Gets whether this context's visualization accumulation will reset on the next visualize call. |
| | | 253 | | /// </summary> |
| | | 254 | | public bool ResetAccumulation |
| | | 255 | | { |
| | | 256 | | get |
| | | 257 | | { |
| | 7 | 258 | | ThrowIfDisposed(); |
| | 7 | 259 | | return _clock.ResetAccumulation; |
| | | 260 | | } |
| | | 261 | | } |
| | | 262 | | |
| | | 263 | | internal bool ResetAccumulationThisVisualize |
| | | 264 | | { |
| | | 265 | | get |
| | | 266 | | { |
| | 46 | 267 | | ThrowIfDisposed(); |
| | 46 | 268 | | return _clock.ResetAccumulationThisVisualize; |
| | | 269 | | } |
| | | 270 | | } |
| | | 271 | | |
| | 430743 | 272 | | internal long LateSimulateToken => _lateSimulateToken; |
| | | 273 | | |
| | | 274 | | internal object CaptureClockLifetime() |
| | | 275 | | { |
| | 676 | 276 | | ThrowIfDisposed(); |
| | 676 | 277 | | return _clock.Lifetime; |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | internal void ValidateClockLifetime(object lifetime) |
| | | 281 | | { |
| | 1096 | 282 | | ThrowIfDisposed(); |
| | 1093 | 283 | | ChronicleGuard.ThrowIfTrue(!ReferenceEquals(lifetime, _clock.Lifetime), |
| | 1093 | 284 | | nameof(GravitasWorldContext), "The wait belongs to a previous simulation lifetime."); |
| | 1090 | 285 | | } |
| | | 286 | | |
| | | 287 | | internal long GetDeadlineFrame(long framesFromNow) |
| | | 288 | | { |
| | 457 | 289 | | ThrowIfDisposed(); |
| | 457 | 290 | | return _clock.GetDeadlineFrame(framesFromNow); |
| | | 291 | | } |
| | | 292 | | |
| | | 293 | | /// <summary> |
| | | 294 | | /// Gets this context's visualization accumulation expressed in simulation frames. |
| | | 295 | | /// </summary> |
| | | 296 | | public Fixed64 ExpectedAccumulation |
| | | 297 | | { |
| | | 298 | | get |
| | | 299 | | { |
| | 19 | 300 | | ThrowIfDisposed(); |
| | 19 | 301 | | return _clock.ExpectedAccumulation; |
| | | 302 | | } |
| | | 303 | | } |
| | | 304 | | |
| | | 305 | | /// <summary> |
| | | 306 | | /// Computes a deterministic fixed-width hash of this context's replay-relevant physics state. |
| | | 307 | | /// </summary> |
| | | 308 | | /// <param name="mode">Selects whether diagnostic solver/cache state is included in addition to authoritative state. |
| | | 309 | | /// <returns>A deterministic hash suitable for lockstep replay conformance checks.</returns> |
| | | 310 | | /// <remarks> |
| | | 311 | | /// The hash includes context settings, environment values, body state, collider shape/filter state, |
| | | 312 | | /// retained pair/contact state, and continuation-affecting CCD handoff state. It excludes host object |
| | | 313 | | /// identity, delegates, diagnostics buffers, debug draw data, query scratch buffers, and visualization |
| | | 314 | | /// interpolation caches. |
| | | 315 | | /// </remarks> |
| | | 316 | | public ChronicleHash ComputeReplayHash( |
| | | 317 | | GravitasReplayHashMode mode = GravitasReplayHashMode.Authoritative) |
| | | 318 | | { |
| | 3875 | 319 | | ThrowIfDisposed(); |
| | 3875 | 320 | | return GravitasReplayHashService.Compute(this, mode); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | /// <summary> |
| | | 324 | | /// Attaches a context to a host-owned <see cref="GridWorld"/>. |
| | | 325 | | /// </summary> |
| | | 326 | | /// <param name="world">The active world to bind.</param> |
| | | 327 | | /// <param name="takeOwnership">True when disposing this context should dispose the supplied world.</param> |
| | | 328 | | /// <returns>A context bound to <paramref name="world"/>.</returns> |
| | | 329 | | public static GravitasWorldContext Attach(GridWorld world, bool takeOwnership = false) |
| | | 330 | | { |
| | 10 | 331 | | ChronicleGuard.ThrowIfNull(world, nameof(world)); |
| | 9 | 332 | | return CreateRegistered(world, takeOwnership); |
| | | 333 | | } |
| | | 334 | | |
| | | 335 | | /// <summary> |
| | | 336 | | /// Creates a context with an owned <see cref="GridWorld"/>. |
| | | 337 | | /// </summary> |
| | | 338 | | /// <param name="spatialGridCellSize">Ordinary-grid spatial lookup cell size for the created world.</param> |
| | | 339 | | /// <returns>A context that owns its created world.</returns> |
| | | 340 | | public static GravitasWorldContext CreateOwned( |
| | | 341 | | int spatialGridCellSize = GridWorld.DefaultSpatialGridCellSize) |
| | | 342 | | { |
| | 10185 | 343 | | return CreateRegistered( |
| | 10185 | 344 | | new GridWorld(spatialGridCellSize), |
| | 10185 | 345 | | ownsWorld: true); |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | /// <summary> |
| | | 349 | | /// Advances this context's deterministic simulation clock and ordered simulate hooks. |
| | | 350 | | /// </summary> |
| | | 351 | | /// <exception cref="InvalidOperationException"> |
| | | 352 | | /// The frame counter or required late-simulation phase counter is exhausted. |
| | | 353 | | /// </exception> |
| | | 354 | | /// <exception cref="OverflowException">The next elapsed timestamp is unrepresentable.</exception> |
| | | 355 | | /// <remarks>Timing exhaustion rejects before this call changes world state.</remarks> |
| | | 356 | | public void Simulate() |
| | | 357 | | { |
| | 70971 | 358 | | ThrowIfDisposed(); |
| | 70971 | 359 | | PhysicsRuntimeMode runtimeMode = Settings.RuntimeMode; |
| | 70971 | 360 | | if ((runtimeMode.Runs3D() && Physics.SimulatePhysics) |
| | 70971 | 361 | | || (runtimeMode.Runs2D() && Physics2D.SimulatePhysics) |
| | 70971 | 362 | | || runtimeMode.RunsMixedContacts()) |
| | 70968 | 363 | | ThrowIfLateSimulateTokenExhausted(); |
| | | 364 | | // Clock exhaustion must reject before opening the containing fixed step. |
| | 70969 | 365 | | _clock.Simulate(); |
| | 70967 | 366 | | RefreshQueryPartitions(); |
| | 70967 | 367 | | _fixedStepOpen = true; |
| | 70967 | 368 | | EnterSimulationPhase(); |
| | | 369 | | try |
| | | 370 | | { |
| | 70967 | 371 | | if (runtimeMode.Runs3D()) |
| | 62982 | 372 | | Physics.Simulate(); |
| | 70967 | 373 | | if (runtimeMode.Runs2D()) |
| | 23868 | 374 | | Physics2D.Simulate(); |
| | 70967 | 375 | | if (runtimeMode.RunsMixedContacts()) |
| | 15810 | 376 | | MixedCollisions.Simulate(); |
| | | 377 | | |
| | 70967 | 378 | | Coroutines.Simulate(); |
| | 70967 | 379 | | _hooks.InvokeSimulate(); |
| | 70962 | 380 | | } |
| | 5 | 381 | | catch |
| | | 382 | | { |
| | 5 | 383 | | _fixedStepOpen = false; |
| | 5 | 384 | | throw; |
| | | 385 | | } |
| | | 386 | | finally |
| | | 387 | | { |
| | 70967 | 388 | | ExitSimulationPhase(); |
| | 70967 | 389 | | } |
| | 70962 | 390 | | } |
| | | 391 | | |
| | | 392 | | /// <summary> |
| | | 393 | | /// Runs this context's late-simulation step. |
| | | 394 | | /// </summary> |
| | | 395 | | /// <exception cref="InvalidOperationException"> |
| | | 396 | | /// The independent late-simulation phase counter is exhausted. Rejection occurs |
| | | 397 | | /// before this call changes world state. |
| | | 398 | | /// </exception> |
| | | 399 | | /// <exception cref="OverflowException"> |
| | | 400 | | /// A body position cannot be represented. Earlier step work may already have advanced; |
| | | 401 | | /// stop and restore a known state before continuing. |
| | | 402 | | /// </exception> |
| | | 403 | | public void LateSimulate() |
| | | 404 | | { |
| | 71317 | 405 | | ThrowIfDisposed(); |
| | 71317 | 406 | | PhysicsRuntimeMode runtimeMode = Settings.RuntimeMode; |
| | 71317 | 407 | | bool willRun3D = runtimeMode.Runs3D() && Physics.SimulatePhysics; |
| | 71317 | 408 | | bool willRun2D = runtimeMode.Runs2D() && Physics2D.SimulatePhysics; |
| | 71317 | 409 | | bool willRunMixed = runtimeMode.RunsMixedContacts(); |
| | 71317 | 410 | | if (willRun3D || willRun2D || willRunMixed) |
| | 71314 | 411 | | AdvanceLateSimulateToken(); |
| | 71315 | 412 | | RefreshQueryPartitions(); |
| | 71315 | 413 | | _fixedStepOpen = true; |
| | 71315 | 414 | | EnterSimulationPhase(); |
| | | 415 | | try |
| | | 416 | | { |
| | 71315 | 417 | | _clock.LateSimulate(); |
| | 71315 | 418 | | if (willRun3D) |
| | 63058 | 419 | | Physics.PrepareContinuousCollisionFrame(); |
| | 71312 | 420 | | if (willRun2D) |
| | 24304 | 421 | | Physics2D.PrepareContinuousCollisionFrame(); |
| | 71309 | 422 | | bool ran3D = willRun3D |
| | 71309 | 423 | | && Physics.BeginLateSimulateBodies(continuousCollisionFramePrepared: true); |
| | 71308 | 424 | | bool ran2D = willRun2D |
| | 71308 | 425 | | && Physics2D.BeginLateSimulateBodies(continuousCollisionFramePrepared: true); |
| | 71307 | 426 | | ProcessQueuedContinuousCollisionHandoffs(ran3D, ran2D); |
| | 71306 | 427 | | if (ran3D) |
| | 63051 | 428 | | Physics.CompleteLateSimulatePhysicsStep(deferSleep: willRunMixed); |
| | 71303 | 429 | | if (ran2D) |
| | 24299 | 430 | | Physics2D.CompleteLateSimulatePhysicsStep(deferSleep: willRunMixed); |
| | 71302 | 431 | | if (willRunMixed) |
| | | 432 | | { |
| | 15999 | 433 | | MixedCollisions.LateSimulate(); |
| | 15999 | 434 | | UpdateAutomaticSleep(ran3D, ran2D, mixed: true); |
| | | 435 | | } |
| | | 436 | | |
| | 71302 | 437 | | _hooks.InvokeLateSimulate(); |
| | 71299 | 438 | | } |
| | | 439 | | finally |
| | | 440 | | { |
| | 71315 | 441 | | ExitSimulationPhase(); |
| | 71315 | 442 | | _fixedStepOpen = false; |
| | 71315 | 443 | | } |
| | 71299 | 444 | | Physics.PublishCollisionPositionStates(); |
| | 71299 | 445 | | Physics2D.PublishCollisionPositionStates(); |
| | 71299 | 446 | | RefreshQueryPartitions(); |
| | 71299 | 447 | | } |
| | | 448 | | |
| | | 449 | | private void ProcessQueuedContinuousCollisionHandoffs(bool runs3D, bool runs2D) |
| | | 450 | | { |
| | 71307 | 451 | | if (!runs3D && !runs2D) |
| | 9 | 452 | | return; |
| | | 453 | | |
| | | 454 | | try |
| | | 455 | | { |
| | 71298 | 456 | | int iterationLimit = Settings.ContinuousCollisionMaxToiIterations; |
| | 71298 | 457 | | int remainingIterations = iterationLimit; |
| | 142748 | 458 | | for (int iteration = 0; iteration < iterationLimit && remainingIterations > 0; iteration++) |
| | | 459 | | { |
| | 71367 | 460 | | int processedIterations = 0; |
| | 71367 | 461 | | if (runs3D) |
| | | 462 | | { |
| | 63113 | 463 | | int usedIterations = Physics.ProcessQueuedContinuousCollisionHandoffs(remainingIterations); |
| | 63112 | 464 | | processedIterations += usedIterations; |
| | 63112 | 465 | | remainingIterations -= usedIterations; |
| | | 466 | | } |
| | | 467 | | |
| | 71366 | 468 | | if (remainingIterations > 0 && runs2D) |
| | | 469 | | { |
| | 24350 | 470 | | int usedIterations = Physics2D.ProcessQueuedContinuousCollisionHandoffs(remainingIterations); |
| | 24350 | 471 | | processedIterations += usedIterations; |
| | 24350 | 472 | | remainingIterations -= usedIterations; |
| | | 473 | | } |
| | | 474 | | |
| | 71366 | 475 | | if (processedIterations == 0) |
| | 71290 | 476 | | return; |
| | | 477 | | } |
| | | 478 | | |
| | 7 | 479 | | if (runs3D) |
| | 6 | 480 | | Physics.ProcessQueuedContinuousCollisionHandoffs(iterationBudget: 0); |
| | 7 | 481 | | if (runs2D) |
| | 6 | 482 | | Physics2D.ProcessQueuedContinuousCollisionHandoffs(iterationBudget: 0); |
| | 7 | 483 | | } |
| | 1 | 484 | | catch |
| | | 485 | | { |
| | 1 | 486 | | if (runs3D) |
| | 1 | 487 | | Physics.AbortContinuousCollisionHandoffFrame(); |
| | 1 | 488 | | if (runs2D) |
| | 1 | 489 | | Physics2D.AbortContinuousCollisionHandoffFrame(); |
| | 1 | 490 | | throw; |
| | | 491 | | } |
| | 71297 | 492 | | } |
| | | 493 | | |
| | | 494 | | internal void AdvanceLateSimulateToken() |
| | | 495 | | { |
| | 71667 | 496 | | ThrowIfLateSimulateTokenExhausted(); |
| | 71665 | 497 | | _lateSimulateToken++; |
| | 71665 | 498 | | } |
| | | 499 | | |
| | | 500 | | private void ThrowIfLateSimulateTokenExhausted() => |
| | 142635 | 501 | | ChronicleGuard.ThrowIfTrue(_lateSimulateToken == long.MaxValue, |
| | 142635 | 502 | | nameof(GravitasWorldContext), "The late-simulation phase counter is exhausted."); |
| | | 503 | | |
| | | 504 | | /// <summary> |
| | | 505 | | /// Runs this context's visualization accumulation step. |
| | | 506 | | /// </summary> |
| | | 507 | | public void Visualize() |
| | | 508 | | { |
| | 49 | 509 | | ThrowIfDisposed(); |
| | 49 | 510 | | _clock.Visualize(); |
| | 49 | 511 | | PhysicsRuntimeMode runtimeMode = Settings.RuntimeMode; |
| | 49 | 512 | | if (runtimeMode.Runs3D()) |
| | 38 | 513 | | Physics.Visualize(); |
| | 49 | 514 | | if (runtimeMode.Runs2D()) |
| | 22 | 515 | | Physics2D.Visualize(); |
| | 49 | 516 | | if (runtimeMode.RunsMixedContacts()) |
| | 6 | 517 | | MixedCollisions.Visualize(); |
| | | 518 | | |
| | 49 | 519 | | _hooks.InvokeVisualize(); |
| | 49 | 520 | | } |
| | | 521 | | |
| | | 522 | | /// <summary> |
| | | 523 | | /// Runs this context's host-owned late-visualization hook phase. |
| | | 524 | | /// </summary> |
| | | 525 | | public void LateVisualize() |
| | | 526 | | { |
| | 35 | 527 | | ThrowIfDisposed(); |
| | 35 | 528 | | _hooks.InvokeLateVisualize(); |
| | 35 | 529 | | } |
| | | 530 | | |
| | | 531 | | /// <summary> |
| | | 532 | | /// Resets this context's deterministic clock and context-local lifecycle hooks. |
| | | 533 | | /// </summary> |
| | | 534 | | public void Reset() |
| | | 535 | | { |
| | 113 | 536 | | ThrowIfDisposed(); |
| | 113 | 537 | | _lateSimulateToken = 0; |
| | 113 | 538 | | _clock.Reset(); |
| | 113 | 539 | | Constraints3D.Reset(); |
| | 113 | 540 | | Constraints2D.Reset(); |
| | 113 | 541 | | Collisions.Reset(); |
| | 113 | 542 | | Collisions2D.Reset(); |
| | 113 | 543 | | Physics.Reset(); |
| | 113 | 544 | | Physics2D.Reset(); |
| | 113 | 545 | | MixedCollisions.Reset(); |
| | 113 | 546 | | Query2D.Reset(); |
| | 113 | 547 | | Query3D.Reset(); |
| | 113 | 548 | | QueryMixed.Reset(); |
| | 113 | 549 | | Coroutines.Reset(); |
| | 113 | 550 | | Diagnostics.Reset(); |
| | 113 | 551 | | _hooks.InvokeReset(); |
| | 113 | 552 | | } |
| | | 553 | | |
| | | 554 | | /// <summary> |
| | | 555 | | /// Updates this context's fixed simulation frame rate. |
| | | 556 | | /// </summary> |
| | | 557 | | /// <param name="frameRate">The new frame rate. Must be within the supported physics settings range.</param> |
| | | 558 | | public void SetFrameRate(int frameRate) |
| | | 559 | | { |
| | 3315 | 560 | | ThrowIfDisposed(); |
| | 3315 | 561 | | Settings.SetFrameRate(frameRate); |
| | 3314 | 562 | | _clock.SetFrameRate(frameRate); |
| | 3314 | 563 | | _hooks.InvokeFrameRateChanged(); |
| | 3314 | 564 | | } |
| | | 565 | | |
| | | 566 | | /// <summary> |
| | | 567 | | /// Applies context-local settings and synchronizes frame-derived clock state. |
| | | 568 | | /// </summary> |
| | | 569 | | /// <param name="settings">The settings instance to own.</param> |
| | | 570 | | public void ApplySettings(PhysicsSettings settings) |
| | | 571 | | { |
| | 916 | 572 | | ThrowIfDisposed(); |
| | 916 | 573 | | ChronicleGuard.ThrowIfNull(settings, nameof(settings)); |
| | 916 | 574 | | ChronicleGuard.ThrowIfTrue(settings.Owner != null && !ReferenceEquals(settings.Owner, this), |
| | 916 | 575 | | nameof(settings), "Physics settings are already owned by another context."); |
| | 915 | 576 | | ValidateMixedGeometry(settings.RuntimeMode, settings.Mixed2DHalfThickness); |
| | 912 | 577 | | Settings.Owner = null; |
| | 912 | 578 | | Settings = settings; |
| | 912 | 579 | | settings.Owner = this; |
| | 912 | 580 | | _clock.SetFrameRate(settings.FrameRate); |
| | 912 | 581 | | _hooks.InvokeFrameRateChanged(); |
| | 912 | 582 | | } |
| | | 583 | | |
| | | 584 | | internal void ValidateMixedGeometry(PhysicsRuntimeMode mode, Fixed64 halfThickness) |
| | | 585 | | { |
| | 6883 | 586 | | ThrowIfFixedStepMutationNotAllowed(); |
| | 6880 | 587 | | if (!mode.RunsMixedContacts()) |
| | 2859 | 588 | | return; |
| | 8052 | 589 | | for (int i = 0; i < Physics2D.ColliderCount; i++) |
| | 11 | 590 | | Physics2D.GetColliderByServiceIndex(i).ValidateMixedGeometry(halfThickness); |
| | 4015 | 591 | | } |
| | | 592 | | |
| | | 593 | | /// <summary> |
| | | 594 | | /// Counts complete steps in a duration using the current fixed step size. |
| | | 595 | | /// </summary> |
| | | 596 | | /// <param name="duration">A nonnegative duration in seconds.</param> |
| | | 597 | | /// <returns>The complete-step count, rounded down using exact raw-unit division.</returns> |
| | | 598 | | /// <remarks>This is not a historical timestamp-to-frame lookup.</remarks> |
| | | 599 | | public long GetFrameCountForDuration(Fixed64 duration) |
| | | 600 | | { |
| | 216 | 601 | | ThrowIfDisposed(); |
| | 216 | 602 | | return _clock.GetFrameCountForDuration(duration); |
| | | 603 | | } |
| | | 604 | | |
| | | 605 | | internal IDisposable RegisterOnSimulate(string owner, int order, Action callback) |
| | | 606 | | { |
| | 18 | 607 | | ThrowIfDisposed(); |
| | 18 | 608 | | return _hooks.RegisterOnSimulate(owner, order, callback); |
| | | 609 | | } |
| | | 610 | | |
| | | 611 | | internal IDisposable RegisterOnLateSimulate(string owner, int order, Action callback) |
| | | 612 | | { |
| | 11 | 613 | | ThrowIfDisposed(); |
| | 11 | 614 | | return _hooks.RegisterOnLateSimulate(owner, order, callback); |
| | | 615 | | } |
| | | 616 | | |
| | | 617 | | internal IDisposable RegisterOnVisualize(string owner, int order, Action callback) |
| | | 618 | | { |
| | 1 | 619 | | ThrowIfDisposed(); |
| | 1 | 620 | | return _hooks.RegisterOnVisualize(owner, order, callback); |
| | | 621 | | } |
| | | 622 | | |
| | | 623 | | internal IDisposable RegisterOnLateVisualize(string owner, int order, Action callback) |
| | | 624 | | { |
| | 1 | 625 | | ThrowIfDisposed(); |
| | 1 | 626 | | return _hooks.RegisterOnLateVisualize(owner, order, callback); |
| | | 627 | | } |
| | | 628 | | |
| | | 629 | | internal IDisposable RegisterOnReset(string owner, int order, Action callback) |
| | | 630 | | { |
| | 2 | 631 | | ThrowIfDisposed(); |
| | 2 | 632 | | return _hooks.RegisterOnReset(owner, order, callback); |
| | | 633 | | } |
| | | 634 | | |
| | | 635 | | internal IDisposable RegisterOnFrameRateChanged(string owner, int order, Action callback) |
| | | 636 | | { |
| | 2 | 637 | | ThrowIfDisposed(); |
| | 2 | 638 | | return _hooks.RegisterOnFrameRateChanged(owner, order, callback); |
| | | 639 | | } |
| | | 640 | | |
| | | 641 | | /// <inheritdoc/> |
| | | 642 | | public void Dispose() |
| | | 643 | | { |
| | 10204 | 644 | | lock (_worldOwnershipLock) |
| | | 645 | | { |
| | 10204 | 646 | | if (_disposed) |
| | 13 | 647 | | return; |
| | | 648 | | |
| | 10191 | 649 | | Constraints3D.Reset(); |
| | 10191 | 650 | | Constraints2D.Reset(); |
| | 10191 | 651 | | Physics.ReleaseStaticSurfaces(); |
| | 10191 | 652 | | Physics2D.ReleaseStaticSurfaces(); |
| | 10191 | 653 | | World.OnChangeCommitted -= OnQueryPartitionWorldChange; |
| | 10191 | 654 | | Settings.Owner = null; |
| | 10191 | 655 | | _disposed = true; |
| | | 656 | | try |
| | | 657 | | { |
| | 10191 | 658 | | Coroutines.Deactivate(); |
| | 10191 | 659 | | } |
| | | 660 | | finally |
| | | 661 | | { |
| | | 662 | | try |
| | | 663 | | { |
| | 10191 | 664 | | if (_ownsWorld && World.IsActive) |
| | 10186 | 665 | | World.Dispose(); |
| | 10191 | 666 | | } |
| | | 667 | | finally |
| | | 668 | | { |
| | 10191 | 669 | | ReleaseWorldOwnership(this); |
| | 10191 | 670 | | } |
| | 10191 | 671 | | } |
| | | 672 | | } |
| | 10204 | 673 | | } |
| | | 674 | | |
| | | 675 | | private static GravitasWorldContext CreateRegistered(GridWorld world, bool ownsWorld) |
| | | 676 | | { |
| | 10194 | 677 | | lock (_worldOwnershipLock) |
| | | 678 | | { |
| | 10194 | 679 | | ChronicleGuard.ThrowIfTrue( |
| | 10194 | 680 | | !world.IsActive, |
| | 10194 | 681 | | nameof(GravitasWorldContext), |
| | 10194 | 682 | | "GravitasWorldContext requires an active GridWorld."); |
| | 10193 | 683 | | ThrowIfWorldOwned(world); |
| | 10191 | 684 | | GravitasWorldContext context = new(world, ownsWorld); |
| | 10191 | 685 | | _worldOwners[world] = context; |
| | 10191 | 686 | | return context; |
| | | 687 | | } |
| | 10191 | 688 | | } |
| | | 689 | | |
| | | 690 | | private static void ThrowIfWorldOwned(GridWorld world) |
| | | 691 | | { |
| | 10193 | 692 | | ChronicleGuard.ThrowIfTrue( |
| | 10193 | 693 | | _worldOwners.ContainsKey(world), |
| | 10193 | 694 | | nameof(GravitasWorldContext), |
| | 10193 | 695 | | "GridWorld is already attached to an active GravitasWorldContext."); |
| | 10191 | 696 | | } |
| | | 697 | | |
| | | 698 | | private static void ReleaseWorldOwnership(GravitasWorldContext context) |
| | | 699 | | { |
| | 10191 | 700 | | _worldOwners.Remove(context.World); |
| | 10191 | 701 | | } |
| | | 702 | | |
| | | 703 | | internal void ThrowIfDisposed() |
| | | 704 | | { |
| | 2972970 | 705 | | ChronicleGuard.ThrowIfDisposed(_disposed, nameof(GravitasWorldContext)); |
| | 2972961 | 706 | | ChronicleGuard.ThrowIfTrue( |
| | 2972961 | 707 | | !World.IsActive, |
| | 2972961 | 708 | | nameof(GravitasWorldContext), |
| | 2972961 | 709 | | "GravitasWorldContext is bound to an inactive GridWorld."); |
| | 2972961 | 710 | | } |
| | | 711 | | } |