| | | 1 | | //======================================================================= |
| | | 2 | | // PhysicsSettings.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 System.Runtime.CompilerServices; |
| | | 10 | | using System.Runtime.InteropServices; |
| | | 11 | | using FixedMathSharp; |
| | | 12 | | using Gravitas.Support; |
| | | 13 | | using SwiftCollections; |
| | | 14 | | |
| | | 15 | | namespace Gravitas; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Stores context-local configuration for deterministic physics simulation. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <content>Owns validated settings, their context binding and registered-layer defaults.</content> |
| | | 21 | | public sealed partial class PhysicsSettings |
| | | 22 | | { |
| | | 23 | | internal GravitasWorldContext? Owner; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Default fixed-step frame rate in simulation frames per second. |
| | | 27 | | /// </summary> |
| | | 28 | | public const int DefaultFrameRate = 32; |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Maximum supported fixed-step frame rate. |
| | | 32 | | /// </summary> |
| | | 33 | | /// <remarks> |
| | | 34 | | /// Higher values quantize <see cref="GravitasWorldContext.DeltaTime"/> at or below |
| | | 35 | | /// <see cref="Fixed64.Epsilon"/>, which would make integration and CCD degeneracy |
| | | 36 | | /// checks disagree about whether a step has meaningful duration. |
| | | 37 | | /// </remarks> |
| | | 38 | | public const int MaxResolvableFrameRate = (int)(FixedMath.ONE_L / (FixedMath.DEFAULT_TOLERANCE_L + 1)); |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Maximum number of physics layers represented by a layer mask. |
| | | 42 | | /// </summary> |
| | | 43 | | public const int MaxLayers = 32; |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Default number of frames an empty partition remains retained for reuse. |
| | | 47 | | /// </summary> |
| | | 48 | | public const int DefaultRetainedPartitionTimeToKillFrames = DefaultFrameRate * 10; |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Default maximum number of retained partitions checked per retirement sweep. |
| | | 52 | | /// </summary> |
| | | 53 | | public const int DefaultRetainedPartitionRetirementSweepBudget = 64; |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Default maximum same-frame time-of-impact iterations for continuous collision. |
| | | 57 | | /// </summary> |
| | | 58 | | public const int DefaultContinuousCollisionMaxToiIterations = 4; |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// Default projected-impulse iteration count for discrete 3D constraint islands. |
| | | 62 | | /// </summary> |
| | | 63 | | public const int DefaultDiscreteSolverIterations = 6; |
| | | 64 | | |
| | | 65 | | /// <summary> |
| | | 66 | | /// Default closing-speed threshold below which restitution is disabled. |
| | | 67 | | /// </summary> |
| | 1 | 68 | | public static readonly Fixed64 DefaultRestitutionVelocityThreshold = (Fixed64)0.25f; |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Default Y-axis half-thickness for 2D colliders embedded in mixed queries and contacts. |
| | | 72 | | /// </summary> |
| | 1 | 73 | | public static readonly Fixed64 DefaultMixed2DHalfThickness = Fixed64.Half; |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Default include mask used for ground and support checks. |
| | | 77 | | /// </summary> |
| | 1 | 78 | | public static readonly PhysicsLayerMask DefaultGroundCheckLayerMask = PhysicsLayerMask.FromLayer(new PhysicsLayer(0) |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Gets the fixed-step frame rate in simulation frames per second. |
| | | 82 | | /// </summary> |
| | | 83 | | public int FrameRate { get; private set; } |
| | | 84 | | |
| | | 85 | | private readonly bool[,] _collisionMatrix; |
| | | 86 | | |
| | | 87 | | /// <summary> |
| | | 88 | | /// Gets the layer-to-layer physical collision enablement matrix. |
| | | 89 | | /// </summary> |
| | 3036669 | 90 | | public bool[,] CollisionMatrix => _collisionMatrix; |
| | | 91 | | |
| | | 92 | | // Raw matrix edits have no setter notification. Retained joined contacts |
| | | 93 | | // need the exact eligible-layer bits, including enabled out-of-table layers. |
| | | 94 | | internal ulong GetCollisionLayerMask(PhysicsLayer row, PhysicsLayer column, |
| | | 95 | | bool watchRow, bool watchColumn) |
| | | 96 | | { |
| | 195290 | 97 | | ulong mask = 0; |
| | 390580 | 98 | | int rows = _collisionMatrix.GetLength(0), columns = _collisionMatrix.GetLength(1); |
| | | 99 | | // CLR rectangular arrays are contiguous in row-major order. Read the |
| | | 100 | | // same cells with one-dimensional bounds checks; empty tables enable all layers. |
| | 195290 | 101 | | ReadOnlySpan<bool> cells = _collisionMatrix.Length == 0 ? default |
| | 195290 | 102 | | : MemoryMarshal.CreateReadOnlySpan(ref _collisionMatrix[0, 0], _collisionMatrix.Length); |
| | 195290 | 103 | | if (watchRow) |
| | | 104 | | { |
| | 17827 | 105 | | uint enabled = uint.MaxValue; |
| | 17827 | 106 | | if (row.Index < rows) |
| | | 107 | | { |
| | 17651 | 108 | | ReadOnlySpan<bool> values = cells.Slice(row.Index * columns, Math.Min(columns, MaxLayers)); |
| | 73118 | 109 | | for (int layer = 0; layer < values.Length; layer++) |
| | 19707 | 110 | | if (!values[layer]) enabled &= ~(1u << layer); |
| | | 111 | | } |
| | 17827 | 112 | | mask = enabled; |
| | | 113 | | } |
| | 195290 | 114 | | if (watchColumn) |
| | | 115 | | { |
| | 177463 | 116 | | uint enabled = uint.MaxValue; |
| | 177463 | 117 | | if (column.Index < columns) |
| | 363142 | 118 | | for (int layer = 0; layer < Math.Min(rows, MaxLayers); layer++) |
| | 92170 | 119 | | if (!cells[layer * columns + column.Index]) enabled &= ~(1u << layer); |
| | 177463 | 120 | | mask |= (ulong)enabled << MaxLayers; |
| | | 121 | | } |
| | 195290 | 122 | | return mask; |
| | | 123 | | } |
| | | 124 | | |
| | | 125 | | /// <summary> |
| | | 126 | | /// Gets or sets whether reusable runtime collision objects are pooled. |
| | | 127 | | /// </summary> |
| | | 128 | | public bool PoolingEnabled { get; set; } = true; |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// Gets or sets the include mask used for ground and support checks. |
| | | 132 | | /// </summary> |
| | | 133 | | public PhysicsLayerMask GroundCheckLayerMask { get; set; } |
| | | 134 | | |
| | 11133 | 135 | | private int _retainedPartitionTimeToKillFrames = DefaultRetainedPartitionTimeToKillFrames; |
| | 11133 | 136 | | private int _retainedPartitionRetirementSweepBudget = DefaultRetainedPartitionRetirementSweepBudget; |
| | 11133 | 137 | | private ContinuousCollisionMode _defaultContinuousCollisionMode = ContinuousCollisionMode.Discrete; |
| | 11133 | 138 | | private int _continuousCollisionMaxToiIterations = DefaultContinuousCollisionMaxToiIterations; |
| | 11133 | 139 | | private int _discreteSolverIterations = DefaultDiscreteSolverIterations; |
| | 11133 | 140 | | private Fixed64 _restitutionVelocityThreshold = DefaultRestitutionVelocityThreshold; |
| | 11133 | 141 | | private PhysicsRuntimeMode _runtimeMode = PhysicsRuntimeMode.ThreeD; |
| | 11133 | 142 | | private Fixed64 _mixed2DHalfThickness = DefaultMixed2DHalfThickness; |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Gets or sets how many simulation frames an empty voxel partition should stay attached for fast reuse. |
| | | 146 | | /// A value of zero retires eligible partitions on the next retirement sweep. |
| | | 147 | | /// </summary> |
| | | 148 | | public int RetainedPartitionTimeToKillFrames |
| | | 149 | | { |
| | 107252 | 150 | | get => _retainedPartitionTimeToKillFrames; |
| | | 151 | | set |
| | | 152 | | { |
| | 35 | 153 | | ChronicleGuard.ThrowIfNegative(value, nameof(value)); |
| | 35 | 154 | | _retainedPartitionTimeToKillFrames = value; |
| | 35 | 155 | | } |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | /// <summary> |
| | | 159 | | /// Gets or sets the maximum retained partitions checked for retirement during one collision distribution step. |
| | | 160 | | /// A value of zero disables retirement sweeps. |
| | | 161 | | /// </summary> |
| | | 162 | | public int RetainedPartitionRetirementSweepBudget |
| | | 163 | | { |
| | 107252 | 164 | | get => _retainedPartitionRetirementSweepBudget; |
| | | 165 | | set |
| | | 166 | | { |
| | 41 | 167 | | ChronicleGuard.ThrowIfNegative(value, nameof(value)); |
| | 41 | 168 | | _retainedPartitionRetirementSweepBudget = value; |
| | 41 | 169 | | } |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary> |
| | | 173 | | /// Gets or sets the default tunneling policy used by bodies configured to inherit from the context. |
| | | 174 | | /// A context default of <see cref="ContinuousCollisionMode.Inherit"/> resolves to |
| | | 175 | | /// <see cref="ContinuousCollisionMode.Discrete"/>. |
| | | 176 | | /// </summary> |
| | | 177 | | /// <exception cref="ArgumentOutOfRangeException">The value is not a declared continuous-collision mode.</exception> |
| | | 178 | | public ContinuousCollisionMode DefaultContinuousCollisionMode |
| | | 179 | | { |
| | 165925 | 180 | | get => _defaultContinuousCollisionMode; |
| | | 181 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 182 | | set |
| | | 183 | | { |
| | 40 | 184 | | value.ThrowIfInvalid(nameof(value)); |
| | 36 | 185 | | _defaultContinuousCollisionMode = value; |
| | 36 | 186 | | } |
| | | 187 | | } |
| | | 188 | | |
| | | 189 | | /// <summary> |
| | | 190 | | /// Gets or sets the maximum same-frame continuous-collision TOI iterations one body or handoff queue may consume. |
| | | 191 | | /// </summary> |
| | | 192 | | public int ContinuousCollisionMaxToiIterations |
| | | 193 | | { |
| | 79666 | 194 | | get => _continuousCollisionMaxToiIterations; |
| | | 195 | | set |
| | | 196 | | { |
| | 113 | 197 | | ChronicleGuard.ThrowIfNegativeOrZero(value, nameof(value)); |
| | 111 | 198 | | _continuousCollisionMaxToiIterations = value; |
| | 111 | 199 | | } |
| | | 200 | | } |
| | | 201 | | |
| | | 202 | | /// <summary> |
| | | 203 | | /// Gets or sets the bounded projected-impulse iteration count used for 3D discrete |
| | | 204 | | /// contact and joint constraint islands. Multipoint 3D pairs use this budget |
| | | 205 | | /// even when alone; a single contact row uses the direct one-pass path. |
| | | 206 | | /// </summary> |
| | | 207 | | public int DiscreteSolverIterations |
| | | 208 | | { |
| | 34510 | 209 | | get => _discreteSolverIterations; |
| | | 210 | | set |
| | | 211 | | { |
| | 283 | 212 | | ChronicleGuard.ThrowIfNegativeOrZero(value, nameof(value)); |
| | 281 | 213 | | _discreteSolverIterations = value; |
| | 281 | 214 | | } |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | /// <summary> |
| | | 218 | | /// Gets or sets the closing speed at or below which contact response uses zero restitution. |
| | | 219 | | /// </summary> |
| | | 220 | | public Fixed64 RestitutionVelocityThreshold |
| | | 221 | | { |
| | 422710 | 222 | | get => _restitutionVelocityThreshold; |
| | | 223 | | set |
| | | 224 | | { |
| | 80 | 225 | | ChronicleGuard.ThrowIfArgument( |
| | 80 | 226 | | value < Fixed64.Zero, |
| | 80 | 227 | | nameof(value), |
| | 80 | 228 | | "Restitution velocity threshold cannot be negative."); |
| | 79 | 229 | | _restitutionVelocityThreshold = value; |
| | 79 | 230 | | } |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary> |
| | | 234 | | /// Gets or sets the default half-thickness used when pure 2D colliders are embedded into mixed 2D/3D contacts. |
| | | 235 | | /// </summary> |
| | | 236 | | public Fixed64 Mixed2DHalfThickness |
| | | 237 | | { |
| | 70720 | 238 | | get => _mixed2DHalfThickness; |
| | | 239 | | set |
| | | 240 | | { |
| | 79 | 241 | | ChronicleGuard.ThrowIfArgument( |
| | 79 | 242 | | value <= Fixed64.Zero, |
| | 79 | 243 | | nameof(value), |
| | 79 | 244 | | "Mixed 2D half-thickness must be greater than zero."); |
| | 77 | 245 | | if (_mixed2DHalfThickness == value) |
| | 7 | 246 | | return; |
| | 70 | 247 | | Owner?.ValidateMixedGeometry(_runtimeMode, value); |
| | 68 | 248 | | _mixed2DHalfThickness = value; |
| | 68 | 249 | | } |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | /// <summary> |
| | | 253 | | /// Gets or sets which dimensional physics service this context should advance. |
| | | 254 | | /// </summary> |
| | | 255 | | public PhysicsRuntimeMode RuntimeMode |
| | | 256 | | { |
| | 354941 | 257 | | get => _runtimeMode; |
| | | 258 | | set |
| | | 259 | | { |
| | 6173 | 260 | | ChronicleGuard.ThrowIfArgument( |
| | 6173 | 261 | | !value.IsValid(), |
| | 6173 | 262 | | nameof(value), |
| | 6173 | 263 | | "Physics runtime mode must be TwoD, ThreeD, Both, or Mixed."); |
| | 6168 | 264 | | if (_runtimeMode == value) |
| | 196 | 265 | | return; |
| | 5972 | 266 | | Owner?.ValidateMixedGeometry(value, _mixed2DHalfThickness); |
| | 5968 | 267 | | _runtimeMode = value; |
| | 5968 | 268 | | } |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | /// <summary> |
| | | 272 | | /// Creates physics settings, using registered-layer defaults for omitted values. |
| | | 273 | | /// </summary> |
| | 11133 | 274 | | public PhysicsSettings( |
| | 11133 | 275 | | int? frameRate, |
| | 11133 | 276 | | bool[,]? collisionMatrix, |
| | 11133 | 277 | | PhysicsLayerMask? groundCheckLayerMask = null) |
| | | 278 | | { |
| | 11133 | 279 | | SetFrameRate(frameRate ?? DefaultFrameRate); |
| | 11132 | 280 | | _collisionMatrix = collisionMatrix ?? GetRegisteredCollisionMatrix(); |
| | 11132 | 281 | | GroundCheckLayerMask = groundCheckLayerMask ?? DefaultGroundCheckLayerMask; |
| | 11132 | 282 | | } |
| | | 283 | | |
| | | 284 | | /// <summary> |
| | | 285 | | /// Sets the fixed-step frame rate after validating its representable range. |
| | | 286 | | /// </summary> |
| | | 287 | | public void SetFrameRate(int frameRate) |
| | | 288 | | { |
| | 14449 | 289 | | ThrowIfInvalidFrameRate(frameRate); |
| | 14446 | 290 | | FrameRate = frameRate; |
| | 14446 | 291 | | } |
| | | 292 | | |
| | | 293 | | internal static void ThrowIfInvalidFrameRate(int frameRate) |
| | | 294 | | { |
| | 28868 | 295 | | ChronicleGuard.ThrowIfNegativeOrZero(frameRate, nameof(frameRate)); |
| | 28868 | 296 | | if (frameRate > MaxResolvableFrameRate) |
| | | 297 | | { |
| | 4 | 298 | | throw new ArgumentOutOfRangeException( |
| | 4 | 299 | | nameof(frameRate), |
| | 4 | 300 | | frameRate, |
| | 4 | 301 | | $"Frame rate cannot exceed {MaxResolvableFrameRate}."); |
| | | 302 | | } |
| | 28864 | 303 | | } |
| | | 304 | | |
| | | 305 | | /// <summary> |
| | | 306 | | /// Creates settings with default values and the currently registered layer matrix. |
| | | 307 | | /// </summary> |
| | | 308 | | public static PhysicsSettings DefaultSettings() |
| | | 309 | | { |
| | 10203 | 310 | | bool[,] collisionMatrix = GetRegisteredCollisionMatrix(); |
| | 10203 | 311 | | return new PhysicsSettings(DefaultFrameRate, collisionMatrix); |
| | | 312 | | } |
| | | 313 | | |
| | | 314 | | /// <summary> |
| | | 315 | | /// Creates a fully enabled square collision matrix sized to the registered layer names. |
| | | 316 | | /// </summary> |
| | | 317 | | public static bool[,] GetRegisteredCollisionMatrix() |
| | | 318 | | { |
| | 10994 | 319 | | SwiftList<string> layersList = new(); |
| | | 320 | | |
| | 725604 | 321 | | for (int i = 0; i < MaxLayers; ++i) |
| | | 322 | | { |
| | 351808 | 323 | | string? layerName = PhysicsLayer.LayerToName(i); |
| | | 324 | | // Check if the layer has a name |
| | 351808 | 325 | | if (!string.IsNullOrEmpty(layerName)) |
| | 5075 | 326 | | layersList.Add(layerName); |
| | | 327 | | } |
| | | 328 | | |
| | 10994 | 329 | | string[] layerNames = layersList.ToArray(); |
| | 10994 | 330 | | int numberOfLayers = layerNames.Length; |
| | | 331 | | |
| | 10994 | 332 | | if (numberOfLayers == 0) |
| | 5921 | 333 | | return new bool[0, 0]; |
| | | 334 | | |
| | 5073 | 335 | | bool[,] collisionMatrix = new bool[numberOfLayers, numberOfLayers]; |
| | 20296 | 336 | | for (int i = 0; i < numberOfLayers; ++i) |
| | 20308 | 337 | | for (int j = 0; j < numberOfLayers; ++j) |
| | 5079 | 338 | | collisionMatrix[i, j] = true; |
| | | 339 | | |
| | 5073 | 340 | | return collisionMatrix; |
| | | 341 | | } |
| | | 342 | | } |