@luma.gl/graph 10.0.0-beta.2 → 10.0.0-beta.3

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 (258) hide show
  1. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.cjs +22 -9
  2. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts +11 -2
  3. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts.map +1 -1
  4. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js +27 -10
  5. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js.map +1 -1
  6. package/dist/arrow/gpu/arrow-gpu-analytics-readback.cjs +24 -13
  7. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts +9 -1
  8. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts.map +1 -1
  9. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js +41 -14
  10. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js.map +1 -1
  11. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +24 -1
  12. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +10 -1
  13. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts.map +1 -1
  14. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +29 -1
  15. package/dist/arrow/gpu/arrow-gpu-table-conversion.js.map +1 -1
  16. package/dist/arrow/index.cjs +2 -0
  17. package/dist/arrow/index.cjs.map +3 -3
  18. package/dist/arrow/index.d.ts +1 -1
  19. package/dist/arrow/index.d.ts.map +1 -1
  20. package/dist/arrow/index.js +1 -1
  21. package/dist/arrow/index.js.map +1 -1
  22. package/dist/gpu-core/gpu-bvh-bounds.cjs +63 -0
  23. package/dist/gpu-core/gpu-bvh-bounds.d.ts +32 -0
  24. package/dist/gpu-core/gpu-bvh-bounds.d.ts.map +1 -0
  25. package/dist/gpu-core/gpu-bvh-bounds.js +56 -0
  26. package/dist/gpu-core/gpu-bvh-bounds.js.map +1 -0
  27. package/dist/gpu-core/gpu-command-graph-submission-pacer.cjs +92 -0
  28. package/dist/gpu-core/gpu-command-graph-submission-pacer.d.ts +41 -0
  29. package/dist/gpu-core/gpu-command-graph-submission-pacer.d.ts.map +1 -0
  30. package/dist/gpu-core/gpu-command-graph-submission-pacer.js +85 -0
  31. package/dist/gpu-core/gpu-command-graph-submission-pacer.js.map +1 -0
  32. package/dist/gpu-core/index.cjs +6 -0
  33. package/dist/gpu-core/index.cjs.map +3 -3
  34. package/dist/gpu-core/index.d.ts +4 -0
  35. package/dist/gpu-core/index.d.ts.map +1 -1
  36. package/dist/gpu-core/index.js +2 -0
  37. package/dist/gpu-core/index.js.map +1 -1
  38. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.cjs +6 -6
  39. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts +1 -1
  40. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts.map +1 -1
  41. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js +6 -6
  42. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js.map +1 -1
  43. package/dist/gpu-dataframe/gpu-data-frame-query.cjs +55 -14
  44. package/dist/gpu-dataframe/gpu-data-frame-query.d.ts +13 -2
  45. package/dist/gpu-dataframe/gpu-data-frame-query.d.ts.map +1 -1
  46. package/dist/gpu-dataframe/gpu-data-frame-query.js +58 -17
  47. package/dist/gpu-dataframe/gpu-data-frame-query.js.map +1 -1
  48. package/dist/gpu-dataframe/gpu-data-frame.cjs +1 -3
  49. package/dist/gpu-dataframe/gpu-data-frame.d.ts +10 -0
  50. package/dist/gpu-dataframe/gpu-data-frame.d.ts.map +1 -1
  51. package/dist/gpu-dataframe/gpu-data-frame.js +1 -3
  52. package/dist/gpu-dataframe/gpu-data-frame.js.map +1 -1
  53. package/dist/gpu-dataframe/gpu-expression-shader.cjs +94 -44
  54. package/dist/gpu-dataframe/gpu-expression-shader.d.ts +8 -5
  55. package/dist/gpu-dataframe/gpu-expression-shader.d.ts.map +1 -1
  56. package/dist/gpu-dataframe/gpu-expression-shader.js +110 -47
  57. package/dist/gpu-dataframe/gpu-expression-shader.js.map +1 -1
  58. package/dist/gpu-dataframe/gpu-expression.cjs +14 -8
  59. package/dist/gpu-dataframe/gpu-expression.d.ts +12 -1
  60. package/dist/gpu-dataframe/gpu-expression.d.ts.map +1 -1
  61. package/dist/gpu-dataframe/gpu-expression.js +11 -6
  62. package/dist/gpu-dataframe/gpu-expression.js.map +1 -1
  63. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.cjs +2 -2
  64. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.d.ts.map +1 -1
  65. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js +4 -2
  66. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js.map +1 -1
  67. package/dist/gpu-dataframe/gpu-global-aggregation-query.cjs +2 -2
  68. package/dist/gpu-dataframe/gpu-global-aggregation-query.d.ts +5 -1
  69. package/dist/gpu-dataframe/gpu-global-aggregation-query.d.ts.map +1 -1
  70. package/dist/gpu-dataframe/gpu-global-aggregation-query.js +6 -2
  71. package/dist/gpu-dataframe/gpu-global-aggregation-query.js.map +1 -1
  72. package/dist/gpu-dataframe/gpu-global-sort-compiler.cjs +113 -88
  73. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts +6 -1
  74. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts.map +1 -1
  75. package/dist/gpu-dataframe/gpu-global-sort-compiler.js +111 -85
  76. package/dist/gpu-dataframe/gpu-global-sort-compiler.js.map +1 -1
  77. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.cjs +286 -48
  78. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts +17 -2
  79. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts.map +1 -1
  80. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js +290 -39
  81. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js.map +1 -1
  82. package/dist/gpu-dataframe/gpu-group-by-query.cjs +8 -6
  83. package/dist/gpu-dataframe/gpu-group-by-query.d.ts +7 -1
  84. package/dist/gpu-dataframe/gpu-group-by-query.d.ts.map +1 -1
  85. package/dist/gpu-dataframe/gpu-group-by-query.js +9 -5
  86. package/dist/gpu-dataframe/gpu-group-by-query.js.map +1 -1
  87. package/dist/gpu-dataframe/gpu-join-compiler.cjs +8 -6
  88. package/dist/gpu-dataframe/gpu-join-compiler.d.ts +1 -1
  89. package/dist/gpu-dataframe/gpu-join-compiler.d.ts.map +1 -1
  90. package/dist/gpu-dataframe/gpu-join-compiler.js +9 -7
  91. package/dist/gpu-dataframe/gpu-join-compiler.js.map +1 -1
  92. package/dist/gpu-dataframe/gpu-query-compiler.cjs +37 -11
  93. package/dist/gpu-dataframe/gpu-query-compiler.d.ts +3 -1
  94. package/dist/gpu-dataframe/gpu-query-compiler.d.ts.map +1 -1
  95. package/dist/gpu-dataframe/gpu-query-compiler.js +36 -10
  96. package/dist/gpu-dataframe/gpu-query-compiler.js.map +1 -1
  97. package/dist/gpu-dataframe/index.cjs +4 -2
  98. package/dist/gpu-dataframe/index.cjs.map +3 -3
  99. package/dist/gpu-dataframe/index.d.ts +1 -1
  100. package/dist/gpu-dataframe/index.d.ts.map +1 -1
  101. package/dist/gpu-dataframe/index.js +1 -1
  102. package/dist/gpu-dataframe/index.js.map +1 -1
  103. package/dist/gpu-physics/gpu-physics-batch.cjs +11 -10
  104. package/dist/gpu-physics/gpu-physics-batch.d.ts +1 -0
  105. package/dist/gpu-physics/gpu-physics-batch.d.ts.map +1 -1
  106. package/dist/gpu-physics/gpu-physics-batch.js +14 -10
  107. package/dist/gpu-physics/gpu-physics-batch.js.map +1 -1
  108. package/dist/gpu-physics/gpu-physics-ensemble.cjs +9 -4
  109. package/dist/gpu-physics/gpu-physics-ensemble.d.ts +10 -1
  110. package/dist/gpu-physics/gpu-physics-ensemble.d.ts.map +1 -1
  111. package/dist/gpu-physics/gpu-physics-ensemble.js +11 -4
  112. package/dist/gpu-physics/gpu-physics-ensemble.js.map +1 -1
  113. package/dist/gpu-physics/gpu-rigid-body-world.cjs +261 -68
  114. package/dist/gpu-physics/gpu-rigid-body-world.d.ts +47 -2
  115. package/dist/gpu-physics/gpu-rigid-body-world.d.ts.map +1 -1
  116. package/dist/gpu-physics/gpu-rigid-body-world.js +324 -75
  117. package/dist/gpu-physics/gpu-rigid-body-world.js.map +1 -1
  118. package/dist/gpu-physics/index.cjs.map +3 -3
  119. package/dist/gpu-physics/index.d.ts +2 -1
  120. package/dist/gpu-physics/index.d.ts.map +1 -1
  121. package/dist/gpu-physics/index.js.map +1 -1
  122. package/dist/gpu-physics/rigid-body-cache-shaders.cjs +10 -6
  123. package/dist/gpu-physics/rigid-body-cache-shaders.d.ts +2 -1
  124. package/dist/gpu-physics/rigid-body-cache-shaders.d.ts.map +1 -1
  125. package/dist/gpu-physics/rigid-body-cache-shaders.js +15 -6
  126. package/dist/gpu-physics/rigid-body-cache-shaders.js.map +1 -1
  127. package/dist/gpu-physics/rigid-body-capacity.cjs +15 -2
  128. package/dist/gpu-physics/rigid-body-capacity.d.ts +3 -1
  129. package/dist/gpu-physics/rigid-body-capacity.d.ts.map +1 -1
  130. package/dist/gpu-physics/rigid-body-capacity.js +21 -2
  131. package/dist/gpu-physics/rigid-body-capacity.js.map +1 -1
  132. package/dist/gpu-physics/rigid-body-cast-index.cjs +192 -0
  133. package/dist/gpu-physics/rigid-body-cast-index.d.ts +44 -0
  134. package/dist/gpu-physics/rigid-body-cast-index.d.ts.map +1 -0
  135. package/dist/gpu-physics/rigid-body-cast-index.js +194 -0
  136. package/dist/gpu-physics/rigid-body-cast-index.js.map +1 -0
  137. package/dist/gpu-physics/rigid-body-ensemble-layout.cjs +4 -2
  138. package/dist/gpu-physics/rigid-body-ensemble-layout.d.ts +2 -1
  139. package/dist/gpu-physics/rigid-body-ensemble-layout.d.ts.map +1 -1
  140. package/dist/gpu-physics/rigid-body-ensemble-layout.js +5 -2
  141. package/dist/gpu-physics/rigid-body-ensemble-layout.js.map +1 -1
  142. package/dist/gpu-physics/rigid-body-ensemble-reset.cjs +11 -9
  143. package/dist/gpu-physics/rigid-body-ensemble-reset.d.ts +1 -1
  144. package/dist/gpu-physics/rigid-body-ensemble-reset.d.ts.map +1 -1
  145. package/dist/gpu-physics/rigid-body-ensemble-reset.js +13 -9
  146. package/dist/gpu-physics/rigid-body-ensemble-reset.js.map +1 -1
  147. package/dist/gpu-physics/rigid-body-ensemble-shaders.cjs +14 -7
  148. package/dist/gpu-physics/rigid-body-ensemble-shaders.d.ts +5 -0
  149. package/dist/gpu-physics/rigid-body-ensemble-shaders.d.ts.map +1 -1
  150. package/dist/gpu-physics/rigid-body-ensemble-shaders.js +17 -7
  151. package/dist/gpu-physics/rigid-body-ensemble-shaders.js.map +1 -1
  152. package/dist/gpu-physics/rigid-body-ensemble-transaction.cjs +21 -11
  153. package/dist/gpu-physics/rigid-body-ensemble-transaction.d.ts +2 -2
  154. package/dist/gpu-physics/rigid-body-ensemble-transaction.d.ts.map +1 -1
  155. package/dist/gpu-physics/rigid-body-ensemble-transaction.js +28 -12
  156. package/dist/gpu-physics/rigid-body-ensemble-transaction.js.map +1 -1
  157. package/dist/gpu-physics/rigid-body-event-compaction.cjs +184 -0
  158. package/dist/gpu-physics/rigid-body-event-compaction.d.ts +35 -0
  159. package/dist/gpu-physics/rigid-body-event-compaction.d.ts.map +1 -0
  160. package/dist/gpu-physics/rigid-body-event-compaction.js +168 -0
  161. package/dist/gpu-physics/rigid-body-event-compaction.js.map +1 -0
  162. package/dist/gpu-physics/rigid-body-event-snapshot.cjs +51 -0
  163. package/dist/gpu-physics/rigid-body-event-snapshot.d.ts +33 -0
  164. package/dist/gpu-physics/rigid-body-event-snapshot.d.ts.map +1 -0
  165. package/dist/gpu-physics/rigid-body-event-snapshot.js +34 -0
  166. package/dist/gpu-physics/rigid-body-event-snapshot.js.map +1 -0
  167. package/dist/gpu-physics/rigid-body-events.cjs +57 -25
  168. package/dist/gpu-physics/rigid-body-events.d.ts +2 -1
  169. package/dist/gpu-physics/rigid-body-events.d.ts.map +1 -1
  170. package/dist/gpu-physics/rigid-body-events.js +60 -25
  171. package/dist/gpu-physics/rigid-body-events.js.map +1 -1
  172. package/dist/gpu-physics/rigid-body-joints.cjs +8 -3
  173. package/dist/gpu-physics/rigid-body-joints.d.ts.map +1 -1
  174. package/dist/gpu-physics/rigid-body-joints.js +10 -6
  175. package/dist/gpu-physics/rigid-body-joints.js.map +1 -1
  176. package/dist/gpu-physics/rigid-body-queries.cjs +159 -16
  177. package/dist/gpu-physics/rigid-body-queries.d.ts +24 -1
  178. package/dist/gpu-physics/rigid-body-queries.d.ts.map +1 -1
  179. package/dist/gpu-physics/rigid-body-queries.js +166 -14
  180. package/dist/gpu-physics/rigid-body-queries.js.map +1 -1
  181. package/dist/gpu-physics/rigid-body-shaders.cjs +3 -3
  182. package/dist/gpu-physics/rigid-body-shaders.d.ts +1 -1
  183. package/dist/gpu-physics/rigid-body-shaders.d.ts.map +1 -1
  184. package/dist/gpu-physics/rigid-body-shaders.js +3 -3
  185. package/dist/gpu-physics/rigid-body-shaders.js.map +1 -1
  186. package/dist/gpu-physics/rigid-body-triggers.cjs +53 -15
  187. package/dist/gpu-physics/rigid-body-triggers.d.ts +1 -0
  188. package/dist/gpu-physics/rigid-body-triggers.d.ts.map +1 -1
  189. package/dist/gpu-physics/rigid-body-triggers.js +55 -15
  190. package/dist/gpu-physics/rigid-body-triggers.js.map +1 -1
  191. package/dist/gpu-physics/sphere-world-shaders.cjs +48 -20
  192. package/dist/gpu-physics/sphere-world-shaders.d.ts.map +1 -1
  193. package/dist/gpu-physics/sphere-world-shaders.js +51 -21
  194. package/dist/gpu-physics/sphere-world-shaders.js.map +1 -1
  195. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  196. package/dist/gpu-project/crs.cjs.map +2 -2
  197. package/dist/gpu-project/index.cjs.map +2 -2
  198. package/dist/gpu-project/projection-program.cjs +2 -9
  199. package/dist/gpu-project/projection-program.d.ts.map +1 -1
  200. package/dist/gpu-project/projection-program.js +1 -8
  201. package/dist/gpu-project/projection-program.js.map +1 -1
  202. package/dist/gpu-sql/gpu-sql.cjs +203 -59
  203. package/dist/gpu-sql/gpu-sql.d.ts +36 -1
  204. package/dist/gpu-sql/gpu-sql.d.ts.map +1 -1
  205. package/dist/gpu-sql/gpu-sql.js +225 -62
  206. package/dist/gpu-sql/gpu-sql.js.map +1 -1
  207. package/dist/gpu-sql/index.cjs.map +3 -3
  208. package/dist/gpu-sql/index.d.ts +1 -1
  209. package/dist/gpu-sql/index.d.ts.map +1 -1
  210. package/dist/utils/float32.cjs +35 -0
  211. package/dist/utils/float32.d.ts +3 -0
  212. package/dist/utils/float32.d.ts.map +1 -0
  213. package/dist/utils/float32.js +16 -0
  214. package/dist/utils/float32.js.map +1 -0
  215. package/package.json +4 -4
  216. package/src/arrow/gpu/arrow-gpu-analytics-adapters.ts +77 -25
  217. package/src/arrow/gpu/arrow-gpu-analytics-readback.ts +52 -16
  218. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +46 -1
  219. package/src/arrow/index.ts +1 -0
  220. package/src/gpu-core/gpu-bvh-bounds.ts +84 -0
  221. package/src/gpu-core/gpu-command-graph-submission-pacer.ts +102 -0
  222. package/src/gpu-core/index.ts +5 -0
  223. package/src/gpu-dataframe/gpu-analytics-compiler-utils.ts +7 -10
  224. package/src/gpu-dataframe/gpu-data-frame-query.ts +106 -25
  225. package/src/gpu-dataframe/gpu-data-frame.ts +35 -2
  226. package/src/gpu-dataframe/gpu-expression-shader.ts +172 -58
  227. package/src/gpu-dataframe/gpu-expression.ts +62 -9
  228. package/src/gpu-dataframe/gpu-global-aggregation-compiler.ts +6 -2
  229. package/src/gpu-dataframe/gpu-global-aggregation-query.ts +12 -3
  230. package/src/gpu-dataframe/gpu-global-sort-compiler.ts +151 -93
  231. package/src/gpu-dataframe/gpu-group-aggregation-compiler.ts +469 -52
  232. package/src/gpu-dataframe/gpu-group-by-query.ts +24 -10
  233. package/src/gpu-dataframe/gpu-join-compiler.ts +12 -6
  234. package/src/gpu-dataframe/gpu-query-compiler.ts +60 -18
  235. package/src/gpu-dataframe/index.ts +1 -1
  236. package/src/gpu-physics/gpu-physics-batch.ts +19 -13
  237. package/src/gpu-physics/gpu-physics-ensemble.ts +20 -4
  238. package/src/gpu-physics/gpu-rigid-body-world.ts +421 -93
  239. package/src/gpu-physics/index.ts +9 -0
  240. package/src/gpu-physics/rigid-body-cache-shaders.ts +18 -6
  241. package/src/gpu-physics/rigid-body-capacity.ts +25 -4
  242. package/src/gpu-physics/rigid-body-cast-index.ts +277 -0
  243. package/src/gpu-physics/rigid-body-ensemble-layout.ts +6 -2
  244. package/src/gpu-physics/rigid-body-ensemble-reset.ts +21 -9
  245. package/src/gpu-physics/rigid-body-ensemble-shaders.ts +18 -7
  246. package/src/gpu-physics/rigid-body-ensemble-transaction.ts +31 -13
  247. package/src/gpu-physics/rigid-body-event-compaction.ts +252 -0
  248. package/src/gpu-physics/rigid-body-event-snapshot.ts +76 -0
  249. package/src/gpu-physics/rigid-body-events.ts +63 -25
  250. package/src/gpu-physics/rigid-body-joints.ts +9 -11
  251. package/src/gpu-physics/rigid-body-queries.ts +202 -14
  252. package/src/gpu-physics/rigid-body-shaders.ts +4 -3
  253. package/src/gpu-physics/rigid-body-triggers.ts +64 -20
  254. package/src/gpu-physics/sphere-world-shaders.ts +53 -21
  255. package/src/gpu-project/projection-program.ts +1 -9
  256. package/src/gpu-sql/gpu-sql.ts +405 -91
  257. package/src/gpu-sql/index.ts +1 -1
  258. package/src/utils/float32.ts +16 -0
