@woosh/meep-engine 2.139.0 → 2.140.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/package.json +1 -1
  2. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_aabb.d.ts +3 -3
  3. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_aabb.d.ts.map +1 -1
  4. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_aabb.js +4 -4
  5. package/src/{engine/physics/broadphase/aabb_transform_oriented.d.ts → core/geom/3d/aabb/aabb3_transform_oriented.d.ts} +2 -2
  6. package/src/core/geom/3d/aabb/aabb3_transform_oriented.d.ts.map +1 -0
  7. package/src/{engine/physics/broadphase/aabb_transform_oriented.js → core/geom/3d/aabb/aabb3_transform_oriented.js} +1 -1
  8. package/src/core/geom/3d/quaternion/quat3_to_matrix3.d.ts +54 -0
  9. package/src/core/geom/3d/quaternion/quat3_to_matrix3.d.ts.map +1 -0
  10. package/src/core/geom/3d/quaternion/quat3_to_matrix3.js +69 -0
  11. package/src/core/geom/3d/shape/AbstractShape3D.d.ts +24 -2
  12. package/src/core/geom/3d/shape/AbstractShape3D.d.ts.map +1 -1
  13. package/src/core/geom/3d/shape/AbstractShape3D.js +24 -1
  14. package/src/core/geom/3d/shape/HeightMapShape3D.d.ts +148 -0
  15. package/src/core/geom/3d/shape/HeightMapShape3D.d.ts.map +1 -0
  16. package/src/core/geom/3d/shape/HeightMapShape3D.js +451 -0
  17. package/src/core/geom/3d/shape/MeshShape3D.d.ts +210 -0
  18. package/src/core/geom/3d/shape/MeshShape3D.d.ts.map +1 -0
  19. package/src/core/geom/3d/shape/MeshShape3D.js +593 -0
  20. package/src/core/geom/3d/shape/TransformedShape3D.d.ts.map +1 -1
  21. package/src/core/geom/3d/shape/TransformedShape3D.js +46 -2
  22. package/src/core/geom/3d/shape/Triangle3D.d.ts +95 -0
  23. package/src/core/geom/3d/shape/Triangle3D.d.ts.map +1 -0
  24. package/src/core/geom/3d/shape/Triangle3D.js +318 -0
  25. package/src/core/geom/3d/shape/UnionShape3D.js +13 -0
  26. package/src/core/geom/3d/shape/shape_mesh_from_geometry.d.ts +30 -0
  27. package/src/core/geom/3d/shape/shape_mesh_from_geometry.d.ts.map +1 -0
  28. package/src/core/geom/3d/shape/shape_mesh_from_geometry.js +64 -0
  29. package/src/core/geom/3d/tetrahedra/prototype_tetrahedrize_mesh.js +9 -11
  30. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_build_vertex_to_tets_map.d.ts +28 -0
  31. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_build_vertex_to_tets_map.d.ts.map +1 -0
  32. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_build_vertex_to_tets_map.js +48 -0
  33. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_improve_quality.d.ts.map +1 -1
  34. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_improve_quality.js +40 -18
  35. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_smooth_vertex.d.ts +9 -5
  36. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_smooth_vertex.d.ts.map +1 -1
  37. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_smooth_vertex.js +38 -10
  38. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_vertex_is_boundary.d.ts +14 -5
  39. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_vertex_is_boundary.d.ts.map +1 -1
  40. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_vertex_is_boundary.js +47 -5
  41. package/src/core/geom/3d/topology/struct/binary/BinaryElementPool.d.ts +19 -0
  42. package/src/core/geom/3d/topology/struct/binary/BinaryElementPool.d.ts.map +1 -1
  43. package/src/core/geom/3d/topology/struct/binary/BinaryElementPool.js +75 -13
  44. package/src/core/geom/3d/triangle/v3_compute_triangle_normal.d.ts +2 -2
  45. package/src/core/geom/3d/triangle/v3_compute_triangle_normal.d.ts.map +1 -1
  46. package/src/core/geom/3d/triangle/v3_compute_triangle_normal.js +1 -1
  47. package/src/core/geom/vec3/v3_dot_array_array.d.ts +3 -3
  48. package/src/core/geom/vec3/v3_dot_array_array.d.ts.map +1 -1
  49. package/src/core/geom/vec3/v3_dot_array_array.js +2 -2
  50. package/src/core/geom/vec3/v3_negate_array.d.ts +3 -3
  51. package/src/core/geom/vec3/v3_negate_array.d.ts.map +1 -1
  52. package/src/core/geom/vec3/v3_negate_array.js +2 -2
  53. package/src/core/geom/vec3/v3_quat3_apply.d.ts +29 -0
  54. package/src/core/geom/vec3/v3_quat3_apply.d.ts.map +1 -0
  55. package/src/core/geom/vec3/v3_quat3_apply.js +39 -0
  56. package/src/core/geom/vec3/v3_quat3_apply_inverse.d.ts +30 -0
  57. package/src/core/geom/vec3/v3_quat3_apply_inverse.d.ts.map +1 -0
  58. package/src/core/geom/vec3/v3_quat3_apply_inverse.js +41 -0
  59. package/src/core/geom/vec3/v3_triple_cross_product.d.ts +32 -0
  60. package/src/core/geom/vec3/v3_triple_cross_product.d.ts.map +1 -0
  61. package/src/core/geom/vec3/v3_triple_cross_product.js +45 -0
  62. package/src/engine/control/first-person/FirstPersonPlayerController.d.ts +16 -3
  63. package/src/engine/control/first-person/FirstPersonPlayerController.d.ts.map +1 -1
  64. package/src/engine/control/first-person/FirstPersonPlayerController.js +211 -211
  65. package/src/engine/control/first-person/FirstPersonPlayerControllerConfig.d.ts +72 -8
  66. package/src/engine/control/first-person/FirstPersonPlayerControllerConfig.d.ts.map +1 -1
  67. package/src/engine/control/first-person/FirstPersonPlayerControllerConfig.js +37 -5
  68. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.d.ts +101 -3
  69. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.d.ts.map +1 -1
  70. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.js +1789 -1416
  71. package/src/engine/control/first-person/TODO.md +173 -127
  72. package/src/engine/control/first-person/abilities/Slide.d.ts.map +1 -1
  73. package/src/engine/control/first-person/abilities/Slide.js +9 -1
  74. package/src/engine/control/first-person/prototype_first_person_controller.js +88 -2
  75. package/src/engine/control/first-person/test/buildTestPlayer.d.ts.map +1 -1
  76. package/src/engine/control/first-person/test/buildTestPlayer.js +9 -1
  77. package/src/engine/graphics/geometry/CapsuleGeometry.d.ts +42 -0
  78. package/src/engine/graphics/geometry/CapsuleGeometry.d.ts.map +1 -0
  79. package/src/engine/graphics/geometry/CapsuleGeometry.js +171 -0
  80. package/src/engine/physics/BULLET_REVIEW.md +945 -0
  81. package/src/engine/physics/CANNON_REVIEW.md +1300 -0
  82. package/src/engine/physics/JOLT_REVIEW.md +913 -0
  83. package/src/engine/physics/PLAN.md +461 -236
  84. package/src/engine/physics/RAPIER_REVIEW.md +934 -0
  85. package/src/engine/physics/REVIEW_001_ACTION_PLAN.md +642 -0
  86. package/src/engine/physics/broadphase/compute_fat_world_aabb.js +2 -2
  87. package/src/engine/physics/contact/ManifoldStore.d.ts +83 -10
  88. package/src/engine/physics/contact/ManifoldStore.d.ts.map +1 -1
  89. package/src/engine/physics/contact/ManifoldStore.js +608 -499
  90. package/src/engine/physics/ecs/ColliderObserverSystem.d.ts +2 -2
  91. package/src/engine/physics/ecs/ColliderObserverSystem.d.ts.map +1 -1
  92. package/src/engine/physics/ecs/PhysicsSystem.d.ts +128 -20
  93. package/src/engine/physics/ecs/PhysicsSystem.d.ts.map +1 -1
  94. package/src/engine/physics/ecs/PhysicsSystem.js +1301 -1159
  95. package/src/engine/physics/fluid/FluidSimulator.d.ts.map +1 -1
  96. package/src/engine/physics/fluid/FluidSimulator.js +2 -1
  97. package/src/engine/physics/fluid/solver/v3_grid_subtract_pressure_gradient.d.ts +28 -6
  98. package/src/engine/physics/fluid/solver/v3_grid_subtract_pressure_gradient.d.ts.map +1 -1
  99. package/src/engine/physics/fluid/solver/v3_grid_subtract_pressure_gradient.js +39 -17
  100. package/src/engine/physics/gjk/expanding_polytope_algorithm.d.ts +6 -6
  101. package/src/engine/physics/gjk/expanding_polytope_algorithm.d.ts.map +1 -1
  102. package/src/engine/physics/gjk/expanding_polytope_algorithm.js +68 -22
  103. package/src/engine/physics/gjk/gjk.d.ts +28 -2
  104. package/src/engine/physics/gjk/gjk.d.ts.map +1 -1
  105. package/src/engine/physics/gjk/gjk.js +421 -378
  106. package/src/engine/physics/gjk/minkowski_support.d.ts +37 -0
  107. package/src/engine/physics/gjk/minkowski_support.d.ts.map +1 -0
  108. package/src/engine/physics/gjk/minkowski_support.js +75 -0
  109. package/src/engine/physics/gjk/mpr.d.ts +56 -0
  110. package/src/engine/physics/gjk/mpr.d.ts.map +1 -0
  111. package/src/engine/physics/gjk/mpr.js +344 -0
  112. package/src/engine/physics/inertia/world_inverse_inertia.d.ts +20 -5
  113. package/src/engine/physics/inertia/world_inverse_inertia.d.ts.map +1 -1
  114. package/src/engine/physics/inertia/world_inverse_inertia.js +36 -38
  115. package/src/engine/physics/integration/integrate_position.d.ts +25 -7
  116. package/src/engine/physics/integration/integrate_position.d.ts.map +1 -1
  117. package/src/engine/physics/integration/integrate_position.js +43 -12
  118. package/src/engine/physics/integration/integrate_velocity.d.ts +30 -0
  119. package/src/engine/physics/integration/integrate_velocity.d.ts.map +1 -1
  120. package/src/engine/physics/integration/integrate_velocity.js +82 -1
  121. package/src/engine/physics/narrowphase/PosedShape.d.ts +0 -8
  122. package/src/engine/physics/narrowphase/PosedShape.d.ts.map +1 -1
  123. package/src/engine/physics/narrowphase/PosedShape.js +28 -30
  124. package/src/engine/physics/narrowphase/box_box_manifold.d.ts.map +1 -1
  125. package/src/engine/physics/narrowphase/box_box_manifold.js +113 -17
  126. package/src/engine/physics/narrowphase/box_triangle_contact.d.ts +30 -0
  127. package/src/engine/physics/narrowphase/box_triangle_contact.d.ts.map +1 -0
  128. package/src/engine/physics/narrowphase/box_triangle_contact.js +811 -0
  129. package/src/engine/physics/narrowphase/capsule_contacts.d.ts.map +1 -1
  130. package/src/engine/physics/narrowphase/capsule_contacts.js +10 -56
  131. package/src/engine/physics/narrowphase/capsule_triangle_contact.d.ts +71 -0
  132. package/src/engine/physics/narrowphase/capsule_triangle_contact.d.ts.map +1 -0
  133. package/src/engine/physics/narrowphase/capsule_triangle_contact.js +375 -0
  134. package/src/engine/physics/narrowphase/compute_penetration.d.ts +91 -0
  135. package/src/engine/physics/narrowphase/compute_penetration.d.ts.map +1 -0
  136. package/src/engine/physics/narrowphase/compute_penetration.js +396 -0
  137. package/src/engine/physics/narrowphase/decomposition/aabb_world_to_local.d.ts +35 -0
  138. package/src/engine/physics/narrowphase/decomposition/aabb_world_to_local.d.ts.map +1 -0
  139. package/src/engine/physics/narrowphase/decomposition/aabb_world_to_local.js +80 -0
  140. package/src/engine/physics/narrowphase/decomposition/decompose_to_triangles.d.ts +31 -0
  141. package/src/engine/physics/narrowphase/decomposition/decompose_to_triangles.d.ts.map +1 -0
  142. package/src/engine/physics/narrowphase/decomposition/decompose_to_triangles.js +55 -0
  143. package/src/engine/physics/narrowphase/decomposition/heightmap_enumerate_triangles.d.ts +42 -0
  144. package/src/engine/physics/narrowphase/decomposition/heightmap_enumerate_triangles.d.ts.map +1 -0
  145. package/src/engine/physics/narrowphase/decomposition/heightmap_enumerate_triangles.js +204 -0
  146. package/src/engine/physics/narrowphase/decomposition/mesh_enumerate_triangles.d.ts +42 -0
  147. package/src/engine/physics/narrowphase/decomposition/mesh_enumerate_triangles.d.ts.map +1 -0
  148. package/src/engine/physics/narrowphase/decomposition/mesh_enumerate_triangles.js +94 -0
  149. package/src/engine/physics/narrowphase/decomposition/triangle_buffer_layout.d.ts +37 -0
  150. package/src/engine/physics/narrowphase/decomposition/triangle_buffer_layout.d.ts.map +1 -0
  151. package/src/engine/physics/narrowphase/decomposition/triangle_buffer_layout.js +37 -0
  152. package/src/engine/physics/narrowphase/narrowphase_step.d.ts +8 -2
  153. package/src/engine/physics/narrowphase/narrowphase_step.d.ts.map +1 -1
  154. package/src/engine/physics/narrowphase/narrowphase_step.js +1422 -382
  155. package/src/engine/physics/narrowphase/sphere_box_contact.d.ts.map +1 -1
  156. package/src/engine/physics/narrowphase/sphere_box_contact.js +16 -23
  157. package/src/engine/physics/narrowphase/sphere_triangle_contact.d.ts +48 -0
  158. package/src/engine/physics/narrowphase/sphere_triangle_contact.d.ts.map +1 -0
  159. package/src/engine/physics/narrowphase/sphere_triangle_contact.js +143 -0
  160. package/src/engine/physics/queries/overlap_shape.d.ts +51 -0
  161. package/src/engine/physics/queries/overlap_shape.d.ts.map +1 -0
  162. package/src/engine/physics/queries/overlap_shape.js +183 -0
  163. package/src/engine/physics/queries/shape_cast.d.ts +56 -0
  164. package/src/engine/physics/queries/shape_cast.d.ts.map +1 -0
  165. package/src/engine/physics/queries/shape_cast.js +387 -0
  166. package/src/engine/physics/solver/solve_contacts.d.ts +116 -30
  167. package/src/engine/physics/solver/solve_contacts.d.ts.map +1 -1
  168. package/src/engine/physics/solver/solve_contacts.js +641 -223
  169. package/src/engine/physics/broadphase/aabb_transform_oriented.d.ts.map +0 -1
  170. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_unmasked_legacy.d.ts +0 -20
  171. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_unmasked_legacy.d.ts.map +0 -1
  172. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_unmasked_legacy.js +0 -83