@@ -20,6 +20,7 @@ import {
20
20
 
21
21
  import {
22
22
  GPUCommandGraph,
23
+ type CompiledGPUCommandGraph,
23
24
  type GPUCommandGraphComputeExecutable,
24
25
  type GraphBufferHandle
25
26
  } from '../gpu-core/gpu-command-graph';
@@ -96,13 +97,34 @@ import {
96
97
  getRigidBodyEventShader,
97
98
  type GPURigidBodyContactBatch
98
99
  } from './rigid-body-events';
100
+ import {addRigidBodyEventCompaction} from './rigid-body-event-compaction';
101
+ import {
102
+ readRigidBodyEventSnapshot,
103
+ type GPURigidBodyContactSnapshot,
104
+ type GPURigidBodyTriggerSnapshot
105
+ } from './rigid-body-event-snapshot';
99
106
  import {
100
107
  RIGID_BODY_QUERY_SHADER,
108
+ getRigidBodyBatchCastShader,
109
+ RIGID_BODY_CAST_COMMAND_BYTES,
110
+ RIGID_BODY_BATCH_RESULT_BYTES,
111
+ packRigidBodyBatchCasts,
112
+ decodeRigidBodyBatchCasts,
113
+ decodeRigidBodyQueryHit,
114
+ type GPURigidBodyBatchCast,
115
+ type GPURigidBodyBatchCastOptions,
101
116
  type GPURigidBodyRayQuery,
102
117
  type GPURigidBodySphereCastQuery,
103
118
  type GPURigidBodyOverlapQuery,
104
119
  type GPURigidBodyQueryResult
105
120
  } from './rigid-body-queries';
121
+ import {
122
+ canIndexRigidBodyCastCollider,
123
+ createRigidBodyCastIndex,
124
+ estimateRigidBodyCastIndexBytes,
125
+ getRigidBodyCastOrder,
126
+ type RigidBodyCastOrder
127
+ } from './rigid-body-cast-index';
106
128
 
107
129
  /** One fixed-dimension slot update. A null field evicts the current tile. */
108
130
  export type GPURigidBodyHeightFieldEdit = {
@@ -180,6 +202,8 @@ export type GPURigidBodyWorldProps = {
180
202
  collisionPartitionSize?: number;
181
203
  /** Equal body ranges for GPU-driven ensemble scheduling; requires parallel sparse partitions. */
182
204
  ensembleBodiesPerInstance?: number;
205
+ /** @internal Disjoint persistent contact slots per instance for local capacity recovery. */
206
+ ensemblePairsPerInstance?: number;
183
207
  /** @internal Global collider indices reserved for writable terrain in a fused ensemble. */
184
208
  ensembleTerrainSlots?: readonly number[];
185
209
  /** @internal Optional fused atlas page capacity by reserved grid. */
@@ -201,6 +225,10 @@ export type GPURigidBodyWorldProps = {
201
225
  impactImpulseThreshold?: number;
202
226
  /** Enable GPU ray, sphere-overlap and sphere-sweep queries. */
203
227
  enableQueries?: boolean;
228
+ /** Maximum commands per batched cast. Requires enableQueries. Defaults to zero. */
229
+ queryBatchCapacity?: number;
230
+ /** Refit a GPU spatial index for batched sphere and box collider queries. Requires a batch capacity. */
231
+ queryBatchIndex?: boolean;
204
232
  /** Roll back poses and persistent contacts after an incomplete step; failures latch until reconstruction. */
205
233
  /** Bounded sphere/static-surface CCD; requires rollback failure policy. */
206
234
  continuous?: GPURigidBodyContinuousOptions;
@@ -236,6 +264,14 @@ export type GPURigidBodyGPUCheckpoint = {
236
264
  destroy(): void;
237
265
  };
238
266
 
267
+ /** An incremental read may need a recovery cursor before it can decode its queued bytes. */
268
+ type PendingEventRead<Batch, Snapshot> = {
269
+ /** Hold the latest read until its cursor update finishes. */
270
+ result: Promise<Batch>;
271
+ /** Coalesce reads only when they use the same recovery dependency. */
272
+ afterSnapshot: Promise<Snapshot> | null;
273
+ };
274
+
239
275
  export class GPURigidBodyWorld {
240
276
  private worldOrigin: [number, number, number] = [0, 0, 0];
241
277
  readonly id: string;
@@ -257,13 +293,39 @@ export class GPURigidBodyWorld {
257
293
  sleepStates: Buffer | null = null;
258
294
  /** World-owned GPU event ring; present only when eventCapacity is positive. */
259
295
  contactEvents: Buffer | null = null;
296
+ /** Trigger history and authored group IDs remain stable until world destruction. */
297
+ private triggerHistory: {buffer: Buffer; groups: Uint32Array} | null = null;
298
+ /** Contact activity is recorded in pair-slot order after accepted steps. */
299
+ private contactHistory: Buffer | null = null;
300
+ /** A recovery read shares the incremental trigger cursor. */
301
+ private triggerSnapshotRead: Promise<GPURigidBodyTriggerSnapshot> | null = null;
302
+ /** A recovery read shares the incremental contact cursor. */
303
+ private contactSnapshotRead: Promise<GPURigidBodyContactSnapshot> | null = null;
260
304
  private triggerEvents: Buffer | null = null;
261
305
  private triggerCursor = 0;
262
- private triggerRead: Promise<GPURigidBodyTriggerBatch> | null = null;
306
+ private triggerRead: PendingEventRead<
307
+ GPURigidBodyTriggerBatch,
308
+ GPURigidBodyTriggerSnapshot
309
+ > | null = null;
263
310
  private eventCursor = 0;
264
- private eventRead: Promise<GPURigidBodyContactBatch> | null = null;
311
+ private eventRead: PendingEventRead<
312
+ GPURigidBodyContactBatch,
313
+ GPURigidBodyContactSnapshot
314
+ > | null = null;
265
315
  private queryComputation: BoundKernel | null = null;
266
316
  private queryReduction: BoundKernel | null = null;
317
+ /** Batched nearest-hit computation using the current world pose buffers. */
318
+ private batchCast: BoundKernel | null = null;
319
+ /** Compiled query graph that refits the world BVH and then casts. */
320
+ private batchCastIndex: CompiledGPUCommandGraph<number> | null = null;
321
+ /** Initial spatial order and stable collider ID mapping for indexed batches. */
322
+ private batchCastOrder: RigidBodyCastOrder | null = null;
323
+ /** Query graph reservation before attachment, when the physical plan is unavailable. */
324
+ private readonly batchCastIndexEstimate: number;
325
+ /** Reusable storage for a bounded list of ray and sweep commands. */
326
+ private batchCastCommands: Buffer | null = null;
327
+ /** Reusable GPU output with one compact result per batch command. */
328
+ private batchCastResults: Buffer | null = null;
267
329
  /** Chassis definitions in GPU storage order. */
268
330
  private readonly vehicles: readonly GPURigidBodyVehicle[];
269
331
  /** Whether any chassis has more than one terrain candidate. */
@@ -312,6 +374,16 @@ export class GPURigidBodyWorld {
312
374
  private broadPhaseCounters: {buffer: Buffer; byteOffset: number} | null = null;
313
375
 
314
376
  constructor(props: GPURigidBodyWorldProps) {
377
+ /** Zero leaves the optional command and result buffers unallocated. */
378
+ const queryBatchCapacity = props.queryBatchCapacity ?? 0;
379
+ if (
380
+ !Number.isSafeInteger(queryBatchCapacity) ||
381
+ queryBatchCapacity < 0 ||
382
+ queryBatchCapacity > 65535 ||
383
+ (queryBatchCapacity > 0 && !props.enableQueries) ||
384
+ (props.queryBatchIndex && queryBatchCapacity === 0)
385
+ )
386
+ throw new Error('Invalid collision cast batch capacity');
315
387
  for (const damping of [props.linearDamping ?? 0, props.angularDamping ?? 0]) {
316
388
  if (!Number.isFinite(damping) || damping < 0) throw new Error('Invalid damping');
317
389
  }
@@ -521,6 +593,18 @@ export class GPURigidBodyWorld {
521
593
  (this.maximumPairs & (this.maximumPairs - 1)) !== 0)
522
594
  )
523
595
  throw new Error('Invalid rigid-body pair capacity');
596
+ /** Size each recoverable cache range independently of the shared candidate budget. */
597
+ const instancePairCapacity = props.ensemblePairsPerInstance;
598
+ if (
599
+ instancePairCapacity !== undefined &&
600
+ (!props.ensembleBodiesPerInstance ||
601
+ props.failurePolicy !== 'rollback' ||
602
+ !Number.isSafeInteger(instancePairCapacity) ||
603
+ instancePairCapacity < 1 ||
604
+ instancePairCapacity * (this.count / props.ensembleBodiesPerInstance) > this.maximumPairs ||
605
+ (instancePairCapacity & (instancePairCapacity - 1)) !== 0)
606
+ )
607
+ throw new Error('Invalid ensemble instance contact capacity');
524
608
  if (props.continuous) {
525
609
  if (
526
610
  props.failurePolicy !== 'rollback' ||
@@ -571,6 +655,12 @@ export class GPURigidBodyWorld {
571
655
  const definitions = structuredClone({colliders, props});
572
656
  this.props = definitions.props;
573
657
  this.colliders = definitions.colliders;
658
+ this.batchCastIndexEstimate =
659
+ this.props.queryBatchIndex && this.colliderCount
660
+ ? estimateRigidBodyCastIndexBytes(
661
+ this.colliders.filter(canIndexRigidBodyCastCollider).length
662
+ )
663
+ : 0;
574
664
  this.ensembleTerrainSlots = new Set(this.props.ensembleTerrainSlots);
575
665
  if (
576
666
  this.ensembleTerrainSlots.size &&
@@ -704,7 +794,11 @@ export class GPURigidBodyWorld {
704
794
  this.props.failurePolicy === 'rollback',
705
795
  Boolean(this.props.continuous),
706
796
  this.props.joints?.length ?? 0,
707
- this.props.ensembleBodiesPerInstance ? this.count / this.props.ensembleBodiesPerInstance : 0
797
+ this.props.ensembleBodiesPerInstance
798
+ ? this.count / this.props.ensembleBodiesPerInstance
799
+ : 0,
800
+ Boolean(this.props.ensemblePairsPerInstance),
801
+ this.props.queryBatchCapacity
708
802
  )
709
803
  };
710
804
  if (this.vehicles.length) {
@@ -793,7 +887,8 @@ export class GPURigidBodyWorld {
793
887
  this.props.collisionPartitionSize!,
794
888
  this.maximumPairs,
795
889
  this.vehiclesPerInstance,
796
- this.ensembleTerrainSlots
890
+ this.ensembleTerrainSlots,
891
+ this.props.ensemblePairsPerInstance
797
892
  );
798
893
  return this.ensembleReset.byteLength;
799
894
  }
@@ -843,7 +938,7 @@ export class GPURigidBodyWorld {
843
938
  instance,
844
939
  this.origin.map((value, axis) => value - this.ensembleResetOrigin![axis])
845
940
  );
846
- this.ensembleBuffer!.write(new Uint32Array([0, 0, 0, 0, 1, 1]), (16 + instance * 8 + 1) * 4);
941
+ this.ensembleBuffer!.write(new Uint32Array([0, 0, 0, 0, 1, 1, 0]), (16 + instance * 8 + 1) * 4);
847
942
  if (this.encodePosePublication) {
848
943
  const encoder = this.device!.createCommandEncoder();
849
944
  this.encodePosePublication(encoder);
@@ -914,7 +1009,7 @@ export class GPURigidBodyWorld {
914
1009
  throw new Error('Invalid ensemble instance');
915
1010
  }
916
1011
 
917
- /** Allocation preflight without GPU allocation. Graph scratch and driver overhead are separate. */
1012
+ /** World buffer sizes and private query scratch. Simulation graph scratch and driver overhead are separate. */
918
1013
  getCapacityInfo(): GPURigidBodyCapacityInfo {
919
1014
  const buffers = this.allocationPlan
920
1015
  ? this.allocationPlan.map(buffer => ({...buffer}))
@@ -925,6 +1020,8 @@ export class GPURigidBodyWorld {
925
1020
  maximumPairs: this.maximumPairs,
926
1021
  pairWorkgroups: Math.ceil(this.maximumPairs / 64),
927
1022
  buffers,
1023
+ queryIndexScratchBytes:
1024
+ this.batchCastIndex?.stats.physicalTransientResourceBytes ?? this.batchCastIndexEstimate,
928
1025
  ownedBufferBytes: buffers.reduce((total, buffer) => total + buffer.byteLength, 0)
929
1026
  };
930
1027
  }
@@ -967,6 +1064,8 @@ export class GPURigidBodyWorld {
967
1064
  if (buffer.byteLength > Math.min(graph.device.limits.maxBufferSize, bindingLimit))
968
1065
  throw new Error(`Rigid-body ${buffer.name} storage exceeds device limits`);
969
1066
  }
1067
+ if ((this.props.queryBatchCapacity ?? 0) > graph.device.limits.maxComputeWorkgroupsPerDimension)
1068
+ throw new Error('Collision cast batch exceeds device dispatch limits');
970
1069
  this.allocationPlan = allocationPlan;
971
1070
  this.device = graph.device;
972
1071
  const allocate = (name: string, data: Float32Array | Uint32Array | number, uniform = false) => {
@@ -1113,7 +1212,8 @@ export class GPURigidBodyWorld {
1113
1212
  ? getEnsembleContactLayout(
1114
1213
  this.count,
1115
1214
  this.count / this.props.ensembleBodiesPerInstance,
1116
- this.maximumPairs
1215
+ this.maximumPairs,
1216
+ Boolean(this.props.ensemblePairsPerInstance)
1117
1217
  ).byteLength
1118
1218
  : Math.ceil((this.count * 32 + (sparse ? 32 + this.maximumPairs * 8 : 16)) / 16) * 16 +
1119
1219
  (this.props.joints?.length ?? 0) * RIGID_BODY_JOINT_STATE_BYTES
@@ -1267,7 +1367,8 @@ export class GPURigidBodyWorld {
1267
1367
  this.props.collisionPartitionSize,
1268
1368
  this.props.ensembleBodiesPerInstance,
1269
1369
  this.props.parallelContactSolver === 'block',
1270
- this.colliders.some(collider => collider.shape.type === 'height-field')
1370
+ this.colliders.some(collider => collider.shape.type === 'height-field'),
1371
+ this.props.ensemblePairsPerInstance
1271
1372
  );
1272
1373
  const parallelBindings: Record<string, readonly string[]> = {
1273
1374
  parallelReset: ['parallelState'],
@@ -1384,6 +1485,8 @@ export class GPURigidBodyWorld {
1384
1485
  )
1385
1486
  : undefined;
1386
1487
  this.triggerEvents = triggers?.events ?? null;
1488
+ if (triggers && triggerLayout)
1489
+ this.triggerHistory = {buffer: triggers.history, groups: triggerLayout.groups};
1387
1490
  const passDescriptions: Record<string, string> = {
1388
1491
  integrate: 'Apply gravity and advance body velocities and predicted poses for this timestep.',
1389
1492
  prepare: 'Reset broad-phase counters before generating potential collider pairs.',
@@ -1606,7 +1709,8 @@ export class GPURigidBodyWorld {
1606
1709
  vehicleResource && {
1607
1710
  state: vehicleResource,
1608
1711
  vehiclesPerInstance: this.vehiclesPerInstance
1609
- }
1712
+ },
1713
+ this.props.ensemblePairsPerInstance
1610
1714
  )
1611
1715
  : addRigidBodyCheckpoint(
1612
1716
  graph,
@@ -2079,7 +2183,18 @@ export class GPURigidBodyWorld {
2079
2183
  diagnosticBinding('bodies'),
2080
2184
  diagnosticBinding('sleepStates'),
2081
2185
  diagnosticBinding('ensemble'),
2082
- {buffer: this.simulationStatistics, resource: statisticsResource}
2186
+ {buffer: this.simulationStatistics, resource: statisticsResource},
2187
+ this.props.ensemblePairsPerInstance
2188
+ ? {
2189
+ ...diagnosticBinding('targets'),
2190
+ wordOffset: getEnsembleContactLayout(
2191
+ this.count,
2192
+ this.count / this.props.ensembleBodiesPerInstance!,
2193
+ this.maximumPairs,
2194
+ true
2195
+ ).failureOffset
2196
+ }
2197
+ : undefined
2083
2198
  );
2084
2199
  triggers?.publish();
2085
2200
  if (this.props.publicationBounds || this.props.publishPoses) {
@@ -2102,6 +2217,7 @@ export class GPURigidBodyWorld {
2102
2217
  }
2103
2218
  if (this.props.eventCapacity) {
2104
2219
  const contactHistory = allocate('contact-history', this.maximumPairs * 16);
2220
+ this.contactHistory = contactHistory;
2105
2221
  this.contactEvents = allocate('contact-events', 16 + this.props.eventCapacity * 64);
2106
2222
  const eventBindings = [
2107
2223
  ...bindings.filter(binding => ['bodies', 'manifolds', 'ensemble'].includes(binding.name)),
@@ -2130,52 +2246,35 @@ export class GPURigidBodyWorld {
2130
2246
  )
2131
2247
  }))
2132
2248
  ];
2133
- const properties = {
2249
+ /** The classify and scatter passes use the same committed manifold and history buffers. */
2250
+ const contactResources = eventBindings.map(({name, resource, location}) => ({
2251
+ name,
2252
+ resource,
2253
+ location,
2254
+ readOnly: name === 'bodies' || name === 'eventStatistics'
2255
+ }));
2256
+ addRigidBodyEventCompaction(graph, {
2134
2257
  id: `${this.id}-contact-events`,
2258
+ rowCount: this.maximumPairs,
2259
+ capacity: this.props.eventCapacity,
2260
+ ring: 'contactEvents',
2135
2261
  source:
2136
2262
  source +
2137
2263
  getRigidBodyEventShader(
2138
2264
  this.props.eventCapacity,
2139
2265
  this.props.impactImpulseThreshold ?? 1,
2140
- this.props.failurePolicy === 'rollback'
2266
+ this.props.failurePolicy === 'rollback',
2267
+ this.props.ensemblePairsPerInstance
2141
2268
  ),
2142
- entryPoint: 'recordContacts',
2143
- shaderLayout: {
2144
- bindings: eventBindings.map(({name, location}) => ({
2145
- name,
2146
- location,
2147
- group: 0,
2148
- type: ['bodies', 'eventStatistics'].includes(name)
2149
- ? ('read-only-storage' as const)
2150
- : ('storage' as const)
2151
- }))
2152
- }
2153
- };
2154
- const executable = (
2155
- computation: BoundKernel
2156
- ): GPUCommandGraphComputeExecutable<Parameters> => ({
2157
- encode: ({computePass, getBuffer}) => {
2158
- Object.assign(
2159
- computation.bindings,
2160
- Object.fromEntries(
2161
- eventBindings.map(binding => [binding.name, getBuffer(binding.resource)])
2162
- )
2163
- );
2164
- computation.kernel.dispatch(computePass, {bindings: computation.bindings, x: 1});
2165
- },
2166
- destroy: () => computation.kernel.destroy()
2167
- });
2168
- graph.addComputePass({
2169
- id: properties.id,
2170
- description: 'Compare contact history and publish contact begin, persist, and end events.',
2171
- resources: eventBindings.map(binding => ({
2172
- buffer: binding.resource,
2173
- usage: ['bodies', 'eventStatistics'].includes(binding.name)
2174
- ? ('storage-read' as const)
2175
- : ('storage-read-write' as const)
2176
- })),
2177
- compile: () => executable(createBoundKernel(graph.device, properties)),
2178
- compileAsync: async () => executable(await createBoundKernelAsync(graph.device, properties))
2269
+ classify: contactResources.filter(
2270
+ binding => !['bodies', 'contactEvents'].includes(binding.name)
2271
+ ),
2272
+ commit: contactResources.filter(binding =>
2273
+ ['eventStatistics', 'contactEvents'].includes(binding.name)
2274
+ ),
2275
+ publish: contactResources.filter(
2276
+ binding => !['eventStatistics', 'ensemble'].includes(binding.name)
2277
+ )
2179
2278
  });
2180
2279
  }
2181
2280
  if (this.props.enableQueries) {
@@ -2220,6 +2319,54 @@ export class GPURigidBodyWorld {
2220
2319
  queryOutput: this.queryOutput
2221
2320
  }
2222
2321
  });
2322
+ if (this.props.queryBatchCapacity) {
2323
+ /** Fixed staging capacity keeps query dispatch independent of simulation allocations. */
2324
+ const capacity = this.props.queryBatchCapacity;
2325
+ this.batchCastCommands = allocate(
2326
+ 'query-batch-commands',
2327
+ capacity * RIGID_BODY_CAST_COMMAND_BYTES
2328
+ );
2329
+ this.batchCastResults = allocate(
2330
+ 'query-batch-results',
2331
+ capacity * RIGID_BODY_BATCH_RESULT_BYTES
2332
+ );
2333
+ /** Share external bindings between the scan and the indexed query graph. */
2334
+ const batchBindings = {
2335
+ positions: this.positions,
2336
+ orientations: this.orientations,
2337
+ bodies,
2338
+ querySelection: this.querySelection,
2339
+ batchCommands: this.batchCastCommands,
2340
+ batchResults: this.batchCastResults
2341
+ };
2342
+ /** Batch commands and results use storage bindings, shared by both strategies. */
2343
+ const batchLayout = [
2344
+ ...queryProperties.shaderLayout.bindings.filter(binding =>
2345
+ ['positions', 'orientations', 'bodies', 'querySelection'].includes(binding.name)
2346
+ ),
2347
+ {name: 'batchCommands', group: 0, location: 30, type: 'read-only-storage' as const},
2348
+ {name: 'batchResults', group: 0, location: 31, type: 'storage' as const}
2349
+ ];
2350
+ this.batchCast = createBoundKernel(graph.device, {
2351
+ id: `${this.id}-batched-casts`,
2352
+ entryPoint: 'castBatch',
2353
+ source: queryProperties.source + getRigidBodyBatchCastShader(),
2354
+ shaderLayout: {bindings: batchLayout},
2355
+ bindings: batchBindings
2356
+ });
2357
+ if (this.props.queryBatchIndex && this.colliderCount) {
2358
+ this.batchCastOrder = getRigidBodyCastOrder(this.colliders, this.props.bodies);
2359
+ if (this.batchCastOrder.indexedCount) {
2360
+ this.batchCastIndex = createRigidBodyCastIndex(graph.device, {
2361
+ id: `${this.id}-cast-index`,
2362
+ source: queryProperties.source,
2363
+ layout: batchLayout,
2364
+ buffers: batchBindings,
2365
+ indexedCount: this.batchCastOrder.indexedCount
2366
+ });
2367
+ }
2368
+ }
2369
+ }
2223
2370
  }
2224
2371
  this.controlSettings = allocate('control-settings', 64, true);
2225
2372
  const controlProperties = {
@@ -2388,7 +2535,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2388
2535
 
2389
2536
  /** Rebase between submissions, preserving velocities, contact impulses and sleeping state. */
2390
2537
  shiftOrigin(shift: Vector3): void {
2391
- if (!this.device || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
2538
+ if (!this.device || this.destroyed || this.queryPending || this.eventReadsPending)
2392
2539
  throw new Error('Origin shifting requires an idle attached world');
2393
2540
  // Exact float32 shifts keep the CPU origin and GPU subtraction consistent.
2394
2541
  if (
@@ -2613,6 +2760,21 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2613
2760
  this.props.publicationBounds = structuredClone(bounds);
2614
2761
  }
2615
2762
 
2763
+ /** Read the authored collider frame relative to its body's node origin, excluding COM offset. */
2764
+ getColliderTransform(colliderIndex: number): {
2765
+ position: [number, number, number];
2766
+ orientation: [number, number, number, number];
2767
+ } {
2768
+ /** This frame is metadata, so reading it does not synchronize the device. */
2769
+ const collider = this.colliders[colliderIndex];
2770
+ if (!Number.isInteger(colliderIndex) || !collider || this.destroyed)
2771
+ throw new Error('Invalid collider');
2772
+ return {
2773
+ position: [...(collider.position ?? [0, 0, 0])],
2774
+ orientation: normalizeRigidBodyRotation(collider.orientation)
2775
+ };
2776
+ }
2777
+
2616
2778
  /** Applied scale relative to the initially cooked analytic shape. */
2617
2779
  getColliderShapeScale(colliderIndex: number): number[] {
2618
2780
  this.getColliderShape(colliderIndex);
@@ -2694,7 +2856,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2694
2856
  setHeightFieldTiles(edits: readonly GPURigidBodyHeightFieldEdit[]): void {
2695
2857
  if (!edits.length) return;
2696
2858
  const metadata = this.ownedBuffers.find(buffer => buffer.id === `${this.id}-bodies`);
2697
- if (!metadata || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
2859
+ if (!metadata || this.destroyed || this.queryPending || this.eventReadsPending)
2698
2860
  throw new Error('Terrain streaming requires an idle attached world');
2699
2861
  const seen = new Set<number>();
2700
2862
  const packedFields = this.terrainAtlas
@@ -3181,10 +3343,18 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3181
3343
  readContactEvents(): Promise<GPURigidBodyContactBatch> {
3182
3344
  if (!this.contactEvents || this.destroyed)
3183
3345
  return Promise.reject(new Error('Contact events are not enabled'));
3184
- if (!this.eventRead)
3185
- this.eventRead = this.contactEvents
3346
+ /** Queue the copy now, then decode only after any preceding recovery sets the cursor. */
3347
+ const afterSnapshot = this.contactSnapshotRead;
3348
+ if (this.eventRead && (!afterSnapshot || this.eventRead.afterSnapshot === afterSnapshot))
3349
+ return this.eventRead.result;
3350
+ /** Register the read before recovery can clear its own busy flag. */
3351
+ const pending = {
3352
+ afterSnapshot,
3353
+ result: this.contactEvents
3186
3354
  .readAsync()
3355
+ .finally(() => afterSnapshot)
3187
3356
  .then(bytes => {
3357
+ /** The newest stream cursor is available once the preceding snapshot resolves. */
3188
3358
  const batch = decodeRigidBodyContactEvents(
3189
3359
  new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4),
3190
3360
  this.eventCursor
@@ -3193,9 +3363,11 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3193
3363
  return batch;
3194
3364
  })
3195
3365
  .finally(() => {
3196
- this.eventRead = null;
3197
- });
3198
- return this.eventRead;
3366
+ if (this.eventRead === pending) this.eventRead = null;
3367
+ })
3368
+ };
3369
+ this.eventRead = pending;
3370
+ return pending.result;
3199
3371
  }
3200
3372
 
3201
3373
  /** Nearest exact sphere/OBB hit. Origins inside a shape return distance zero and a zero normal. */
@@ -3208,6 +3380,79 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3208
3380
  return this.runQuery(query);
3209
3381
  }
3210
3382
 
3383
+ /**
3384
+ * Query the closest hit for each ray or sphere cast with one submission and readback.
3385
+ * Results follow input order. This snapshots already submitted poses, using one shared collider selection.
3386
+ */
3387
+ async castBatch(
3388
+ commands: readonly GPURigidBodyBatchCast[],
3389
+ options: GPURigidBodyBatchCastOptions = {}
3390
+ ): Promise<GPURigidBodyQueryResult[]> {
3391
+ if (
3392
+ !this.device ||
3393
+ !this.batchCast ||
3394
+ !this.querySelection ||
3395
+ !this.batchCastCommands ||
3396
+ !this.batchCastResults ||
3397
+ this.destroyed ||
3398
+ this.queryPending
3399
+ )
3400
+ throw new Error('Batched collision casts are disabled or busy');
3401
+ if (commands.length > this.props.queryBatchCapacity!)
3402
+ throw new Error('Collision cast batch exceeds capacity');
3403
+ if (!commands.length) return [];
3404
+ if (options.strategy === 'indexed' && !this.props.queryBatchIndex)
3405
+ throw new Error('Batched collision cast index is disabled');
3406
+ /** The scan remains available for short or dense workloads and reference comparisons. */
3407
+ const order = options.strategy === 'scan' ? null : this.batchCastOrder;
3408
+ /** Deduplicate the shared selection before publishing any GPU input. */
3409
+ const selection = options.colliderIndices
3410
+ ? Uint32Array.from(new Set(this.validateQueryColliders(options.colliderIndices)))
3411
+ : (order?.indices ?? Uint32Array.from({length: this.colliderCount}, (_, index) => index));
3412
+ /** The indexed prefix can be empty when a filter selects only extended geometry. */
3413
+ let indexedCount = order?.indexedCount ?? 0;
3414
+ if (order && options.colliderIndices) {
3415
+ selection.sort((first, second) => order.ranks[first] - order.ranks[second]);
3416
+ /** All selected primitives precede the extended collider fallback. */
3417
+ const firstExtended = selection.findIndex(index => order.ranks[index] >= order.indexedCount);
3418
+ indexedCount = firstExtended < 0 ? selection.length : firstExtended;
3419
+ }
3420
+ /** Validate and encode all commands before changing staging data. */
3421
+ const data = packRigidBodyBatchCasts(commands, this.count, selection.length, indexedCount);
3422
+ this.queryPending = true;
3423
+ try {
3424
+ this.batchCastCommands.write(data);
3425
+ if (selection.length) this.querySelection.write(selection);
3426
+ /** Submit after any preceding pose changes in device queue order. */
3427
+ const encoder = this.device.createCommandEncoder();
3428
+ if (this.batchCastIndex && indexedCount) {
3429
+ this.batchCastIndex.encode(encoder, {parameters: commands.length});
3430
+ } else {
3431
+ /** One workgroup handles one command and reduces its collider results locally. */
3432
+ const pass = encoder.beginComputePass();
3433
+ this.batchCast.kernel.dispatch(pass, {
3434
+ bindings: this.batchCast.bindings,
3435
+ x: commands.length
3436
+ });
3437
+ pass.end();
3438
+ }
3439
+ this.device.submit(encoder.finish());
3440
+ return decodeRigidBodyBatchCasts(
3441
+ await this.batchCastResults.readAsync(0, commands.length * RIGID_BODY_BATCH_RESULT_BYTES)
3442
+ );
3443
+ } finally {
3444
+ this.queryPending = false;
3445
+ }
3446
+ }
3447
+
3448
+ /** Reject invalid indices before scalar or batch query buffers are written. */
3449
+ private validateQueryColliders(indices: readonly number[]): readonly number[] {
3450
+ for (const index of indices)
3451
+ if (!Number.isInteger(index) || index < 0 || index >= this.colliderCount)
3452
+ throw new Error('Invalid query collider');
3453
+ return indices;
3454
+ }
3455
+
3211
3456
  private async runQuery(
3212
3457
  query: GPURigidBodyRayQuery | GPURigidBodyOverlapQuery | GPURigidBodySphereCastQuery
3213
3458
  ): Promise<GPURigidBodyQueryResult> {
@@ -3251,9 +3496,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3251
3496
  const selected =
3252
3497
  query.colliderIndices ?? Array.from({length: this.colliderCount}, (_, index) => index);
3253
3498
  const selection = new Uint32Array(this.colliderStorageCount);
3254
- for (const index of selected) {
3255
- if (!Number.isInteger(index) || index < 0 || index >= this.colliderCount)
3256
- throw new Error('Invalid query collider');
3499
+ for (const index of this.validateQueryColliders(selected)) {
3257
3500
  const collider = this.colliders[index];
3258
3501
  if (collider.body === query.excludeBody) continue;
3259
3502
  selection[index] = 1;
@@ -3282,24 +3525,9 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3282
3525
  const bytes = await this.queryOutput.readAsync(0, 16 + maximumHits * 48);
3283
3526
  const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
3284
3527
  const floats = new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
3285
- const hits = Array.from({length: words[0]}, (_, index) => {
3286
- const offset = 4 + index * 12;
3287
- return {
3288
- body: words[offset],
3289
- collider: words[offset + 1],
3290
- point: [floats[offset + 4], floats[offset + 5], floats[offset + 6]] as [
3291
- number,
3292
- number,
3293
- number
3294
- ],
3295
- distance: floats[offset + 7],
3296
- normal: [floats[offset + 8], floats[offset + 9], floats[offset + 10]] as [
3297
- number,
3298
- number,
3299
- number
3300
- ]
3301
- };
3302
- });
3528
+ const hits = Array.from({length: words[0]}, (_, index) =>
3529
+ decodeRigidBodyQueryHit(words, floats, 4 + index * 12)
3530
+ );
3303
3531
  return {
3304
3532
  hits,
3305
3533
  totalHits: words[1],
@@ -3355,21 +3583,120 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3355
3583
  /** Read step-ordered trigger transitions without losing intermediate enter/exit changes. */
3356
3584
  readTriggerEvents(): Promise<GPURigidBodyTriggerBatch> {
3357
3585
  if (!this.triggerEvents || this.destroyed) throw new Error('Triggers are disabled');
3358
- if (this.triggerRead) return this.triggerRead;
3359
- this.triggerRead = this.triggerEvents
3360
- .readAsync()
3361
- .then(bytes => {
3362
- const batch = decodeRigidBodyTriggerEvents(
3363
- new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4),
3364
- this.triggerCursor
3365
- );
3366
- this.triggerCursor = batch.sequence;
3367
- return batch;
3586
+ /** Queue the copy in caller order, including when recovery is still mapping. */
3587
+ const afterSnapshot = this.triggerSnapshotRead;
3588
+ if (this.triggerRead && (!afterSnapshot || this.triggerRead.afterSnapshot === afterSnapshot))
3589
+ return this.triggerRead.result;
3590
+ /** Track the read immediately so checkpoint operations see a busy world. */
3591
+ const pending = {
3592
+ afterSnapshot,
3593
+ result: this.triggerEvents
3594
+ .readAsync()
3595
+ .finally(() => afterSnapshot)
3596
+ .then(bytes => {
3597
+ /** The snapshot has established the sequence used to decode this delta. */
3598
+ const batch = decodeRigidBodyTriggerEvents(
3599
+ new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4),
3600
+ this.triggerCursor
3601
+ );
3602
+ this.triggerCursor = batch.sequence;
3603
+ return batch;
3604
+ })
3605
+ .finally(() => {
3606
+ if (this.triggerRead === pending) this.triggerRead = null;
3607
+ })
3608
+ };
3609
+ this.triggerRead = pending;
3610
+ return pending.result;
3611
+ }
3612
+
3613
+ /** Recover the active contact set and advance the incremental cursor to the snapshot. */
3614
+ resyncContactEvents(): Promise<GPURigidBodyContactSnapshot> {
3615
+ if (!this.device || !this.contactEvents || !this.contactHistory || this.destroyed)
3616
+ return Promise.reject(new Error('Contact events are not enabled'));
3617
+ if (this.contactSnapshotRead) return this.contactSnapshotRead;
3618
+ /** An earlier incremental read may still be advancing its cursor. */
3619
+ const priorRead = this.eventRead?.result.catch(() => undefined);
3620
+ /** Capture immediately, even when a previous delta read is still mapping. */
3621
+ const snapshot = readRigidBodyEventSnapshot<GPURigidBodyContactSnapshot>(
3622
+ this.device,
3623
+ this.contactEvents,
3624
+ this.contactHistory,
3625
+ (header, rows) => {
3626
+ /** The retained history contains active pairs, independent of event retention. */
3627
+ const contacts: GPURigidBodyContactSnapshot['contacts'] = [];
3628
+ for (let offset = 0; offset < rows.length; offset += 4) {
3629
+ if (rows[offset + 2] === 0) continue;
3630
+ /** A contact history row stores the two original collider IDs. */
3631
+ const first = rows[offset];
3632
+ /** Compound collider IDs map back to their owning bodies. */
3633
+ const second = rows[offset + 1];
3634
+ contacts.push({
3635
+ colliders: [first, second],
3636
+ bodies: [this.colliders[first].body, this.colliders[second].body]
3637
+ });
3638
+ }
3639
+ return {...header, contacts};
3640
+ }
3641
+ );
3642
+ this.contactSnapshotRead = snapshot
3643
+ .finally(() => priorRead)
3644
+ .then(result => {
3645
+ this.eventCursor = result.sequence;
3646
+ return result;
3647
+ })
3648
+ .finally(() => {
3649
+ this.contactSnapshotRead = null;
3650
+ });
3651
+ return this.contactSnapshotRead;
3652
+ }
3653
+
3654
+ /** Recover the active trigger overlap set and advance the incremental trigger cursor. */
3655
+ resyncTriggerEvents(): Promise<GPURigidBodyTriggerSnapshot> {
3656
+ if (!this.device || !this.triggerEvents || !this.triggerHistory || this.destroyed)
3657
+ return Promise.reject(new Error('Triggers are disabled'));
3658
+ if (this.triggerSnapshotRead) return this.triggerSnapshotRead;
3659
+ /** Preserve authored trigger and target-body identities alongside the sampled pairs. */
3660
+ const {buffer, groups} = this.triggerHistory;
3661
+ /** Wait for prior cursor updates before replacing them with the new recovery point. */
3662
+ const priorRead = this.triggerRead?.result.catch(() => undefined);
3663
+ /** Read only the history bit and representative collider pair for each group. */
3664
+ const snapshot = readRigidBodyEventSnapshot<GPURigidBodyTriggerSnapshot>(
3665
+ this.device,
3666
+ this.triggerEvents,
3667
+ buffer,
3668
+ (header, rows) => {
3669
+ /** Swept crossings with no final overlap are absent from this state. */
3670
+ const overlaps: GPURigidBodyTriggerSnapshot['overlaps'] = [];
3671
+ for (let offset = 0; offset < rows.length; offset += 4) {
3672
+ if ((rows[offset] & 1) === 0) continue;
3673
+ overlaps.push({
3674
+ trigger: groups[offset],
3675
+ body: groups[offset + 1],
3676
+ triggerCollider: rows[offset + 1],
3677
+ collider: rows[offset + 2]
3678
+ });
3679
+ }
3680
+ return {...header, overlaps};
3681
+ }
3682
+ );
3683
+ this.triggerSnapshotRead = snapshot
3684
+ .finally(() => priorRead)
3685
+ .then(result => {
3686
+ this.triggerCursor = result.sequence;
3687
+ return result;
3368
3688
  })
3369
3689
  .finally(() => {
3370
- this.triggerRead = null;
3690
+ this.triggerSnapshotRead = null;
3371
3691
  });
3372
- return this.triggerRead;
3692
+ return this.triggerSnapshotRead;
3693
+ }
3694
+
3695
+ /** Reset, capture and origin operations require stable event cursors. */
3696
+ private get eventReadsPending(): boolean {
3697
+ return Boolean(
3698
+ this.eventRead || this.triggerRead || this.contactSnapshotRead || this.triggerSnapshotRead
3699
+ );
3373
3700
  }
3374
3701
 
3375
3702
  private getSnapshotBuffers(includeRollbackScratch = true): Buffer[] {
@@ -3408,7 +3735,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3408
3735
  throw error;
3409
3736
  }
3410
3737
  const copy = (restore: boolean) => {
3411
- if (released || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
3738
+ if (released || this.destroyed || this.queryPending || this.eventReadsPending)
3412
3739
  throw new Error('Checkpoint requires an idle live world');
3413
3740
  const encoder = device.createCommandEncoder();
3414
3741
  for (const [index, buffer] of checkpointBuffers.entries())
@@ -3469,7 +3796,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3469
3796
  async captureState(
3470
3797
  options: {includeRollbackScratch?: boolean} = {}
3471
3798
  ): Promise<GPURigidBodyCapture> {
3472
- if (!this.device || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
3799
+ if (!this.device || this.destroyed || this.queryPending || this.eventReadsPending)
3473
3800
  throw new Error('Capture requires an idle attached world');
3474
3801
  return {
3475
3802
  version: 1,
@@ -3498,8 +3825,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3498
3825
  !this.device ||
3499
3826
  this.destroyed ||
3500
3827
  this.queryPending ||
3501
- this.eventRead ||
3502
- this.triggerRead ||
3828
+ this.eventReadsPending ||
3503
3829
  capture.version !== 1 ||
3504
3830
  Boolean(capture.terrainAtlasLeases) !== Boolean(this.terrainAtlas) ||
3505
3831
  !Number.isInteger(terrainRevision) ||
@@ -3713,6 +4039,8 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3713
4039
  this.terrainWake?.kernel.destroy();
3714
4040
  this.queryComputation?.kernel.destroy();
3715
4041
  this.queryReduction?.kernel.destroy();
4042
+ this.batchCastIndex?.destroy();
4043
+ this.batchCast?.kernel.destroy();
3716
4044
  for (const buffer of this.ownedBuffers) buffer.destroy();
3717
4045
  this.ownedBuffers.length = 0;
3718
4046
  }