@@ -1,1159 +1,1301 @@
1
- import { assert } from "../../../core/assert.js";
2
- import { BVH } from "../../../core/bvh2/bvh3/BVH.js";
3
- import Signal from "../../../core/events/signal/Signal.js";
4
- import Vector3 from "../../../core/geom/Vector3.js";
5
- import { ResourceAccessKind } from "../../../core/model/ResourceAccessKind.js";
6
- import { ResourceAccessSpecification } from "../../../core/model/ResourceAccessSpecification.js";
7
- import { System } from "../../ecs/System.js";
8
- import { Transform } from "../../ecs/transform/Transform.js";
9
- import { body_id_index, BodyStorage } from "../body/BodyStorage.js";
10
- import { aabb_transform_oriented } from "../broadphase/aabb_transform_oriented.js";
11
- import { compute_fat_world_aabb } from "../broadphase/compute_fat_world_aabb.js";
12
- import { generate_pairs } from "../broadphase/generate_pairs.js";
13
- import { PairList } from "../broadphase/PairList.js";
14
- import { CONTACT_STRIDE, ManifoldStore } from "../contact/ManifoldStore.js";
15
- import { ContactEventBuffer, ContactEventKind } from "../events/ContactEventBuffer.js";
16
- import { diff_manifolds } from "../events/diff_manifolds.js";
17
- import { integrate_position } from "../integration/integrate_position.js";
18
- import { integrate_velocity } from "../integration/integrate_velocity.js";
19
- import { IslandBuilder } from "../island/IslandBuilder.js";
20
- import { narrowphase_step } from "../narrowphase/narrowphase_step.js";
21
- import { raycast as raycast_query } from "../queries/raycast.js";
22
- import { returnTrue } from "../../../core/function/returnTrue.js";
23
- import { solve_contacts } from "../solver/solve_contacts.js";
24
- import { world_inverse_inertia_apply } from "../inertia/world_inverse_inertia.js";
25
- import { PhysicsEvents } from "./PhysicsEvents.js";
26
-
27
- /**
28
- * Scratch for {@link applyImpulseAt}'s angular delta calculation.
29
- * @type {Float64Array}
30
- */
31
- const scratch_angular_delta = new Float64Array(3);
32
- import { BodyKind } from "./BodyKind.js";
33
- import { Collider, COLLIDER_UNBOUND } from "./Collider.js";
34
- import { RIGID_BODY_UNALLOCATED, RigidBody } from "./RigidBody.js";
35
- import { RigidBodyFlags } from "./RigidBodyFlags.js";
36
- import { SleepState } from "./SleepState.js";
37
-
38
- /**
39
- * Reusable scratch buffer for world-AABB construction so the link path is
40
- * allocation-free in steady state.
41
- * @type {Float64Array}
42
- */
43
- const scratch_world_aabb = new Float64Array(6);
44
-
45
- /**
46
- * Reusable scratch buffer for the local AABB returned by
47
- * {@link AbstractShape3D#compute_bounding_box}.
48
- * @type {Float64Array}
49
- */
50
- const scratch_local_aabb = new Float64Array(6);
51
-
52
- /**
53
- * Rigid-body physics system.
54
- *
55
- * v1 scope: pool + active list + two BVHs (static / dynamic), Transform sync
56
- * contract, and the user-facing API surface (gravity, force / impulse, layer
57
- * filtering, wake / sleep, contact filter). The per-step simulation pipeline
58
- * (broadphase pair generation, narrowphase, solver, islands, sleep test,
59
- * contact-event emission) is built on top of this skeleton in subsequent
60
- * iterations.
61
- *
62
- * Dependency tuple is `(RigidBody, Collider, Transform)` — every body has
63
- * exactly one collider on the same entity. Compound bodies via child collider
64
- * entities are an extension point handled by a follow-up sub-observer.
65
- *
66
- * @author Alex Goldring
67
- * @copyright Company Named Limited (c) 2026
68
- */
69
- export class PhysicsSystem extends System {
70
-
71
- constructor() {
72
- super();
73
-
74
- this.dependencies = [RigidBody, Transform];
75
-
76
- this.components_used = [
77
- ResourceAccessSpecification.from(RigidBody, ResourceAccessKind.Read | ResourceAccessKind.Write),
78
- ResourceAccessSpecification.from(Collider, ResourceAccessKind.Read),
79
- ResourceAccessSpecification.from(Transform, ResourceAccessKind.Read | ResourceAccessKind.Write),
80
- ];
81
-
82
- /**
83
- * @type {BodyStorage}
84
- */
85
- this.storage = new BodyStorage();
86
-
87
- /**
88
- * @type {BVH}
89
- */
90
- this.staticBvh = new BVH();
91
-
92
- /**
93
- * @type {BVH}
94
- */
95
- this.dynamicBvh = new BVH();
96
-
97
- /**
98
- * Persistent contact-manifold cache. One slot per active pair.
99
- * @type {ManifoldStore}
100
- */
101
- this.manifolds = new ManifoldStore();
102
-
103
- /**
104
- * Per-frame list of broadphase-overlapping pairs (canonical
105
- * `(min, max)`). Cleared at the top of each step.
106
- * @type {PairList}
107
- */
108
- this.pairs = new PairList();
109
-
110
- /**
111
- * Per-frame contact-event buffer. Populated by the manifold diff
112
- * pass at end-of-step and consumed by the dispatch pass.
113
- * @type {ContactEventBuffer}
114
- */
115
- this.contactEvents = new ContactEventBuffer();
116
-
117
- /**
118
- * Per-frame island partitioning of the awake-body + contact graph.
119
- * Rebuilt after narrowphase, consumed by the solver (and, in the
120
- * follow-up slice, by the per-island atomic sleep test). Bodies
121
- * static and kinematic act as constraint anchors and do not enlarge
122
- * islands.
123
- * @type {IslandBuilder}
124
- */
125
- this.islands = new IslandBuilder();
126
-
127
- /**
128
- * Velocity-squared threshold below which a body is eligible to start
129
- * accumulating sleep time. Combined linear + angular kinetic-ish
130
- * metric: `vx²+vy²+vz² + ωx²+ωy²+ωz²`. Default 0.01 corresponds to
131
- * ~0.1 m/s linear or ~0.1 rad/s angular.
132
- * @type {number}
133
- */
134
- this.sleepVelocitySqrThreshold = 0.01;
135
-
136
- /**
137
- * Number of TGS substeps per fixed tick. Each substep does
138
- * `integrate_velocity solve_contacts integrate_position` with
139
- * `dt / substeps` as its time step; narrowphase + island building
140
- * run once per tick before the substep loop. Higher values give
141
- * better convergence on tall stacks (impulses propagate through
142
- * deeper contact chains thanks to per-substep position
143
- * integration) at proportionally higher solver cost.
144
- *
145
- * Box2D's default is 4; we match. Set to 1 to fall back to
146
- * classic PGS behaviour (one solve per tick at full `dt`).
147
- * @type {number}
148
- */
149
- this.solverSubsteps = 4;
150
-
151
- /**
152
- * Velocity iterations within each TGS substep. With 4 substeps,
153
- * the total iterations per tick is `solverSubsteps × this` = 8 —
154
- * comparable to the classic PGS default of 10, but distributed
155
- * across substeps with position integration between them, which
156
- * is dramatically more stable on stacks.
157
- * @type {number}
158
- */
159
- this.solverItersPerSubstep = 2;
160
-
161
- /**
162
- * Seconds of below-threshold motion before a body is moved to the
163
- * sleeping set. Box2D default is 0.5 s.
164
- * @type {number}
165
- */
166
- this.sleepTimeThreshold = 0.5;
167
-
168
- /**
169
- * Reusable contact-event payload. Listeners must copy any fields they
170
- * intend to retain past their own scope. Reset before each dispatch.
171
- * @private
172
- */
173
- this.__contact_payload = {
174
- entityA: -1,
175
- entityB: -1,
176
- kind: 0,
177
- depth: 0,
178
- normal: new Vector3(),
179
- point: new Vector3(),
180
- };
181
-
182
- /**
183
- * World gravity, m/s². Applied each step scaled by per-body gravityScale.
184
- * @readonly
185
- * @type {Vector3}
186
- */
187
- this.gravity = new Vector3(0, -9.81, 0);
188
-
189
- /**
190
- * Emitted at end-of-step for newly established contact pairs.
191
- * @readonly
192
- * @type {Signal}
193
- */
194
- this.onContactBegin = new Signal();
195
-
196
- /**
197
- * Emitted at end-of-step for contact pairs that persisted from the previous step.
198
- * @readonly
199
- * @type {Signal}
200
- */
201
- this.onContactStay = new Signal();
202
-
203
- /**
204
- * Emitted at end-of-step for contact pairs that disappeared.
205
- * @readonly
206
- * @type {Signal}
207
- */
208
- this.onContactEnd = new Signal();
209
-
210
- /**
211
- * Optional global contact filter. Called for each surviving broadphase
212
- * pair; returning `false` discards the pair.
213
- * @type {((entityA: number, entityB: number, colliderA: Collider, colliderB: Collider) => boolean) | null}
214
- * @private
215
- */
216
- this.__contact_filter = null;
217
-
218
- /**
219
- * Per-body component side-tables indexed by body index (NOT packed id).
220
- * Sparse arrays — populated at link, cleared at unlink. The hot loop
221
- * iterates `storage.awake_at(i)` and dereferences these.
222
- * @type {RigidBody[]}
223
- */
224
- this.__bodies = [];
225
- /** @type {Transform[]} */
226
- this.__transforms = [];
227
-
228
- /**
229
- * Per-body list of attached colliders. Each entry stores the
230
- * Collider component, its world Transform, the entity that owns
231
- * it (the body entity for same-entity attachments, a child entity
232
- * for compound bodies), and the BVH leaf id assigned at attach
233
- * time. A body may have zero or more attached colliders.
234
- *
235
- * @type {Array<Array<{collider: Collider, transform: Transform, entity: number, bvhNode: number}>>}
236
- */
237
- this.__body_collider_lists = [];
238
-
239
- /**
240
- * Bound reference to {@link __pair_filter} so we hand the same
241
- * callable to {@link generate_pairs} each step without per-step
242
- * allocation.
243
- * @private
244
- */
245
- this.__pair_filter_bound = (idA, idB) => this.__pair_filter(idA, idB);
246
- }
247
-
248
- /**
249
- * Symmetric layer/mask check + optional user callback. Called per
250
- * candidate pair during broadphase. Returns `true` to accept the pair.
251
- *
252
- * Layer/mask rule: pair (A, B) collides iff
253
- * `(A.layer & B.mask) !== 0 && (B.layer & A.mask) !== 0`.
254
- * The user's contact-filter callback is consulted only for pairs that
255
- * pass the bitmask test (cheap gate first).
256
- *
257
- * @private
258
- * @param {number} idA packed body id
259
- * @param {number} idB packed body id
260
- * @returns {boolean}
261
- */
262
- __pair_filter(idA, idB) {
263
- const idxA = body_id_index(idA);
264
- const idxB = body_id_index(idB);
265
- const rbA = this.__bodies[idxA];
266
- const rbB = this.__bodies[idxB];
267
- if (rbA === undefined || rbB === undefined) return false;
268
-
269
- // Layer/mask gate (symmetric).
270
- if (((rbA.layer & rbB.mask) | 0) === 0) return false;
271
- if (((rbB.layer & rbA.mask) | 0) === 0) return false;
272
-
273
- // User callback gate, if installed.
274
- const fn = this.__contact_filter;
275
- if (fn !== null) {
276
- const entA = this.storage.entity_at(idxA);
277
- const entB = this.storage.entity_at(idxB);
278
- const colA = this.__primary_collider(idxA);
279
- const colB = this.__primary_collider(idxB);
280
- if (!fn(entA, entB, colA, colB)) return false;
281
- }
282
- return true;
283
- }
284
-
285
- /**
286
- * First attached collider of a body, or `null` if none. Used by the
287
- * solver to read material parameters (friction / restitution) when the
288
- * per-contact source-collider identity isn't tracked yet (v1 limitation
289
- * multi-collider bodies with mixed materials lose precision here).
290
- *
291
- * @private
292
- * @param {number} body_idx
293
- * @returns {Collider|null}
294
- */
295
- __primary_collider(body_idx) {
296
- const list = this.__body_collider_lists[body_idx];
297
- return (list !== undefined && list.length > 0) ? list[0].collider : null;
298
- }
299
-
300
- /**
301
- * Replace the world gravity vector. Effective on the next step.
302
- * @param {Vector3|{x:number,y:number,z:number}} v
303
- */
304
- setGravity(v) {
305
- this.gravity.set(v.x, v.y, v.z);
306
- }
307
-
308
- /**
309
- * Install (or remove with `null`) the contact filter callback.
310
- * @param {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null} fn
311
- */
312
- setContactFilter(fn) {
313
- this.__contact_filter = fn;
314
- }
315
-
316
- /**
317
- * @returns {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null}
318
- */
319
- getContactFilter() {
320
- return this.__contact_filter;
321
- }
322
-
323
- /**
324
- * @private
325
- * @param {RigidBody} rb
326
- * @param {Collider} collider
327
- * @param {Transform} transform
328
- * @returns {number} BVH node id
329
- */
330
- __insert_into_broadphase(rb, collider, transform) {
331
- const shape = collider.shape;
332
-
333
- assert.notNull(shape, 'Collider.shape must be set before attaching');
334
-
335
- shape.compute_bounding_box(scratch_local_aabb);
336
-
337
- const p = transform.position;
338
- const q = transform.rotation;
339
-
340
- aabb_transform_oriented(
341
- scratch_world_aabb, 0,
342
- scratch_local_aabb[0], scratch_local_aabb[1], scratch_local_aabb[2],
343
- scratch_local_aabb[3], scratch_local_aabb[4], scratch_local_aabb[5],
344
- p.x, p.y, p.z,
345
- q.x, q.y, q.z, q.w
346
- );
347
-
348
- const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
349
- const node = bvh.allocate_node();
350
-
351
- bvh.node_set_aabb_primitive(
352
- node,
353
- scratch_world_aabb[0], scratch_world_aabb[1], scratch_world_aabb[2],
354
- scratch_world_aabb[3], scratch_world_aabb[4], scratch_world_aabb[5]
355
- );
356
- bvh.node_set_user_data(node, rb._bodyId);
357
- bvh.insert_leaf(node);
358
-
359
- return node;
360
- }
361
-
362
- /**
363
- * @private
364
- * @param {RigidBody} rb
365
- * @param {number} node
366
- */
367
- __remove_from_broadphase(rb, node) {
368
- const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
369
- bvh.remove_leaf(node);
370
- bvh.release_node(node);
371
- }
372
-
373
- /**
374
- * Lifecycle entry: invoked when an entity gains the (RigidBody, Transform)
375
- * tuple. Allocates the body's slot in storage and seeds an empty collider
376
- * list. Colliders are attached separately via {@link attach_collider} (the
377
- * paired {@link ColliderObserverSystem} drives this from the dataset; in
378
- * tests, call manually).
379
- *
380
- * @param {RigidBody} rigidBody
381
- * @param {Transform} transform
382
- * @param {number} entity
383
- */
384
- link(rigidBody, transform, entity) {
385
- const packed = this.storage.allocate(entity);
386
- rigidBody._bodyId = packed;
387
- rigidBody.sleepState = SleepState.Awake;
388
-
389
- const index = body_id_index(packed);
390
- this.storage.set_kind(index, rigidBody.kind);
391
- this.storage.set_flags(index, rigidBody.flags);
392
-
393
- this.__bodies[index] = rigidBody;
394
- this.__transforms[index] = transform;
395
- this.__body_collider_lists[index] = [];
396
-
397
- // Static bodies do not need to live in the active list — they never move.
398
- if (rigidBody.kind === BodyKind.Static) {
399
- this.storage.mark_sleeping(index);
400
- }
401
- }
402
-
403
- /**
404
- * Detach every collider attached to this body, free its slot, and clear
405
- * the side-tables.
406
- *
407
- * @param {RigidBody} rigidBody
408
- * @param {Transform} transform
409
- * @param {number} entity
410
- */
411
- unlink(rigidBody, transform, entity) {
412
- const packed = rigidBody._bodyId;
413
-
414
- assert.equal(this.storage.is_valid(packed), true, 'unlink: stale or absent body id');
415
-
416
- // If the body is sleeping inside a multi-member sleep group, dissolve
417
- // the group by waking every member first. Otherwise the surviving
418
- // members would hold dangling indices in their sleep-group chain
419
- // pointing at a slot that has just been freed.
420
- if (rigidBody.sleep_group_next !== -1) {
421
- this.__wake_body(rigidBody);
422
- }
423
-
424
- const index = body_id_index(packed);
425
- const list = this.__body_collider_lists[index];
426
- if (list !== undefined) {
427
- for (let i = 0; i < list.length; i++) {
428
- const entry = list[i];
429
- if (entry.bvhNode !== COLLIDER_UNBOUND) {
430
- this.__remove_from_broadphase(rigidBody, entry.bvhNode);
431
- }
432
- entry.collider._bvhNode = COLLIDER_UNBOUND;
433
- entry.collider._bodyId = -1;
434
- }
435
- }
436
-
437
- this.__bodies[index] = undefined;
438
- this.__transforms[index] = undefined;
439
- this.__body_collider_lists[index] = undefined;
440
-
441
- this.storage.free(packed);
442
- rigidBody._bodyId = RIGID_BODY_UNALLOCATED;
443
- }
444
-
445
- /**
446
- * Attach a collider to an existing body. The collider can live on the
447
- * same entity as the body (single-collider body) or on a child entity
448
- * (compound body). The world transform passed here is the collider's
449
- * own for a same-entity collider it is the body's Transform; for a
450
- * child collider it is the child entity's Transform.
451
- *
452
- * Idempotent — re-attaching the same collider is a no-op.
453
- *
454
- * @param {number} body_entity entity that owns the body
455
- * @param {Collider} collider
456
- * @param {Transform} transform world transform of the collider
457
- * @param {number} [collider_entity] entity owning the collider (defaults to body_entity)
458
- */
459
- attach_collider(body_entity, collider, transform, collider_entity = body_entity) {
460
- // Find the body by walking the storage entity table. The body must
461
- // have been allocated via `link` before any colliders are attached.
462
- const body_index = this.__find_body_index_by_entity(body_entity);
463
- assert.notEqual(body_index, -1, `attach_collider: no body found for entity ${body_entity}`);
464
-
465
- const rb = this.__bodies[body_index];
466
- // Idempotent: skip if collider already attached.
467
- if (collider._bvhNode !== COLLIDER_UNBOUND) return;
468
-
469
- const node = this.__insert_into_broadphase(rb, collider, transform);
470
-
471
- collider._bvhNode = node;
472
- collider._bodyId = rb._bodyId;
473
- this.__body_collider_lists[body_index].push({
474
- collider, transform, entity: collider_entity, bvhNode: node,
475
- });
476
- }
477
-
478
- /**
479
- * Reverse of {@link attach_collider}. Idempotent.
480
- *
481
- * @param {number} body_entity
482
- * @param {Collider} collider
483
- */
484
- detach_collider(body_entity, collider) {
485
- if (collider._bvhNode === COLLIDER_UNBOUND) return;
486
-
487
- const body_index = this.__find_body_index_by_entity(body_entity);
488
- if (body_index === -1) return;
489
-
490
- const rb = this.__bodies[body_index];
491
- this.__remove_from_broadphase(rb, collider._bvhNode);
492
-
493
- const list = this.__body_collider_lists[body_index];
494
- for (let i = 0; i < list.length; i++) {
495
- if (list[i].collider === collider) {
496
- list.splice(i, 1);
497
- break;
498
- }
499
- }
500
-
501
- collider._bvhNode = COLLIDER_UNBOUND;
502
- collider._bodyId = -1;
503
- }
504
-
505
- /**
506
- * Linear scan over body slots looking for the one whose entity matches.
507
- * O(N) where N is the live body count — only called on the link/unlink
508
- * paths, not during simulation, so the scan cost is bounded.
509
- *
510
- * @private
511
- * @param {number} entity
512
- * @returns {number} body index or -1
513
- */
514
- __find_body_index_by_entity(entity) {
515
- const hwm = this.storage.high_water_mark;
516
- for (let i = 0; i < hwm; i++) {
517
- if (this.storage.entity_at(i) === entity) return i;
518
- }
519
- return -1;
520
- }
521
-
522
- /**
523
- * Resolve a packed body id to its entity, or `-1` if the id is stale.
524
- * @param {number} packed_body_id
525
- * @returns {number}
526
- */
527
- entityOf(packed_body_id) {
528
- if (!this.storage.is_valid(packed_body_id)) return -1;
529
- return this.storage.entity_at(body_id_index(packed_body_id));
530
- }
531
-
532
- /**
533
- * Number of live bodies (regardless of awake/sleeping state).
534
- * @returns {number}
535
- */
536
- get bodyCount() {
537
- return this.storage.size;
538
- }
539
-
540
- /**
541
- * Apply an instantaneous change of momentum at the body's centre of mass.
542
- * Linear-only — see {@link applyImpulseAt} for an off-centre impulse that
543
- * also produces angular response.
544
- *
545
- * Wakes the body if it is asleep.
546
- *
547
- * @param {RigidBody} rigidBody
548
- * @param {Vector3|{x:number,y:number,z:number}} impulse
549
- */
550
- applyImpulse(rigidBody, impulse) {
551
- if (rigidBody.kind !== BodyKind.Dynamic) {
552
- return;
553
- }
554
- const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
555
- rigidBody.linearVelocity.addScaled(impulse, inv_m);
556
-
557
- this.__wake_body(rigidBody);
558
- }
559
-
560
- /**
561
- * Apply an instantaneous change of momentum at a specific world-space point.
562
- * Off-centre impulses produce both linear (Δv = P/m) and angular
563
- * (Δω = I_w⁻¹·(r × P)) response.
564
- *
565
- * Wakes the body if it is asleep.
566
- *
567
- * @param {RigidBody} rigidBody
568
- * @param {Transform} transform body's current world Transform (used for r and I_w)
569
- * @param {Vector3|{x:number,y:number,z:number}} impulse
570
- * @param {Vector3|{x:number,y:number,z:number}} worldPoint
571
- */
572
- applyImpulseAt(rigidBody, transform, impulse, worldPoint) {
573
- if (rigidBody.kind !== BodyKind.Dynamic) {
574
- return;
575
- }
576
- const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
577
-
578
- rigidBody.linearVelocity.set(
579
- rigidBody.linearVelocity.x + impulse.x * inv_m,
580
- rigidBody.linearVelocity.y + impulse.y * inv_m,
581
- rigidBody.linearVelocity.z + impulse.z * inv_m
582
- );
583
-
584
- const rx = worldPoint.x - transform.position.x;
585
- const ry = worldPoint.y - transform.position.y;
586
- const rz = worldPoint.z - transform.position.z;
587
-
588
- // Δω = I_w⁻¹ · (r × P)
589
- const tx = ry * impulse.z - rz * impulse.y;
590
- const ty = rz * impulse.x - rx * impulse.z;
591
- const tz = rx * impulse.y - ry * impulse.x;
592
-
593
- world_inverse_inertia_apply(scratch_angular_delta, 0, rigidBody, transform, tx, ty, tz);
594
-
595
- rigidBody.angularVelocity.set(
596
- rigidBody.angularVelocity.x + scratch_angular_delta[0],
597
- rigidBody.angularVelocity.y + scratch_angular_delta[1],
598
- rigidBody.angularVelocity.z + scratch_angular_delta[2]
599
- );
600
-
601
- this.__wake_body(rigidBody);
602
- }
603
-
604
- /**
605
- * Accumulate a continuous torque (world-space) for integration on the
606
- * next fixedUpdate. Pairs with {@link applyForce} for the rotational case.
607
- *
608
- * Wakes the body if asleep.
609
- *
610
- * @param {RigidBody} rigidBody
611
- * @param {Vector3|{x:number,y:number,z:number}} torque
612
- */
613
- applyTorque(rigidBody, torque) {
614
- if (rigidBody.kind !== BodyKind.Dynamic) {
615
- return;
616
- }
617
- rigidBody.accumulatedTorque.set(
618
- rigidBody.accumulatedTorque.x + torque.x,
619
- rigidBody.accumulatedTorque.y + torque.y,
620
- rigidBody.accumulatedTorque.z + torque.z
621
- );
622
- this.__wake_body(rigidBody);
623
- }
624
-
625
- /**
626
- * Apply a continuous force at a specific world-space point. The force
627
- * generates both a linear acceleration (F/m) and a torque (r × F) about
628
- * the body's centre of mass.
629
- *
630
- * Wakes the body if asleep.
631
- *
632
- * @param {RigidBody} rigidBody
633
- * @param {Transform} transform body's current world Transform
634
- * @param {Vector3|{x:number,y:number,z:number}} force
635
- * @param {Vector3|{x:number,y:number,z:number}} worldPoint
636
- */
637
- applyForceAt(rigidBody, transform, force, worldPoint) {
638
- if (rigidBody.kind !== BodyKind.Dynamic) {
639
- return;
640
- }
641
- rigidBody.accumulatedForce.set(
642
- rigidBody.accumulatedForce.x + force.x,
643
- rigidBody.accumulatedForce.y + force.y,
644
- rigidBody.accumulatedForce.z + force.z
645
- );
646
-
647
- const rx = worldPoint.x - transform.position.x;
648
- const ry = worldPoint.y - transform.position.y;
649
- const rz = worldPoint.z - transform.position.z;
650
-
651
- rigidBody.accumulatedTorque.set(
652
- rigidBody.accumulatedTorque.x + (ry * force.z - rz * force.y),
653
- rigidBody.accumulatedTorque.y + (rz * force.x - rx * force.z),
654
- rigidBody.accumulatedTorque.z + (rx * force.y - ry * force.x)
655
- );
656
-
657
- this.__wake_body(rigidBody);
658
- }
659
-
660
- /**
661
- * Accumulate a continuous force to be integrated next fixedUpdate step.
662
- * Wakes the body if asleep.
663
- *
664
- * @param {RigidBody} rigidBody
665
- * @param {Vector3|{x:number,y:number,z:number}} force
666
- */
667
- applyForce(rigidBody, force) {
668
- if (rigidBody.kind !== BodyKind.Dynamic) {
669
- return;
670
- }
671
- rigidBody.accumulatedForce.add( force);
672
- this.__wake_body(rigidBody);
673
- }
674
-
675
- /**
676
- * Replace the linear velocity. Wakes the body if asleep.
677
- *
678
- * @param {RigidBody} rigidBody
679
- * @param {Vector3|{x:number,y:number,z:number}} v
680
- */
681
- setLinearVelocity(rigidBody, v) {
682
- rigidBody.linearVelocity.copy(v);
683
- if (rigidBody.kind === BodyKind.Dynamic) {
684
- this.__wake_body(rigidBody);
685
- }
686
- }
687
-
688
- /**
689
- * Force the body awake. Static bodies are ignored.
690
- * @param {RigidBody} rigidBody
691
- */
692
- wake(rigidBody) {
693
- this.__wake_body(rigidBody);
694
- }
695
-
696
- /**
697
- * Force the body asleep. Dynamic bodies will not re-enter the active list
698
- * until a wake event occurs.
699
- * @param {RigidBody} rigidBody
700
- */
701
- sleep(rigidBody) {
702
- if (rigidBody.kind !== BodyKind.Dynamic) {
703
- return;
704
- }
705
- if (rigidBody.sleepState === SleepState.Sleeping) {
706
- return;
707
- }
708
- rigidBody.sleepState = SleepState.Sleeping;
709
- const index = body_id_index(rigidBody._bodyId);
710
- this.storage.mark_sleeping(index);
711
- }
712
-
713
- /**
714
- * Wake a body and atomically wake every other body it was last sleeping
715
- * with (its "sleep group"). Sleep groups are circular doubly-linked lists
716
- * threaded through every member of an island when it sleeps atomically;
717
- * waking any one member walks the chain and wakes the rest in the same
718
- * call.
719
- *
720
- * Without this, a 100-block stack hit at the base would wake one block
721
- * per frame as the broadphase propagated awareness up the stack — a
722
- * visible ~1.6 s wave at 60 fps. Atomic wake eliminates the wave.
723
- *
724
- * No-op for non-dynamic bodies. Idempotent for already-awake bodies.
725
- * @private
726
- * @param {RigidBody} rb
727
- */
728
- __wake_body(rb) {
729
- if (rb.kind !== BodyKind.Dynamic) return;
730
- if (rb.sleepState === SleepState.Awake) return;
731
- const index = body_id_index(rb._bodyId);
732
-
733
- // Remember the next-in-chain before clearing the body's own pointers;
734
- // the rest of the group is reached by walking forward from there.
735
- const start_next = rb.sleep_group_next;
736
-
737
- rb.sleepState = SleepState.Awake;
738
- rb.sleep_timer = 0;
739
- rb.sleep_group_next = -1;
740
- rb.sleep_group_prev = -1;
741
- this.storage.mark_awake(index);
742
-
743
- if (start_next === -1 || start_next === index) return;
744
-
745
- // Walk the (now-broken) chain forward until we loop back. The chain
746
- // is circular so we know when to stop; defensive `-1` guards against
747
- // corruption from a body being unlinked mid-sleep-group.
748
- let cur = start_next;
749
- while (cur !== -1 && cur !== index) {
750
- const cur_rb = this.__bodies[cur];
751
- if (cur_rb === undefined) break;
752
- const nxt = cur_rb.sleep_group_next;
753
- cur_rb.sleepState = SleepState.Awake;
754
- cur_rb.sleep_timer = 0;
755
- cur_rb.sleep_group_next = -1;
756
- cur_rb.sleep_group_prev = -1;
757
- this.storage.mark_awake(cur);
758
- cur = nxt;
759
- }
760
- }
761
-
762
- /**
763
- * Atomically put every body in a contiguous range of island members to
764
- * sleep. Members are threaded into a circular doubly-linked list so any
765
- * future `wake` on any member walks the chain and revives them all.
766
- *
767
- * Velocities are zeroed because the body is by definition at rest at
768
- * this point the alternative (storing residual velocities for "softer"
769
- * wake) is what Bullet does, but for a deterministic game-physics target
770
- * fully resetting is simpler and avoids drift while sleeping.
771
- *
772
- * @private
773
- * @param {Uint32Array} member_array view (or full array) of body indices
774
- * @param {number} start
775
- * @param {number} end
776
- */
777
- __atomic_sleep_island_range(member_array, start, end) {
778
- const count = end - start;
779
- if (count === 0) return;
780
- const bodies = this.__bodies;
781
- const storage = this.storage;
782
-
783
- if (count === 1) {
784
- const idx = member_array[start];
785
- const rb = bodies[idx];
786
- if (rb === undefined) return;
787
- rb.sleep_group_next = -1;
788
- rb.sleep_group_prev = -1;
789
- rb.sleepState = SleepState.Sleeping;
790
- rb.linearVelocity[0] = 0; rb.linearVelocity[1] = 0; rb.linearVelocity[2] = 0;
791
- rb.angularVelocity[0] = 0; rb.angularVelocity[1] = 0; rb.angularVelocity[2] = 0;
792
- storage.mark_sleeping(idx);
793
- return;
794
- }
795
-
796
- for (let i = 0; i < count; i++) {
797
- const idx = member_array[start + i];
798
- const rb = bodies[idx];
799
- if (rb === undefined) continue;
800
- const next_idx = member_array[start + ((i + 1) % count)];
801
- const prev_idx = member_array[start + ((i - 1 + count) % count)];
802
- rb.sleep_group_next = next_idx;
803
- rb.sleep_group_prev = prev_idx;
804
- rb.sleepState = SleepState.Sleeping;
805
- rb.linearVelocity[0] = 0; rb.linearVelocity[1] = 0; rb.linearVelocity[2] = 0;
806
- rb.angularVelocity[0] = 0; rb.angularVelocity[1] = 0; rb.angularVelocity[2] = 0;
807
- storage.mark_sleeping(idx);
808
- }
809
- }
810
-
811
- /**
812
- * Get the body index for a packed body id without revalidation. Used by
813
- * query traversals that already trust the id came from a live BVH leaf.
814
- * @param {number} packed_body_id
815
- * @returns {number}
816
- */
817
- __index_of(packed_body_id) {
818
- return body_id_index(packed_body_id);
819
- }
820
-
821
- /**
822
- * Broadphase raycast against both BVHs. Fills `result` with the nearest
823
- * hit and returns `true` on hit, `false` on miss.
824
- *
825
- * Narrowphase refinement against the actual shape geometry is a
826
- * follow-up for now `result.t` is the distance to the leaf's
827
- * inflated AABB and `result.normal` is the AABB face normal. Both are
828
- * exact for AABB-shaped colliders.
829
- *
830
- * @param {Ray3} ray origin + unit direction + `tMax`
831
- * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
832
- * @param {(entity:number, collider:Collider)=>boolean} [filter] defaults
833
- * to {@link returnTrue} (accept every candidate)
834
- * @returns {boolean}
835
- */
836
- raycast(ray, result, filter = returnTrue) {
837
- return raycast_query(this, ray, result, filter);
838
- }
839
-
840
- /**
841
- * Run one simulation step. v1 pipeline: integrate velocity → integrate
842
- * position refit broadphase AABBs. Narrowphase, solver, islands and
843
- * contact-event emission land in subsequent slices.
844
- *
845
- * @param {number} dt
846
- */
847
- /**
848
- * Wake any sleeping body that appears in this step's broadphase pair list.
849
- * A pair means the BVH AABBs overlap — even if the sleeper hasn't moved,
850
- * an awake neighbour has come into contact range and the sleeper must
851
- * participate in narrowphase / solve.
852
- * @private
853
- */
854
- __wake_pairs() {
855
- const list = this.pairs;
856
- const n = list.count;
857
- const bodies = this.__bodies;
858
- for (let i = 0; i < n; i++) {
859
- const idA = list.get_a(i);
860
- const idB = list.get_b(i);
861
- const idxA = body_id_index(idA);
862
- const idxB = body_id_index(idB);
863
- const a = bodies[idxA];
864
- const b = bodies[idxB];
865
- if (a !== undefined && a.sleepState === SleepState.Sleeping) {
866
- this.__wake_body(a);
867
- }
868
- if (b !== undefined && b.sleepState === SleepState.Sleeping) {
869
- this.__wake_body(b);
870
- }
871
- }
872
- }
873
-
874
- /**
875
- * Per-island atomic sleep test. Walks each island once and applies the
876
- * decision uniformly across all members:
877
- *
878
- * - If any member carries {@link RigidBodyFlags.DisableSleep}, the
879
- * entire island is exempt; every member's sleep_timer is reset.
880
- * - If `max(|v|² + |ω|²)` across all members is below
881
- * {@link sleepVelocitySqrThreshold}, every member's sleep_timer is
882
- * incremented by `dt`. When the smallest member's timer crosses
883
- * {@link sleepTimeThreshold}, the whole island sleeps atomically in
884
- * the same step (members get threaded into a sleep-group chain so
885
- * {@link __wake_body} can wake them all in one call).
886
- * - Otherwise the island has at least one active member, so every
887
- * member's timer is reset.
888
- *
889
- * This is the design-plan atomic-island sleep — replaces the per-body
890
- * approximation that lived in this slot during the previous slice.
891
- * Weakly-connected piles no longer chatter awake when a single member
892
- * blips above threshold; piles fall asleep and wake up as one.
893
- *
894
- * @private
895
- * @param {number} dt
896
- */
897
- __sleep_test(dt) {
898
- const threshold_sqr = this.sleepVelocitySqrThreshold;
899
- const time_threshold = this.sleepTimeThreshold;
900
- const bodies = this.__bodies;
901
- const islands = this.islands;
902
- const island_count = islands.island_count;
903
- const body_offsets = islands.body_offsets;
904
- const body_data = islands.body_data;
905
-
906
- for (let isl = 0; isl < island_count; isl++) {
907
- const start = body_offsets[isl];
908
- const end = body_offsets[isl + 1];
909
- if (end === start) continue;
910
-
911
- // Pass 1: find max + check DisableSleep across the island.
912
- let max_v_sqr = 0;
913
- let any_disable_sleep = false;
914
- for (let i = start; i < end; i++) {
915
- const idx = body_data[i];
916
- const rb = bodies[idx];
917
- if (rb === undefined) continue;
918
- if ((rb.flags & RigidBodyFlags.DisableSleep) !== 0) {
919
- any_disable_sleep = true;
920
- break;
921
- }
922
- const lv = rb.linearVelocity;
923
- const av = rb.angularVelocity;
924
- const v_sqr = lv[0] * lv[0] + lv[1] * lv[1] + lv[2] * lv[2]
925
- + av[0] * av[0] + av[1] * av[1] + av[2] * av[2];
926
- if (v_sqr > max_v_sqr) max_v_sqr = v_sqr;
927
- }
928
-
929
- if (any_disable_sleep) {
930
- // Whole island is exempt reset every member's timer.
931
- for (let i = start; i < end; i++) {
932
- const rb = bodies[body_data[i]];
933
- if (rb !== undefined) rb.sleep_timer = 0;
934
- }
935
- continue;
936
- }
937
-
938
- if (max_v_sqr < threshold_sqr) {
939
- // Island is at rest increment every member's timer; if the
940
- // slowest-stabilising member has crossed the time threshold,
941
- // every member has (they were incremented together this step),
942
- // so atomic-sleep the island.
943
- let min_timer = Infinity;
944
- for (let i = start; i < end; i++) {
945
- const rb = bodies[body_data[i]];
946
- if (rb === undefined) continue;
947
- rb.sleep_timer += dt;
948
- if (rb.sleep_timer < min_timer) min_timer = rb.sleep_timer;
949
- }
950
- if (min_timer >= time_threshold) {
951
- this.__atomic_sleep_island_range(body_data, start, end);
952
- }
953
- } else {
954
- // At least one member is active — reset every timer.
955
- for (let i = start; i < end; i++) {
956
- const rb = bodies[body_data[i]];
957
- if (rb !== undefined) rb.sleep_timer = 0;
958
- }
959
- }
960
- }
961
- }
962
-
963
- /**
964
- * Dispatch every buffered contact event through:
965
- * - the system-level Signals ({@link onContactBegin}/Stay/End), always; and
966
- * - the entity-level event channel via `dataset.sendEvent(entity, name, payload)`,
967
- * when a dataset is attached.
968
- *
969
- * Payload is a reused scratch object; listeners must copy anything they
970
- * intend to retain past the listener body.
971
- * @private
972
- */
973
- __dispatch_contact_events() {
974
- const events = this.contactEvents;
975
- const n = events.count;
976
- if (n === 0) return;
977
-
978
- const ecd = (this.entityManager !== null && this.entityManager !== undefined)
979
- ? this.entityManager.dataset
980
- : null;
981
- const manifolds = this.manifolds;
982
- const data = manifolds.data_buffer;
983
-
984
- const payload = this.__contact_payload;
985
-
986
- for (let i = 0; i < n; i++) {
987
- const kind = events.kind_at(i);
988
- const entA = events.entityA_at(i);
989
- const entB = events.entityB_at(i);
990
- const slot = events.slot_at(i);
991
-
992
- // Use the deepest contact of the manifold as the representative
993
- // point/normal/depth for the event. v1: contact 0 only.
994
- const slot_off = manifolds.slot_data_offset(slot);
995
- const has_contact = manifolds.contact_count(slot) > 0;
996
-
997
- // Scratch payload no observers subscribe to its component
998
- // vectors; write indices directly to skip the Signal dispatch.
999
- const pt = payload.point;
1000
- const nm = payload.normal;
1001
- if (has_contact) {
1002
- const wax = data[slot_off], way = data[slot_off + 1], waz = data[slot_off + 2];
1003
- const wbx = data[slot_off + 3], wby = data[slot_off + 4], wbz = data[slot_off + 5];
1004
- pt[0] = (wax + wbx) * 0.5; pt[1] = (way + wby) * 0.5; pt[2] = (waz + wbz) * 0.5;
1005
- nm[0] = data[slot_off + 6]; nm[1] = data[slot_off + 7]; nm[2] = data[slot_off + 8];
1006
- payload.depth = data[slot_off + 9];
1007
- } else {
1008
- pt[0] = 0; pt[1] = 0; pt[2] = 0;
1009
- nm[0] = 0; nm[1] = 0; nm[2] = 0;
1010
- payload.depth = 0;
1011
- }
1012
- payload.entityA = entA;
1013
- payload.entityB = entB;
1014
-
1015
- let event_name;
1016
- let signal;
1017
- if (kind === ContactEventKind.Begin) { event_name = PhysicsEvents.ContactBegin; signal = this.onContactBegin; }
1018
- else if (kind === ContactEventKind.Stay) { event_name = PhysicsEvents.ContactStay; signal = this.onContactStay; }
1019
- else { event_name = PhysicsEvents.ContactEnd; signal = this.onContactEnd; }
1020
-
1021
- signal.send1(payload);
1022
-
1023
- if (ecd !== null && ecd !== undefined) {
1024
- if (entA >= 0) ecd.sendEvent(entA, event_name, payload);
1025
- if (entB >= 0) ecd.sendEvent(entB, event_name, payload);
1026
- }
1027
- }
1028
- }
1029
-
1030
- fixedUpdate(dt) {
1031
- const gx = this.gravity.x;
1032
- const gy = this.gravity.y;
1033
- const gz = this.gravity.z;
1034
-
1035
- const lists = this.__body_collider_lists;
1036
-
1037
- // ─── Once-per-tick stages (broadphase, narrowphase, islands) ────
1038
- //
1039
- // Position-dependent work — broadphase refit, pair generation,
1040
- // narrowphase contact extraction, island partitioning — runs ONCE
1041
- // at the top of the tick using the pose at tick-start. Substep
1042
- // position integration happens inside the inner loop further down;
1043
- // intra-tick motion is bounded by the fat AABB margin (it uses the
1044
- // full-tick dt for sweep volume) so manifolds stay valid across
1045
- // substeps without re-running narrowphase.
1046
-
1047
- // Stage 1: refit each awake body's collider leaves with a fat AABB
1048
- // padded for the full tick's swept extent.
1049
- const count = this.storage.awake_count;
1050
- for (let i = 0; i < count; i++) {
1051
- const idx = this.storage.awake_at(i);
1052
- const rb = this.__bodies[idx];
1053
- const list = lists[idx];
1054
- if (list === undefined) continue;
1055
- const lv = rb.linearVelocity;
1056
- for (let k = 0; k < list.length; k++) {
1057
- const entry = list[k];
1058
- compute_fat_world_aabb(
1059
- scratch_world_aabb, 0,
1060
- entry.collider.shape, entry.transform,
1061
- lv[0], lv[1], lv[2],
1062
- dt
1063
- );
1064
- this.dynamicBvh.node_move_aabb(entry.bvhNode, scratch_world_aabb);
1065
- }
1066
- }
1067
-
1068
- // Stage 2: broadphase pair generation (canonical min,max body pairs).
1069
- generate_pairs(
1070
- this.storage,
1071
- this.dynamicBvh,
1072
- this.staticBvh,
1073
- this.manifolds,
1074
- lists,
1075
- this.pairs,
1076
- this.__pair_filter_bound,
1077
- );
1078
-
1079
- // Stage 3: wake propagation. Any sleeping body whose leaf overlaps
1080
- // an awake leaf this tick must participate in narrowphase + solve.
1081
- this.__wake_pairs();
1082
-
1083
- // Stage 4: narrowphase closed-form fast paths or GJK+EPA per pair.
1084
- narrowphase_step(this.pairs, this.manifolds, this);
1085
-
1086
- // Stage 5: partition awake bodies + touched contacts into islands.
1087
- this.islands.build(this.storage, this.manifolds, this.__bodies, this.__body_collider_lists);
1088
-
1089
- // ─── TGS substep loop ───────────────────────────────────────────
1090
- //
1091
- // Each substep advances velocity by `gravity * sub_dt`, runs a
1092
- // short velocity-iteration sweep with Baumgarte bias scaled to
1093
- // `sub_dt`, and integrates position by `sub_dt`. Warm-start only
1094
- // fires on substep 0 — subsequent substeps continue from the
1095
- // impulses already accumulated in the manifold data buffer (those
1096
- // are reflected in the current velocity state; re-applying would
1097
- // double-count).
1098
- //
1099
- // Position correction is K× stronger over a tick than classic PGS
1100
- // for the same Baumgarte beta, because the velocity-correcting
1101
- // impulse fires K times and each one's position contribution
1102
- // integrates immediately. This is the mechanism that lets TGS
1103
- // resolve tall stacks where single-shot PGS just spreads info
1104
- // through the chain without resolving cumulative drift.
1105
- const substeps = this.solverSubsteps | 0;
1106
- const iters_per_substep = this.solverItersPerSubstep | 0;
1107
- const sub_dt = dt / substeps;
1108
-
1109
- // Re-read awake_count because __wake_pairs may have grown it.
1110
- const count_after_wake = this.storage.awake_count;
1111
-
1112
- for (let s = 0; s < substeps; s++) {
1113
- // Integrate velocity (gravity + accumulated forces) for this substep.
1114
- for (let i = 0; i < count_after_wake; i++) {
1115
- const idx = this.storage.awake_at(i);
1116
- const rb = this.__bodies[idx];
1117
- const tr = this.__transforms[idx];
1118
- integrate_velocity(rb, tr, gx, gy, gz, sub_dt);
1119
- }
1120
-
1121
- // Solve velocity constraints over the current pose. Bias term
1122
- // inside the solver uses `sub_dt`, so per-substep Baumgarte
1123
- // correction is stronger than full-dt PGS would apply.
1124
- solve_contacts(this.manifolds, this, sub_dt, iters_per_substep, s === 0);
1125
-
1126
- // Advance position with the solved velocity.
1127
- for (let i = 0; i < count_after_wake; i++) {
1128
- const idx = this.storage.awake_at(i);
1129
- const rb = this.__bodies[idx];
1130
- const tr = this.__transforms[idx];
1131
- integrate_position(rb, tr, sub_dt);
1132
- }
1133
- }
1134
-
1135
- // ─── End-of-tick stages (sleep, events, manifold cleanup) ───────
1136
-
1137
- // Stage 6: sleep test using the full-tick `dt` for the sleep timer.
1138
- this.__sleep_test(dt);
1139
-
1140
- // Stage 7: diff manifolds against the previous frame and dispatch
1141
- // Begin / Stay / End events. MUST run before advance_frame, which
1142
- // rolls the touched flags.
1143
- diff_manifolds(this.manifolds, this.storage, this.contactEvents);
1144
- this.__dispatch_contact_events();
1145
-
1146
- // Stage 8 (end-of-step): roll touched → prev_touched and evict slots
1147
- // whose pair has not been touched within the grace window.
1148
- this.manifolds.advance_frame();
1149
- }
1150
- }
1151
-
1152
- /**
1153
- * @readonly
1154
- * @type {boolean}
1155
- */
1156
- PhysicsSystem.prototype.isPhysicsSystem = true;
1157
-
1158
- // Re-export for convenience.
1159
- export { BodyKind, RigidBodyFlags };
1
+ import { assert } from "../../../core/assert.js";
2
+ import { BVH } from "../../../core/bvh2/bvh3/BVH.js";
3
+ import Signal from "../../../core/events/signal/Signal.js";
4
+ import Vector3 from "../../../core/geom/Vector3.js";
5
+ import { ResourceAccessKind } from "../../../core/model/ResourceAccessKind.js";
6
+ import { ResourceAccessSpecification } from "../../../core/model/ResourceAccessSpecification.js";
7
+ import { System } from "../../ecs/System.js";
8
+ import { Transform } from "../../ecs/transform/Transform.js";
9
+ import { body_id_index, BodyStorage } from "../body/BodyStorage.js";
10
+ import { aabb3_transform_oriented } from "../../../core/geom/3d/aabb/aabb3_transform_oriented.js";
11
+ import { compute_fat_world_aabb } from "../broadphase/compute_fat_world_aabb.js";
12
+ import { generate_pairs } from "../broadphase/generate_pairs.js";
13
+ import { PairList } from "../broadphase/PairList.js";
14
+ import { CONTACT_STRIDE, ManifoldStore } from "../contact/ManifoldStore.js";
15
+ import { ContactEventBuffer, ContactEventKind } from "../events/ContactEventBuffer.js";
16
+ import { diff_manifolds } from "../events/diff_manifolds.js";
17
+ import { integrate_position } from "../integration/integrate_position.js";
18
+ import { integrate_velocity_forces, integrate_velocity_gravity } from "../integration/integrate_velocity.js";
19
+ import { IslandBuilder } from "../island/IslandBuilder.js";
20
+ import { narrowphase_step } from "../narrowphase/narrowphase_step.js";
21
+ import { overlap_shape as overlap_shape_query } from "../queries/overlap_shape.js";
22
+ import { raycast as raycast_query } from "../queries/raycast.js";
23
+ import { shape_cast as shape_cast_query } from "../queries/shape_cast.js";
24
+ import { returnTrue } from "../../../core/function/returnTrue.js";
25
+ import {
26
+ prepare_contacts,
27
+ refresh_contacts,
28
+ warm_start_contacts,
29
+ solve_velocity,
30
+ apply_restitution,
31
+ solve_position,
32
+ } from "../solver/solve_contacts.js";
33
+ import { world_inverse_inertia_apply } from "../inertia/world_inverse_inertia.js";
34
+ import { PhysicsEvents } from "./PhysicsEvents.js";
35
+
36
+ /**
37
+ * Scratch for {@link applyImpulseAt}'s angular delta calculation.
38
+ * @type {Float64Array}
39
+ */
40
+ const scratch_angular_delta = new Float64Array(3);
41
+ import { BodyKind } from "./BodyKind.js";
42
+ import { Collider, COLLIDER_UNBOUND } from "./Collider.js";
43
+ import { RIGID_BODY_UNALLOCATED, RigidBody } from "./RigidBody.js";
44
+ import { RigidBodyFlags } from "./RigidBodyFlags.js";
45
+ import { SleepState } from "./SleepState.js";
46
+
47
+ /**
48
+ * Reusable scratch buffer for world-AABB construction so the link path is
49
+ * allocation-free in steady state.
50
+ * @type {Float64Array}
51
+ */
52
+ const scratch_world_aabb = new Float64Array(6);
53
+
54
+ /**
55
+ * Reusable scratch buffer for the local AABB returned by
56
+ * {@link AbstractShape3D#compute_bounding_box}.
57
+ * @type {Float64Array}
58
+ */
59
+ const scratch_local_aabb = new Float64Array(6);
60
+
61
+ /**
62
+ * Rigid-body physics system.
63
+ *
64
+ * v1 scope: pool + active list + two BVHs (static / dynamic), Transform sync
65
+ * contract, and the user-facing API surface (gravity, force / impulse, layer
66
+ * filtering, wake / sleep, contact filter). The per-step simulation pipeline
67
+ * (broadphase pair generation, narrowphase, solver, islands, sleep test,
68
+ * contact-event emission) is built on top of this skeleton in subsequent
69
+ * iterations.
70
+ *
71
+ * Dependency tuple is `(RigidBody, Collider, Transform)` — every body has
72
+ * exactly one collider on the same entity. Compound bodies via child collider
73
+ * entities are an extension point handled by a follow-up sub-observer.
74
+ *
75
+ * @author Alex Goldring
76
+ * @copyright Company Named Limited (c) 2026
77
+ */
78
+ export class PhysicsSystem extends System {
79
+
80
+ constructor() {
81
+ super();
82
+
83
+ this.dependencies = [RigidBody, Transform];
84
+
85
+ this.components_used = [
86
+ ResourceAccessSpecification.from(RigidBody, ResourceAccessKind.Read | ResourceAccessKind.Write),
87
+ ResourceAccessSpecification.from(Collider, ResourceAccessKind.Read),
88
+ ResourceAccessSpecification.from(Transform, ResourceAccessKind.Read | ResourceAccessKind.Write),
89
+ ];
90
+
91
+ /**
92
+ * @type {BodyStorage}
93
+ */
94
+ this.storage = new BodyStorage();
95
+
96
+ /**
97
+ * @type {BVH}
98
+ */
99
+ this.staticBvh = new BVH();
100
+
101
+ /**
102
+ * @type {BVH}
103
+ */
104
+ this.dynamicBvh = new BVH();
105
+
106
+ /**
107
+ * Persistent contact-manifold cache. One slot per active pair.
108
+ * @type {ManifoldStore}
109
+ */
110
+ this.manifolds = new ManifoldStore();
111
+
112
+ /**
113
+ * Per-frame list of broadphase-overlapping pairs (canonical
114
+ * `(min, max)`). Cleared at the top of each step.
115
+ * @type {PairList}
116
+ */
117
+ this.pairs = new PairList();
118
+
119
+ /**
120
+ * Per-frame contact-event buffer. Populated by the manifold diff
121
+ * pass at end-of-step and consumed by the dispatch pass.
122
+ * @type {ContactEventBuffer}
123
+ */
124
+ this.contactEvents = new ContactEventBuffer();
125
+
126
+ /**
127
+ * Per-frame island partitioning of the awake-body + contact graph.
128
+ * Rebuilt after narrowphase, consumed by the solver (and, in the
129
+ * follow-up slice, by the per-island atomic sleep test). Bodies
130
+ * static and kinematic act as constraint anchors and do not enlarge
131
+ * islands.
132
+ * @type {IslandBuilder}
133
+ */
134
+ this.islands = new IslandBuilder();
135
+
136
+ /**
137
+ * Velocity-squared threshold below which a body is eligible to start
138
+ * accumulating sleep time. Combined linear + angular kinetic-ish
139
+ * metric: `vx²+vy²+vz² + ωx²+ωy²+ωz²`. Default 0.01 corresponds to
140
+ * ~0.1 m/s linear or ~0.1 rad/s angular.
141
+ * @type {number}
142
+ */
143
+ this.sleepVelocitySqrThreshold = 0.01;
144
+
145
+ /**
146
+ * Seconds of below-threshold motion before a body is moved to the
147
+ * sleeping set. Box2D default is 0.5 s.
148
+ * @type {number}
149
+ */
150
+ this.sleepTimeThreshold = 0.5;
151
+
152
+ /**
153
+ * Number of TGS substeps per `fixedUpdate`. Each substep re-runs the
154
+ * velocity + position solve at `dt / substeps` against contacts whose
155
+ * penetration is re-derived analytically from the bodies' moved poses
156
+ * narrowphase still runs once per outer step. Higher counts buy
157
+ * stack stability, high-mass-ratio robustness, and smoother
158
+ * trajectories at a near-linear solver cost (sleeping islands are
159
+ * unaffected — they never enter the loop).
160
+ *
161
+ * `1` reproduces the non-substepped (single-step) solve.
162
+ * @type {number}
163
+ */
164
+ this.substeps = 4;
165
+
166
+ /**
167
+ * Velocity iterations per substep. Lower than a single-step solver
168
+ * would need, because the substep loop revisits the contact set
169
+ * `substeps` times.
170
+ * @type {number}
171
+ */
172
+ this.velocityIterations = 4;
173
+
174
+ /**
175
+ * Position (split-impulse) iterations per substep.
176
+ * @type {number}
177
+ */
178
+ this.positionIterations = 1;
179
+
180
+ /**
181
+ * Reusable contact-event payload. Listeners must copy any fields they
182
+ * intend to retain past their own scope. Reset before each dispatch.
183
+ * @private
184
+ */
185
+ this.__contact_payload = {
186
+ entityA: -1,
187
+ entityB: -1,
188
+ kind: 0,
189
+ depth: 0,
190
+ normal: new Vector3(),
191
+ point: new Vector3(),
192
+ };
193
+
194
+ /**
195
+ * World gravity, m/s². Applied each step scaled by per-body gravityScale.
196
+ * @readonly
197
+ * @type {Vector3}
198
+ */
199
+ this.gravity = new Vector3(0, -9.81, 0);
200
+
201
+ /**
202
+ * Emitted at end-of-step for newly established contact pairs.
203
+ * @readonly
204
+ * @type {Signal}
205
+ */
206
+ this.onContactBegin = new Signal();
207
+
208
+ /**
209
+ * Emitted at end-of-step for contact pairs that persisted from the previous step.
210
+ * @readonly
211
+ * @type {Signal}
212
+ */
213
+ this.onContactStay = new Signal();
214
+
215
+ /**
216
+ * Emitted at end-of-step for contact pairs that disappeared.
217
+ * @readonly
218
+ * @type {Signal}
219
+ */
220
+ this.onContactEnd = new Signal();
221
+
222
+ /**
223
+ * Optional global contact filter. Called for each surviving broadphase
224
+ * pair; returning `false` discards the pair.
225
+ * @type {((entityA: number, entityB: number, colliderA: Collider, colliderB: Collider) => boolean) | null}
226
+ * @private
227
+ */
228
+ this.__contact_filter = null;
229
+
230
+ /**
231
+ * Per-body component side-tables indexed by body index (NOT packed id).
232
+ * Sparse arrays populated at link, cleared at unlink. The hot loop
233
+ * iterates `storage.awake_at(i)` and dereferences these.
234
+ * @type {RigidBody[]}
235
+ */
236
+ this.__bodies = [];
237
+ /** @type {Transform[]} */
238
+ this.__transforms = [];
239
+
240
+ /**
241
+ * Per-body list of attached colliders. Each entry stores the
242
+ * Collider component, its world Transform, the entity that owns
243
+ * it (the body entity for same-entity attachments, a child entity
244
+ * for compound bodies), and the BVH leaf id assigned at attach
245
+ * time. A body may have zero or more attached colliders.
246
+ *
247
+ * @type {Array<Array<{collider: Collider, transform: Transform, entity: number, bvhNode: number}>>}
248
+ */
249
+ this.__body_collider_lists = [];
250
+
251
+ /**
252
+ * Per-body pseudo-velocity for the Catto split-impulse position
253
+ * pass (TGS Phase 1). Flat layout, 6 doubles per body slot index:
254
+ * `[lin.x, lin.y, lin.z, ang.x, ang.y, ang.z]`. Sized to
255
+ * `storage.high_water_mark * 6` at the top of each fixedUpdate
256
+ * and zeroed in place so unwritten slots contribute nothing to
257
+ * `integrate_position`.
258
+ *
259
+ * The solver writes during its position pass; `integrate_position`
260
+ * reads and folds into the pose update on the same tick, then
261
+ * the next tick's zero-pass wipes the state. It NEVER lands in
262
+ * `linearVelocity` / `angularVelocity` — that's the point of
263
+ * split impulse: depth correction does not contaminate persistent
264
+ * velocity (so a `restitution = 0` impact stops cleanly).
265
+ *
266
+ * @type {Float64Array}
267
+ */
268
+ this.__pseudo_velocity = new Float64Array(0);
269
+
270
+ /**
271
+ * Bound reference to {@link __pair_filter} so we hand the same
272
+ * callable to {@link generate_pairs} each step without per-step
273
+ * allocation.
274
+ * @private
275
+ */
276
+ this.__pair_filter_bound = (idA, idB) => this.__pair_filter(idA, idB);
277
+ }
278
+
279
+ /**
280
+ * Symmetric layer/mask check + optional user callback. Called per
281
+ * candidate pair during broadphase. Returns `true` to accept the pair.
282
+ *
283
+ * Layer/mask rule: pair (A, B) collides iff
284
+ * `(A.layer & B.mask) !== 0 && (B.layer & A.mask) !== 0`.
285
+ * The user's contact-filter callback is consulted only for pairs that
286
+ * pass the bitmask test (cheap gate first).
287
+ *
288
+ * @private
289
+ * @param {number} idA packed body id
290
+ * @param {number} idB packed body id
291
+ * @returns {boolean}
292
+ */
293
+ __pair_filter(idA, idB) {
294
+ const idxA = body_id_index(idA);
295
+ const idxB = body_id_index(idB);
296
+ const rbA = this.__bodies[idxA];
297
+ const rbB = this.__bodies[idxB];
298
+ if (rbA === undefined || rbB === undefined) return false;
299
+
300
+ // Layer/mask gate (symmetric).
301
+ if (((rbA.layer & rbB.mask) | 0) === 0) return false;
302
+ if (((rbB.layer & rbA.mask) | 0) === 0) return false;
303
+
304
+ // User callback gate, if installed.
305
+ const fn = this.__contact_filter;
306
+ if (fn !== null) {
307
+ const entA = this.storage.entity_at(idxA);
308
+ const entB = this.storage.entity_at(idxB);
309
+ const colA = this.__primary_collider(idxA);
310
+ const colB = this.__primary_collider(idxB);
311
+ if (!fn(entA, entB, colA, colB)) return false;
312
+ }
313
+ return true;
314
+ }
315
+
316
+ /**
317
+ * First attached collider of a body, or `null` if none. Used by the
318
+ * solver to read material parameters (friction / restitution) when the
319
+ * per-contact source-collider identity isn't tracked yet (v1 limitation
320
+ * — multi-collider bodies with mixed materials lose precision here).
321
+ *
322
+ * @private
323
+ * @param {number} body_idx
324
+ * @returns {Collider|null}
325
+ */
326
+ __primary_collider(body_idx) {
327
+ const list = this.__body_collider_lists[body_idx];
328
+ return (list !== undefined && list.length > 0) ? list[0].collider : null;
329
+ }
330
+
331
+ /**
332
+ * Resize {@link __pseudo_velocity} to cover every live body slot and
333
+ * zero its contents. Called at the top of each fixedUpdate so the
334
+ * split-impulse position pass starts from a clean state — bodies the
335
+ * solver doesn't touch contribute zero pseudo-velocity to
336
+ * {@link integrate_position}.
337
+ *
338
+ * Doubles on growth like the other physics scratches; never shrinks.
339
+ *
340
+ * @private
341
+ */
342
+ __reset_pseudo_velocity() {
343
+ const required = this.storage.high_water_mark * 6;
344
+ if (this.__pseudo_velocity.length < required) {
345
+ this.__pseudo_velocity = new Float64Array(required * 2);
346
+ } else if (required > 0) {
347
+ this.__pseudo_velocity.fill(0, 0, required);
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Replace the world gravity vector. Effective on the next step.
353
+ * @param {Vector3|{x:number,y:number,z:number}} v
354
+ */
355
+ setGravity(v) {
356
+ this.gravity.set(v.x, v.y, v.z);
357
+ }
358
+
359
+ /**
360
+ * Install (or remove with `null`) the contact filter callback.
361
+ * @param {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null} fn
362
+ */
363
+ setContactFilter(fn) {
364
+ this.__contact_filter = fn;
365
+ }
366
+
367
+ /**
368
+ * @returns {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null}
369
+ */
370
+ getContactFilter() {
371
+ return this.__contact_filter;
372
+ }
373
+
374
+ /**
375
+ * @private
376
+ * @param {RigidBody} rb
377
+ * @param {Collider} collider
378
+ * @param {Transform} transform
379
+ * @returns {number} BVH node id
380
+ */
381
+ __insert_into_broadphase(rb, collider, transform) {
382
+ const shape = collider.shape;
383
+
384
+ assert.notNull(shape, 'Collider.shape must be set before attaching');
385
+
386
+ shape.compute_bounding_box(scratch_local_aabb);
387
+
388
+ const p = transform.position;
389
+ const q = transform.rotation;
390
+
391
+ aabb3_transform_oriented(
392
+ scratch_world_aabb, 0,
393
+ scratch_local_aabb[0], scratch_local_aabb[1], scratch_local_aabb[2],
394
+ scratch_local_aabb[3], scratch_local_aabb[4], scratch_local_aabb[5],
395
+ p.x, p.y, p.z,
396
+ q.x, q.y, q.z, q.w
397
+ );
398
+
399
+ const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
400
+ const node = bvh.allocate_node();
401
+
402
+ bvh.node_set_aabb_primitive(
403
+ node,
404
+ scratch_world_aabb[0], scratch_world_aabb[1], scratch_world_aabb[2],
405
+ scratch_world_aabb[3], scratch_world_aabb[4], scratch_world_aabb[5]
406
+ );
407
+ bvh.node_set_user_data(node, rb._bodyId);
408
+ bvh.insert_leaf(node);
409
+
410
+ return node;
411
+ }
412
+
413
+ /**
414
+ * @private
415
+ * @param {RigidBody} rb
416
+ * @param {number} node
417
+ */
418
+ __remove_from_broadphase(rb, node) {
419
+ const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
420
+ bvh.remove_leaf(node);
421
+ bvh.release_node(node);
422
+ }
423
+
424
+ /**
425
+ * Lifecycle entry: invoked when an entity gains the (RigidBody, Transform)
426
+ * tuple. Allocates the body's slot in storage and seeds an empty collider
427
+ * list. Colliders are attached separately via {@link attach_collider} (the
428
+ * paired {@link ColliderObserverSystem} drives this from the dataset; in
429
+ * tests, call manually).
430
+ *
431
+ * @param {RigidBody} rigidBody
432
+ * @param {Transform} transform
433
+ * @param {number} entity
434
+ */
435
+ link(rigidBody, transform, entity) {
436
+ const packed = this.storage.allocate(entity);
437
+ rigidBody._bodyId = packed;
438
+ rigidBody.sleepState = SleepState.Awake;
439
+
440
+ const index = body_id_index(packed);
441
+ this.storage.set_kind(index, rigidBody.kind);
442
+ this.storage.set_flags(index, rigidBody.flags);
443
+
444
+ this.__bodies[index] = rigidBody;
445
+ this.__transforms[index] = transform;
446
+ this.__body_collider_lists[index] = [];
447
+
448
+ // Static bodies do not need to live in the active list — they never move.
449
+ if (rigidBody.kind === BodyKind.Static) {
450
+ this.storage.mark_sleeping(index);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Detach every collider attached to this body, free its slot, and clear
456
+ * the side-tables.
457
+ *
458
+ * @param {RigidBody} rigidBody
459
+ * @param {Transform} transform
460
+ * @param {number} entity
461
+ */
462
+ unlink(rigidBody, transform, entity) {
463
+ const packed = rigidBody._bodyId;
464
+
465
+ assert.equal(this.storage.is_valid(packed), true, 'unlink: stale or absent body id');
466
+
467
+ // If the body is sleeping inside a multi-member sleep group, dissolve
468
+ // the group by waking every member first. Otherwise the surviving
469
+ // members would hold dangling indices in their sleep-group chain
470
+ // pointing at a slot that has just been freed.
471
+ if (rigidBody.sleep_group_next !== -1) {
472
+ this.__wake_body(rigidBody);
473
+ }
474
+
475
+ const index = body_id_index(packed);
476
+ const list = this.__body_collider_lists[index];
477
+ if (list !== undefined) {
478
+ for (let i = 0; i < list.length; i++) {
479
+ const entry = list[i];
480
+ if (entry.bvhNode !== COLLIDER_UNBOUND) {
481
+ this.__remove_from_broadphase(rigidBody, entry.bvhNode);
482
+ }
483
+ entry.collider._bvhNode = COLLIDER_UNBOUND;
484
+ entry.collider._bodyId = -1;
485
+ }
486
+ }
487
+
488
+ this.__bodies[index] = undefined;
489
+ this.__transforms[index] = undefined;
490
+ this.__body_collider_lists[index] = undefined;
491
+
492
+ this.storage.free(packed);
493
+ rigidBody._bodyId = RIGID_BODY_UNALLOCATED;
494
+ }
495
+
496
+ /**
497
+ * Attach a collider to an existing body. The collider can live on the
498
+ * same entity as the body (single-collider body) or on a child entity
499
+ * (compound body). The world transform passed here is the collider's
500
+ * own — for a same-entity collider it is the body's Transform; for a
501
+ * child collider it is the child entity's Transform.
502
+ *
503
+ * Idempotent — re-attaching the same collider is a no-op.
504
+ *
505
+ * @param {number} body_entity entity that owns the body
506
+ * @param {Collider} collider
507
+ * @param {Transform} transform world transform of the collider
508
+ * @param {number} [collider_entity] entity owning the collider (defaults to body_entity)
509
+ */
510
+ attach_collider(body_entity, collider, transform, collider_entity = body_entity) {
511
+ // Find the body by walking the storage entity table. The body must
512
+ // have been allocated via `link` before any colliders are attached.
513
+ const body_index = this.__find_body_index_by_entity(body_entity);
514
+ assert.notEqual(body_index, -1, `attach_collider: no body found for entity ${body_entity}`);
515
+
516
+ const rb = this.__bodies[body_index];
517
+ // Idempotent: skip if collider already attached.
518
+ if (collider._bvhNode !== COLLIDER_UNBOUND) return;
519
+
520
+ const node = this.__insert_into_broadphase(rb, collider, transform);
521
+
522
+ collider._bvhNode = node;
523
+ collider._bodyId = rb._bodyId;
524
+ this.__body_collider_lists[body_index].push({
525
+ collider, transform, entity: collider_entity, bvhNode: node,
526
+ });
527
+ }
528
+
529
+ /**
530
+ * Reverse of {@link attach_collider}. Idempotent.
531
+ *
532
+ * @param {number} body_entity
533
+ * @param {Collider} collider
534
+ */
535
+ detach_collider(body_entity, collider) {
536
+ if (collider._bvhNode === COLLIDER_UNBOUND) return;
537
+
538
+ const body_index = this.__find_body_index_by_entity(body_entity);
539
+ if (body_index === -1) return;
540
+
541
+ const rb = this.__bodies[body_index];
542
+ this.__remove_from_broadphase(rb, collider._bvhNode);
543
+
544
+ const list = this.__body_collider_lists[body_index];
545
+ for (let i = 0; i < list.length; i++) {
546
+ if (list[i].collider === collider) {
547
+ list.splice(i, 1);
548
+ break;
549
+ }
550
+ }
551
+
552
+ collider._bvhNode = COLLIDER_UNBOUND;
553
+ collider._bodyId = -1;
554
+ }
555
+
556
+ /**
557
+ * Linear scan over body slots looking for the one whose entity matches.
558
+ * O(N) where N is the live body count — only called on the link/unlink
559
+ * paths, not during simulation, so the scan cost is bounded.
560
+ *
561
+ * @private
562
+ * @param {number} entity
563
+ * @returns {number} body index or -1
564
+ */
565
+ __find_body_index_by_entity(entity) {
566
+ const hwm = this.storage.high_water_mark;
567
+ for (let i = 0; i < hwm; i++) {
568
+ if (this.storage.entity_at(i) === entity) return i;
569
+ }
570
+ return -1;
571
+ }
572
+
573
+ /**
574
+ * Resolve a packed body id to its entity, or `-1` if the id is stale.
575
+ * @param {number} packed_body_id
576
+ * @returns {number}
577
+ */
578
+ entityOf(packed_body_id) {
579
+ if (!this.storage.is_valid(packed_body_id)) return -1;
580
+ return this.storage.entity_at(body_id_index(packed_body_id));
581
+ }
582
+
583
+ /**
584
+ * Number of live bodies (regardless of awake/sleeping state).
585
+ * @returns {number}
586
+ */
587
+ get bodyCount() {
588
+ return this.storage.size;
589
+ }
590
+
591
+ /**
592
+ * Apply an instantaneous change of momentum at the body's centre of mass.
593
+ * Linear-only see {@link applyImpulseAt} for an off-centre impulse that
594
+ * also produces angular response.
595
+ *
596
+ * Wakes the body if it is asleep.
597
+ *
598
+ * @param {RigidBody} rigidBody
599
+ * @param {Vector3|{x:number,y:number,z:number}} impulse
600
+ */
601
+ applyImpulse(rigidBody, impulse) {
602
+ if (rigidBody.kind !== BodyKind.Dynamic) {
603
+ return;
604
+ }
605
+ const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
606
+ rigidBody.linearVelocity.addScaled(impulse, inv_m);
607
+
608
+ this.__wake_body(rigidBody);
609
+ }
610
+
611
+ /**
612
+ * Apply an instantaneous change of momentum at a specific world-space point.
613
+ * Off-centre impulses produce both linear (Δv = P/m) and angular
614
+ * (Δω = I_w⁻¹·(r × P)) response.
615
+ *
616
+ * Wakes the body if it is asleep.
617
+ *
618
+ * @param {RigidBody} rigidBody
619
+ * @param {Transform} transform body's current world Transform (used for r and I_w)
620
+ * @param {Vector3|{x:number,y:number,z:number}} impulse
621
+ * @param {Vector3|{x:number,y:number,z:number}} worldPoint
622
+ */
623
+ applyImpulseAt(rigidBody, transform, impulse, worldPoint) {
624
+ if (rigidBody.kind !== BodyKind.Dynamic) {
625
+ return;
626
+ }
627
+ const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
628
+
629
+ rigidBody.linearVelocity.set(
630
+ rigidBody.linearVelocity.x + impulse.x * inv_m,
631
+ rigidBody.linearVelocity.y + impulse.y * inv_m,
632
+ rigidBody.linearVelocity.z + impulse.z * inv_m
633
+ );
634
+
635
+ const rx = worldPoint.x - transform.position.x;
636
+ const ry = worldPoint.y - transform.position.y;
637
+ const rz = worldPoint.z - transform.position.z;
638
+
639
+ // Δω = I_w⁻¹ · (r × P)
640
+ const tx = ry * impulse.z - rz * impulse.y;
641
+ const ty = rz * impulse.x - rx * impulse.z;
642
+ const tz = rx * impulse.y - ry * impulse.x;
643
+
644
+ world_inverse_inertia_apply(scratch_angular_delta, 0, rigidBody.inverseInertiaLocal, transform.rotation, tx, ty, tz);
645
+
646
+ rigidBody.angularVelocity.set(
647
+ rigidBody.angularVelocity.x + scratch_angular_delta[0],
648
+ rigidBody.angularVelocity.y + scratch_angular_delta[1],
649
+ rigidBody.angularVelocity.z + scratch_angular_delta[2]
650
+ );
651
+
652
+ this.__wake_body(rigidBody);
653
+ }
654
+
655
+ /**
656
+ * Accumulate a continuous torque (world-space) for integration on the
657
+ * next fixedUpdate. Pairs with {@link applyForce} for the rotational case.
658
+ *
659
+ * Wakes the body if asleep.
660
+ *
661
+ * @param {RigidBody} rigidBody
662
+ * @param {Vector3|{x:number,y:number,z:number}} torque
663
+ */
664
+ applyTorque(rigidBody, torque) {
665
+ if (rigidBody.kind !== BodyKind.Dynamic) {
666
+ return;
667
+ }
668
+ rigidBody.accumulatedTorque.set(
669
+ rigidBody.accumulatedTorque.x + torque.x,
670
+ rigidBody.accumulatedTorque.y + torque.y,
671
+ rigidBody.accumulatedTorque.z + torque.z
672
+ );
673
+ this.__wake_body(rigidBody);
674
+ }
675
+
676
+ /**
677
+ * Apply a continuous force at a specific world-space point. The force
678
+ * generates both a linear acceleration (F/m) and a torque (r × F) about
679
+ * the body's centre of mass.
680
+ *
681
+ * Wakes the body if asleep.
682
+ *
683
+ * @param {RigidBody} rigidBody
684
+ * @param {Transform} transform body's current world Transform
685
+ * @param {Vector3|{x:number,y:number,z:number}} force
686
+ * @param {Vector3|{x:number,y:number,z:number}} worldPoint
687
+ */
688
+ applyForceAt(rigidBody, transform, force, worldPoint) {
689
+ if (rigidBody.kind !== BodyKind.Dynamic) {
690
+ return;
691
+ }
692
+ rigidBody.accumulatedForce.set(
693
+ rigidBody.accumulatedForce.x + force.x,
694
+ rigidBody.accumulatedForce.y + force.y,
695
+ rigidBody.accumulatedForce.z + force.z
696
+ );
697
+
698
+ const rx = worldPoint.x - transform.position.x;
699
+ const ry = worldPoint.y - transform.position.y;
700
+ const rz = worldPoint.z - transform.position.z;
701
+
702
+ rigidBody.accumulatedTorque.set(
703
+ rigidBody.accumulatedTorque.x + (ry * force.z - rz * force.y),
704
+ rigidBody.accumulatedTorque.y + (rz * force.x - rx * force.z),
705
+ rigidBody.accumulatedTorque.z + (rx * force.y - ry * force.x)
706
+ );
707
+
708
+ this.__wake_body(rigidBody);
709
+ }
710
+
711
+ /**
712
+ * Accumulate a continuous force to be integrated next fixedUpdate step.
713
+ * Wakes the body if asleep.
714
+ *
715
+ * @param {RigidBody} rigidBody
716
+ * @param {Vector3|{x:number,y:number,z:number}} force
717
+ */
718
+ applyForce(rigidBody, force) {
719
+ if (rigidBody.kind !== BodyKind.Dynamic) {
720
+ return;
721
+ }
722
+ rigidBody.accumulatedForce.add( force);
723
+ this.__wake_body(rigidBody);
724
+ }
725
+
726
+ /**
727
+ * Replace the linear velocity. Wakes the body if asleep.
728
+ *
729
+ * @param {RigidBody} rigidBody
730
+ * @param {Vector3|{x:number,y:number,z:number}} v
731
+ */
732
+ setLinearVelocity(rigidBody, v) {
733
+ rigidBody.linearVelocity.copy(v);
734
+ if (rigidBody.kind === BodyKind.Dynamic) {
735
+ this.__wake_body(rigidBody);
736
+ }
737
+ }
738
+
739
+ /**
740
+ * Force the body awake. Static bodies are ignored.
741
+ * @param {RigidBody} rigidBody
742
+ */
743
+ wake(rigidBody) {
744
+ this.__wake_body(rigidBody);
745
+ }
746
+
747
+ /**
748
+ * Force the body asleep. Dynamic bodies will not re-enter the active list
749
+ * until a wake event occurs.
750
+ * @param {RigidBody} rigidBody
751
+ */
752
+ sleep(rigidBody) {
753
+ if (rigidBody.kind !== BodyKind.Dynamic) {
754
+ return;
755
+ }
756
+ if (rigidBody.sleepState === SleepState.Sleeping) {
757
+ return;
758
+ }
759
+ rigidBody.sleepState = SleepState.Sleeping;
760
+ const index = body_id_index(rigidBody._bodyId);
761
+ this.storage.mark_sleeping(index);
762
+ }
763
+
764
+ /**
765
+ * Wake a body and atomically wake every other body it was last sleeping
766
+ * with (its "sleep group"). Sleep groups are circular doubly-linked lists
767
+ * threaded through every member of an island when it sleeps atomically;
768
+ * waking any one member walks the chain and wakes the rest in the same
769
+ * call.
770
+ *
771
+ * Without this, a 100-block stack hit at the base would wake one block
772
+ * per frame as the broadphase propagated awareness up the stack — a
773
+ * visible ~1.6 s wave at 60 fps. Atomic wake eliminates the wave.
774
+ *
775
+ * No-op for non-dynamic bodies. Idempotent for already-awake bodies.
776
+ * @private
777
+ * @param {RigidBody} rb
778
+ */
779
+ __wake_body(rb) {
780
+ if (rb.kind !== BodyKind.Dynamic) return;
781
+ if (rb.sleepState === SleepState.Awake) return;
782
+ const index = body_id_index(rb._bodyId);
783
+
784
+ // Remember the next-in-chain before clearing the body's own pointers;
785
+ // the rest of the group is reached by walking forward from there.
786
+ const start_next = rb.sleep_group_next;
787
+
788
+ rb.sleepState = SleepState.Awake;
789
+ rb.sleep_timer = 0;
790
+ rb.sleep_group_next = -1;
791
+ rb.sleep_group_prev = -1;
792
+ this.storage.mark_awake(index);
793
+
794
+ if (start_next === -1 || start_next === index) return;
795
+
796
+ // Walk the (now-broken) chain forward until we loop back. The chain
797
+ // is circular so we know when to stop; defensive `-1` guards against
798
+ // corruption from a body being unlinked mid-sleep-group.
799
+ let cur = start_next;
800
+ while (cur !== -1 && cur !== index) {
801
+ const cur_rb = this.__bodies[cur];
802
+ if (cur_rb === undefined) break;
803
+ const nxt = cur_rb.sleep_group_next;
804
+ cur_rb.sleepState = SleepState.Awake;
805
+ cur_rb.sleep_timer = 0;
806
+ cur_rb.sleep_group_next = -1;
807
+ cur_rb.sleep_group_prev = -1;
808
+ this.storage.mark_awake(cur);
809
+ cur = nxt;
810
+ }
811
+ }
812
+
813
+ /**
814
+ * Atomically put every body in a contiguous range of island members to
815
+ * sleep. Members are threaded into a circular doubly-linked list so any
816
+ * future `wake` on any member walks the chain and revives them all.
817
+ *
818
+ * Velocities are zeroed because the body is by definition at rest at
819
+ * this point — the alternative (storing residual velocities for "softer"
820
+ * wake) is what Bullet does, but for a deterministic game-physics target
821
+ * fully resetting is simpler and avoids drift while sleeping.
822
+ *
823
+ * @private
824
+ * @param {Uint32Array} member_array view (or full array) of body indices
825
+ * @param {number} start
826
+ * @param {number} end
827
+ */
828
+ __atomic_sleep_island_range(member_array, start, end) {
829
+ const count = end - start;
830
+ if (count === 0) return;
831
+ const bodies = this.__bodies;
832
+ const storage = this.storage;
833
+
834
+ if (count === 1) {
835
+ const idx = member_array[start];
836
+ const rb = bodies[idx];
837
+ if (rb === undefined) return;
838
+ rb.sleep_group_next = -1;
839
+ rb.sleep_group_prev = -1;
840
+ rb.sleepState = SleepState.Sleeping;
841
+ rb.linearVelocity[0] = 0; rb.linearVelocity[1] = 0; rb.linearVelocity[2] = 0;
842
+ rb.angularVelocity[0] = 0; rb.angularVelocity[1] = 0; rb.angularVelocity[2] = 0;
843
+ storage.mark_sleeping(idx);
844
+ return;
845
+ }
846
+
847
+ for (let i = 0; i < count; i++) {
848
+ const idx = member_array[start + i];
849
+ const rb = bodies[idx];
850
+ if (rb === undefined) continue;
851
+ const next_idx = member_array[start + ((i + 1) % count)];
852
+ const prev_idx = member_array[start + ((i - 1 + count) % count)];
853
+ rb.sleep_group_next = next_idx;
854
+ rb.sleep_group_prev = prev_idx;
855
+ rb.sleepState = SleepState.Sleeping;
856
+ rb.linearVelocity[0] = 0; rb.linearVelocity[1] = 0; rb.linearVelocity[2] = 0;
857
+ rb.angularVelocity[0] = 0; rb.angularVelocity[1] = 0; rb.angularVelocity[2] = 0;
858
+ storage.mark_sleeping(idx);
859
+ }
860
+ }
861
+
862
+ /**
863
+ * Get the body index for a packed body id without revalidation. Used by
864
+ * query traversals that already trust the id came from a live BVH leaf.
865
+ * @param {number} packed_body_id
866
+ * @returns {number}
867
+ */
868
+ __index_of(packed_body_id) {
869
+ return body_id_index(packed_body_id);
870
+ }
871
+
872
+ /**
873
+ * Broadphase raycast against both BVHs. Fills `result` with the nearest
874
+ * hit and returns `true` on hit, `false` on miss.
875
+ *
876
+ * Narrowphase refinement against the actual shape geometry is a
877
+ * follow-up — for now `result.t` is the distance to the leaf's
878
+ * inflated AABB and `result.normal` is the AABB face normal. Both are
879
+ * exact for AABB-shaped colliders.
880
+ *
881
+ * @param {Ray3} ray origin + unit direction + `tMax`
882
+ * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
883
+ * @param {(entity:number, collider:Collider)=>boolean} [filter] defaults
884
+ * to {@link returnTrue} (accept every candidate)
885
+ * @returns {boolean}
886
+ */
887
+ raycast(ray, result, filter = returnTrue) {
888
+ return raycast_query(this, ray, result, filter);
889
+ }
890
+
891
+ /**
892
+ * Sweep a convex shape along a ray and find the first body it
893
+ * would hit. The shape starts at `ray.origin` oriented by
894
+ * `rotation` and translates along `ray.direction` for up to
895
+ * `ray.tMax` units. Returns the nearest impact within that
896
+ * interval.
897
+ *
898
+ * The "swept AABB" broadphase finds candidate bodies whose BVH
899
+ * leaves overlap the shape's swept volume; the narrowphase then
900
+ * bisects [0, t] on GJK overlap to find the time-of-impact for
901
+ * each candidate. Best-t early termination skips candidates that
902
+ * can't tighten the answer.
903
+ *
904
+ * @param {Ray3} ray origin + unit direction + `tMax`
905
+ * @param {AbstractShape3D} shape
906
+ * @param {{x:number,y:number,z:number,w:number}} rotation
907
+ * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
908
+ * @param {(entity:number, collider:Collider)=>boolean} [filter]
909
+ * @returns {boolean}
910
+ */
911
+ shapeCast(ray, shape, rotation, result, filter = returnTrue) {
912
+ return shape_cast_query(this, ray, shape, rotation, result, filter);
913
+ }
914
+
915
+ /**
916
+ * Speculative overlap query: find all bodies whose collider would
917
+ * overlap the given convex shape placed at the given world pose,
918
+ * without mutating the simulation. Intended for kinematic /
919
+ * character controllers that need to test "would I collide if I
920
+ * moved here?" before committing the move.
921
+ *
922
+ * Pipeline:
923
+ * 1. The shape's world AABB is computed from `position` + `rotation`.
924
+ * 2. Both broadphase trees (static + dynamic) are queried for
925
+ * bodies whose leaf AABB overlaps that envelope.
926
+ * 3. Each candidate is GJK-tested in world frame. Convex
927
+ * candidates run one GJK call; concave candidates (heightmap,
928
+ * mesh) run per-triangle GJK via the decomposition path.
929
+ * 4. The optional `filter` is consulted before the GJK test —
930
+ * useful for skipping the caller's own body, allies, sensors,
931
+ * etc.
932
+ *
933
+ * The output buffer is filled with overlapping bodies' `body_id`
934
+ * values (uint32 with packed generation), starting at
935
+ * `output_offset`. The caller is responsible for sizing the buffer;
936
+ * IDs past its end are dropped silently and the count caps at the
937
+ * available space.
938
+ *
939
+ * The query shape must be convex. Concave query shapes throw
940
+ * they're typically static terrain and not used as kinematic
941
+ * probes; the M×N triangle-pair cost wouldn't be worth the rare
942
+ * use case.
943
+ *
944
+ * @param {AbstractShape3D} shape convex query shape, in its local frame
945
+ * @param {{x:number,y:number,z:number}} position world position of
946
+ * the query shape
947
+ * @param {{x:number,y:number,z:number,w:number}} rotation world
948
+ * rotation (unit quaternion)
949
+ * @param {Uint32Array|number[]} output buffer to receive body_ids
950
+ * @param {number} output_offset starting index in output
951
+ * @param {(entity:number, collider:Collider)=>boolean} [filter]
952
+ * defaults to {@link returnTrue}
953
+ * @returns {number} number of overlapping bodies written
954
+ */
955
+ overlap(shape, position, rotation, output, output_offset, filter = returnTrue) {
956
+ return overlap_shape_query(this, shape, position, rotation, output, output_offset, filter);
957
+ }
958
+
959
+ /**
960
+ * Run one simulation step. v1 pipeline: integrate velocity → integrate
961
+ * position → refit broadphase AABBs. Narrowphase, solver, islands and
962
+ * contact-event emission land in subsequent slices.
963
+ *
964
+ * @param {number} dt
965
+ */
966
+ /**
967
+ * Wake any sleeping body that appears in this step's broadphase pair list.
968
+ * A pair means the BVH AABBs overlap — even if the sleeper hasn't moved,
969
+ * an awake neighbour has come into contact range and the sleeper must
970
+ * participate in narrowphase / solve.
971
+ * @private
972
+ */
973
+ __wake_pairs() {
974
+ const list = this.pairs;
975
+ const n = list.count;
976
+ const bodies = this.__bodies;
977
+ for (let i = 0; i < n; i++) {
978
+ const idA = list.get_a(i);
979
+ const idB = list.get_b(i);
980
+ const idxA = body_id_index(idA);
981
+ const idxB = body_id_index(idB);
982
+ const a = bodies[idxA];
983
+ const b = bodies[idxB];
984
+ if (a !== undefined && a.sleepState === SleepState.Sleeping) {
985
+ this.__wake_body(a);
986
+ }
987
+ if (b !== undefined && b.sleepState === SleepState.Sleeping) {
988
+ this.__wake_body(b);
989
+ }
990
+ }
991
+ }
992
+
993
+ /**
994
+ * Per-island atomic sleep test. Walks each island once and applies the
995
+ * decision uniformly across all members:
996
+ *
997
+ * - If any member carries {@link RigidBodyFlags.DisableSleep}, the
998
+ * entire island is exempt; every member's sleep_timer is reset.
999
+ * - If `max(|v|² + |ω|²)` across all members is below
1000
+ * {@link sleepVelocitySqrThreshold}, every member's sleep_timer is
1001
+ * incremented by `dt`. When the smallest member's timer crosses
1002
+ * {@link sleepTimeThreshold}, the whole island sleeps atomically in
1003
+ * the same step (members get threaded into a sleep-group chain so
1004
+ * {@link __wake_body} can wake them all in one call).
1005
+ * - Otherwise the island has at least one active member, so every
1006
+ * member's timer is reset.
1007
+ *
1008
+ * This is the design-plan atomic-island sleep replaces the per-body
1009
+ * approximation that lived in this slot during the previous slice.
1010
+ * Weakly-connected piles no longer chatter awake when a single member
1011
+ * blips above threshold; piles fall asleep and wake up as one.
1012
+ *
1013
+ * @private
1014
+ * @param {number} dt
1015
+ */
1016
+ __sleep_test(dt) {
1017
+ const threshold_sqr = this.sleepVelocitySqrThreshold;
1018
+ const time_threshold = this.sleepTimeThreshold;
1019
+ const bodies = this.__bodies;
1020
+ const islands = this.islands;
1021
+ const island_count = islands.island_count;
1022
+ const body_offsets = islands.body_offsets;
1023
+ const body_data = islands.body_data;
1024
+
1025
+ for (let isl = 0; isl < island_count; isl++) {
1026
+ const start = body_offsets[isl];
1027
+ const end = body_offsets[isl + 1];
1028
+ if (end === start) continue;
1029
+
1030
+ // Pass 1: find max v² + check DisableSleep across the island.
1031
+ let max_v_sqr = 0;
1032
+ let any_disable_sleep = false;
1033
+ for (let i = start; i < end; i++) {
1034
+ const idx = body_data[i];
1035
+ const rb = bodies[idx];
1036
+ if (rb === undefined) continue;
1037
+ if ((rb.flags & RigidBodyFlags.DisableSleep) !== 0) {
1038
+ any_disable_sleep = true;
1039
+ break;
1040
+ }
1041
+ const lv = rb.linearVelocity;
1042
+ const av = rb.angularVelocity;
1043
+ const v_sqr = lv[0] * lv[0] + lv[1] * lv[1] + lv[2] * lv[2]
1044
+ + av[0] * av[0] + av[1] * av[1] + av[2] * av[2];
1045
+ if (v_sqr > max_v_sqr) max_v_sqr = v_sqr;
1046
+ }
1047
+
1048
+ if (any_disable_sleep) {
1049
+ // Whole island is exempt — reset every member's timer.
1050
+ for (let i = start; i < end; i++) {
1051
+ const rb = bodies[body_data[i]];
1052
+ if (rb !== undefined) rb.sleep_timer = 0;
1053
+ }
1054
+ continue;
1055
+ }
1056
+
1057
+ if (max_v_sqr < threshold_sqr) {
1058
+ // Island is at rest — increment every member's timer; if the
1059
+ // slowest-stabilising member has crossed the time threshold,
1060
+ // every member has (they were incremented together this step),
1061
+ // so atomic-sleep the island.
1062
+ let min_timer = Infinity;
1063
+ for (let i = start; i < end; i++) {
1064
+ const rb = bodies[body_data[i]];
1065
+ if (rb === undefined) continue;
1066
+ rb.sleep_timer += dt;
1067
+ if (rb.sleep_timer < min_timer) min_timer = rb.sleep_timer;
1068
+ }
1069
+ if (min_timer >= time_threshold) {
1070
+ this.__atomic_sleep_island_range(body_data, start, end);
1071
+ }
1072
+ } else {
1073
+ // At least one member is active — reset every timer.
1074
+ for (let i = start; i < end; i++) {
1075
+ const rb = bodies[body_data[i]];
1076
+ if (rb !== undefined) rb.sleep_timer = 0;
1077
+ }
1078
+ }
1079
+ }
1080
+ }
1081
+
1082
+ /**
1083
+ * Dispatch every buffered contact event through:
1084
+ * - the system-level Signals ({@link onContactBegin}/Stay/End), always; and
1085
+ * - the entity-level event channel via `dataset.sendEvent(entity, name, payload)`,
1086
+ * when a dataset is attached.
1087
+ *
1088
+ * Payload is a reused scratch object; listeners must copy anything they
1089
+ * intend to retain past the listener body.
1090
+ * @private
1091
+ */
1092
+ __dispatch_contact_events() {
1093
+ const events = this.contactEvents;
1094
+ const n = events.count;
1095
+ if (n === 0) return;
1096
+
1097
+ const ecd = (this.entityManager !== null && this.entityManager !== undefined)
1098
+ ? this.entityManager.dataset
1099
+ : null;
1100
+ const manifolds = this.manifolds;
1101
+ const data = manifolds.data_buffer;
1102
+
1103
+ const payload = this.__contact_payload;
1104
+
1105
+ for (let i = 0; i < n; i++) {
1106
+ const kind = events.kind_at(i);
1107
+ const entA = events.entityA_at(i);
1108
+ const entB = events.entityB_at(i);
1109
+ const slot = events.slot_at(i);
1110
+
1111
+ // Use the deepest contact of the manifold as the representative
1112
+ // point/normal/depth for the event. v1: contact 0 only.
1113
+ const slot_off = manifolds.slot_data_offset(slot);
1114
+ const has_contact = manifolds.contact_count(slot) > 0;
1115
+
1116
+ // Scratch payload — no observers subscribe to its component
1117
+ // vectors; write indices directly to skip the Signal dispatch.
1118
+ const pt = payload.point;
1119
+ const nm = payload.normal;
1120
+ if (has_contact) {
1121
+ const wax = data[slot_off], way = data[slot_off + 1], waz = data[slot_off + 2];
1122
+ const wbx = data[slot_off + 3], wby = data[slot_off + 4], wbz = data[slot_off + 5];
1123
+ pt[0] = (wax + wbx) * 0.5; pt[1] = (way + wby) * 0.5; pt[2] = (waz + wbz) * 0.5;
1124
+ nm[0] = data[slot_off + 6]; nm[1] = data[slot_off + 7]; nm[2] = data[slot_off + 8];
1125
+ payload.depth = data[slot_off + 9];
1126
+ } else {
1127
+ pt[0] = 0; pt[1] = 0; pt[2] = 0;
1128
+ nm[0] = 0; nm[1] = 0; nm[2] = 0;
1129
+ payload.depth = 0;
1130
+ }
1131
+ payload.entityA = entA;
1132
+ payload.entityB = entB;
1133
+
1134
+ let event_name;
1135
+ let signal;
1136
+ if (kind === ContactEventKind.Begin) { event_name = PhysicsEvents.ContactBegin; signal = this.onContactBegin; }
1137
+ else if (kind === ContactEventKind.Stay) { event_name = PhysicsEvents.ContactStay; signal = this.onContactStay; }
1138
+ else { event_name = PhysicsEvents.ContactEnd; signal = this.onContactEnd; }
1139
+
1140
+ signal.send1(payload);
1141
+
1142
+ if (ecd !== null && ecd !== undefined) {
1143
+ if (entA >= 0) ecd.sendEvent(entA, event_name, payload);
1144
+ if (entB >= 0) ecd.sendEvent(entB, event_name, payload);
1145
+ }
1146
+ }
1147
+ }
1148
+
1149
+ fixedUpdate(dt) {
1150
+ const gx = this.gravity.x;
1151
+ const gy = this.gravity.y;
1152
+ const gz = this.gravity.z;
1153
+
1154
+ const count = this.storage.awake_count;
1155
+
1156
+ // Stage 1: consume the per-frame force / torque accumulators into
1157
+ // velocity at the full `dt`, exactly once (a user force is a per-frame
1158
+ // budget that must land in full regardless of substep count). Gravity
1159
+ // is applied per substep below, so the trajectory integrates at the
1160
+ // substep rate and — crucially — each substep's gravity is balanced by
1161
+ // that substep's contact warm-start, keeping resting stacks at zero
1162
+ // velocity.
1163
+ for (let i = 0; i < count; i++) {
1164
+ const idx = this.storage.awake_at(i);
1165
+ const rb = this.__bodies[idx];
1166
+ const tr = this.__transforms[idx];
1167
+ integrate_velocity_forces(rb, tr, dt);
1168
+ }
1169
+
1170
+ // Stage 2: refit each awake body's collider leaves at the current
1171
+ // pose, padded by the swept extent for the body's velocity. The fat
1172
+ // margin uses the post-force velocity; this frame's gravity increment
1173
+ // is a sub-millimetre slack difference, safely inside the margin.
1174
+ const lists = this.__body_collider_lists;
1175
+ for (let i = 0; i < count; i++) {
1176
+ const idx = this.storage.awake_at(i);
1177
+ const rb = this.__bodies[idx];
1178
+ const list = lists[idx];
1179
+ if (list === undefined) continue;
1180
+ const lv = rb.linearVelocity;
1181
+ for (let k = 0; k < list.length; k++) {
1182
+ const entry = list[k];
1183
+ compute_fat_world_aabb(
1184
+ scratch_world_aabb, 0,
1185
+ entry.collider.shape, entry.transform,
1186
+ lv[0], lv[1], lv[2],
1187
+ dt
1188
+ );
1189
+ this.dynamicBvh.node_move_aabb(entry.bvhNode, scratch_world_aabb);
1190
+ }
1191
+ }
1192
+
1193
+ // Stage 3: broadphase pair generation. The fat AABBs cover the full
1194
+ // outer-step motion, so the pair set stays valid across all substeps
1195
+ // — broadphase runs once.
1196
+ generate_pairs(
1197
+ this.storage,
1198
+ this.dynamicBvh,
1199
+ this.staticBvh,
1200
+ this.manifolds,
1201
+ lists,
1202
+ this.pairs,
1203
+ this.__pair_filter_bound,
1204
+ );
1205
+
1206
+ // Stage 4: wake propagation.
1207
+ this.__wake_pairs();
1208
+
1209
+ // Stage 5: narrowphase — once per outer step. The substep loop below
1210
+ // re-derives each contact's penetration analytically from the moved
1211
+ // poses rather than re-running geometry.
1212
+ narrowphase_step(this.pairs, this.manifolds, this.__body_collider_lists);
1213
+
1214
+ // Stage 6: partition awake bodies + touched contacts into islands.
1215
+ // Consumed by the solver (flattened contact list) and the sleep test.
1216
+ this.islands.build(this.storage, this.manifolds, this.__bodies, this.__body_collider_lists);
1217
+
1218
+ // Stage 7: TGS substep loop.
1219
+ //
1220
+ // prepare_contacts captures per-contact anchors / effective masses /
1221
+ // approach velocity (no warm-start — that's per-substep). Each substep
1222
+ // integrates gravity by `h`, re-derives contact geometry from the
1223
+ // current poses, replays warm-start, solves velocity (non-penetration
1224
+ // + friction) and position (pseudo-velocity), and integrates the pose
1225
+ // by `h`. Per-substep gravity + per-substep warm-start balance exactly
1226
+ // at a resting contact (each cancels `h` of the other), so stacks hold
1227
+ // at zero velocity and sleep; the position correction adapts as bodies
1228
+ // separate between substeps — the TGS stack-stability mechanism —
1229
+ // without re-running narrowphase. Restitution is applied once after
1230
+ // the loop.
1231
+ const N = this.substeps;
1232
+ const h = dt / N;
1233
+ const count_after_wake = this.storage.awake_count;
1234
+
1235
+ // Size the pseudo-velocity buffer ONCE (it may reallocate on growth),
1236
+ // then capture the reference. Inside the loop we only zero its live
1237
+ // region per substep — re-capturing is unnecessary since it won't
1238
+ // reallocate again this step.
1239
+ this.__reset_pseudo_velocity();
1240
+ const pseudoVel = this.__pseudo_velocity;
1241
+ const pseudo_len = this.storage.high_water_mark * 6;
1242
+
1243
+ prepare_contacts(this.manifolds, this, h);
1244
+
1245
+ for (let s = 0; s < N; s++) {
1246
+ // Gravity (+ damping) for this substep.
1247
+ for (let i = 0; i < count_after_wake; i++) {
1248
+ const idx = this.storage.awake_at(i);
1249
+ integrate_velocity_gravity(this.__bodies[idx], this.__transforms[idx], gx, gy, gz, h);
1250
+ }
1251
+
1252
+ // Re-derive contact geometry at the current poses, replay the
1253
+ // per-substep warm-start, then solve velocity.
1254
+ refresh_contacts(this.manifolds, this);
1255
+ warm_start_contacts(this.manifolds, this);
1256
+ solve_velocity(this.manifolds, this, this.velocityIterations);
1257
+
1258
+ // Position correction writes pseudo-velocity (zeroed first so it
1259
+ // is a fresh per-substep correction), folded into the pose by the
1260
+ // position integrate and then discarded.
1261
+ pseudoVel.fill(0, 0, pseudo_len);
1262
+ solve_position(this.manifolds, this, this.positionIterations);
1263
+
1264
+ for (let i = 0; i < count_after_wake; i++) {
1265
+ const idx = this.storage.awake_at(i);
1266
+ const rb = this.__bodies[idx];
1267
+ const tr = this.__transforms[idx];
1268
+ const base = idx * 6;
1269
+ integrate_position(rb, tr, h,
1270
+ pseudoVel[base], pseudoVel[base + 1], pseudoVel[base + 2],
1271
+ pseudoVel[base + 3], pseudoVel[base + 4], pseudoVel[base + 5]);
1272
+ }
1273
+ }
1274
+
1275
+ // Stage 8: one-shot restitution, after the substep loop, keyed off
1276
+ // the approach velocity captured at prepare time.
1277
+ apply_restitution(this.manifolds, this);
1278
+
1279
+ // Stage 9: sleep test.
1280
+ this.__sleep_test(dt);
1281
+
1282
+ // Stage 10: diff manifolds against the previous frame and dispatch
1283
+ // Begin / Stay / End events. MUST run before advance_frame, which
1284
+ // rolls the touched flags.
1285
+ diff_manifolds(this.manifolds, this.storage, this.contactEvents);
1286
+ this.__dispatch_contact_events();
1287
+
1288
+ // Stage 11 (end-of-step): roll touched → prev_touched and evict slots
1289
+ // whose pair has not been touched within the grace window.
1290
+ this.manifolds.advance_frame();
1291
+ }
1292
+ }
1293
+
1294
+ /**
1295
+ * @readonly
1296
+ * @type {boolean}
1297
+ */
1298
+ PhysicsSystem.prototype.isPhysicsSystem = true;
1299
+
1300
+ // Re-export for convenience.
1301
+ export { BodyKind, RigidBodyFlags };