@series-inc/rundot-syncplay 6.0.0-rc.2 → 6.0.0-rc.21

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 (329) hide show
  1. package/README.md +133 -0
  2. package/core/deterministic-math.d.ts +75 -1
  3. package/core/native/instance_ledger.hpp +1095 -0
  4. package/core/native/legacy_checkpoint_ids.hpp +107 -0
  5. package/core/native/physics/abi.cpp +39 -211
  6. package/core/native/physics/abi.hpp +2 -6
  7. package/core/native/physics/articulation.cpp +1434 -0
  8. package/core/native/physics/articulation.hpp +279 -0
  9. package/core/native/physics/buoyancy.cpp +1588 -0
  10. package/core/native/physics/buoyancy.hpp +254 -0
  11. package/core/native/physics/capsule_triangle.cpp +168 -0
  12. package/core/native/physics/capsule_triangle.hpp +40 -0
  13. package/core/native/physics/capsule_triangle_native.inc +291 -0
  14. package/core/native/physics/certified_sum.hpp +218 -0
  15. package/core/native/physics/character.cpp +638 -0
  16. package/core/native/physics/character.hpp +169 -0
  17. package/core/native/physics/checkpoint_schema.hpp +379 -0
  18. package/core/native/physics/cloth.cpp +1401 -0
  19. package/core/native/physics/cloth.hpp +357 -0
  20. package/core/native/physics/constraint_rows.cpp +363 -2
  21. package/core/native/physics/constraint_rows.hpp +72 -1
  22. package/core/native/physics/deformable_query.cpp +1630 -0
  23. package/core/native/physics/deformable_query.hpp +578 -0
  24. package/core/native/physics/distance.cpp +1166 -0
  25. package/core/native/physics/distance.hpp +151 -0
  26. package/core/native/physics/exact/exact-applied.cpp +101 -0
  27. package/core/native/physics/exact/exact-applied.hpp +112 -0
  28. package/core/native/physics/exact/exact-dyadic.cpp +691 -0
  29. package/core/native/physics/exact/exact-dyadic.hpp +58 -0
  30. package/core/native/physics/exact/exact-operation.hpp +51 -0
  31. package/core/native/physics/exact/word-core.hpp +262 -0
  32. package/core/native/physics/extended_abi.cpp +1242 -0
  33. package/core/native/physics/extended_abi.hpp +355 -0
  34. package/core/native/physics/extended_abi_characters.cpp +261 -0
  35. package/core/native/physics/extended_abi_characters.hpp +434 -0
  36. package/core/native/physics/extended_abi_core_features.cpp +713 -0
  37. package/core/native/physics/extended_abi_core_features.hpp +226 -0
  38. package/core/native/physics/extended_abi_deformables.cpp +448 -0
  39. package/core/native/physics/extended_abi_deformables.hpp +867 -0
  40. package/core/native/physics/extended_abi_vehicles.cpp +411 -0
  41. package/core/native/physics/extended_abi_vehicles.hpp +222 -0
  42. package/core/native/physics/fracture.cpp +1981 -0
  43. package/core/native/physics/fracture.hpp +460 -0
  44. package/core/native/physics/gear.cpp +563 -0
  45. package/core/native/physics/gear.hpp +158 -0
  46. package/core/native/physics/geometry_memory.hpp +476 -0
  47. package/core/native/physics/geometry_store.cpp +547 -0
  48. package/core/native/physics/geometry_store.hpp +134 -0
  49. package/core/native/physics/lag_compensation.cpp +1626 -0
  50. package/core/native/physics/lag_compensation.hpp +405 -0
  51. package/core/native/physics/mass_properties.cpp +449 -0
  52. package/core/native/physics/mass_properties.hpp +23 -0
  53. package/core/native/physics/material_pose.hpp +988 -0
  54. package/core/native/physics/particles.cpp +1065 -0
  55. package/core/native/physics/particles.hpp +261 -0
  56. package/core/native/physics/path_joint.cpp +781 -0
  57. package/core/native/physics/path_joint.hpp +154 -0
  58. package/core/native/physics/physics.cpp +13043 -1065
  59. package/core/native/physics/physics.hpp +184 -8
  60. package/core/native/physics/planar_deformable.cpp +2433 -0
  61. package/core/native/physics/planar_deformable.hpp +889 -0
  62. package/core/native/physics/platformer_2d.cpp +1353 -0
  63. package/core/native/physics/platformer_2d.hpp +340 -0
  64. package/core/native/physics/powered_ragdoll.cpp +1100 -0
  65. package/core/native/physics/powered_ragdoll.hpp +279 -0
  66. package/core/native/physics/powertrain.cpp +586 -0
  67. package/core/native/physics/powertrain.hpp +180 -0
  68. package/core/native/physics/pulley.cpp +311 -0
  69. package/core/native/physics/pulley.hpp +121 -0
  70. package/core/native/physics/ragdoll.cpp +586 -0
  71. package/core/native/physics/ragdoll.hpp +221 -0
  72. package/core/native/physics/rope.cpp +692 -0
  73. package/core/native/physics/rope.hpp +215 -0
  74. package/core/native/physics/rounded_convex.cpp +1229 -0
  75. package/core/native/physics/rounded_convex.hpp +287 -0
  76. package/core/native/physics/sdf_geometry.cpp +1821 -0
  77. package/core/native/physics/sdf_geometry.hpp +474 -0
  78. package/core/native/physics/soft_body.cpp +1449 -0
  79. package/core/native/physics/soft_body.hpp +328 -0
  80. package/core/native/physics/soft_collision.cpp +1862 -0
  81. package/core/native/physics/soft_collision.hpp +561 -0
  82. package/core/native/physics/surface_velocity.cpp +366 -0
  83. package/core/native/physics/surface_velocity.hpp +243 -0
  84. package/core/native/physics/topology.cpp +357 -39
  85. package/core/native/physics/topology.hpp +97 -6
  86. package/core/native/physics/tracks.cpp +1179 -0
  87. package/core/native/physics/tracks.hpp +404 -0
  88. package/core/native/physics/vehicle.cpp +629 -0
  89. package/core/native/physics/vehicle.hpp +191 -0
  90. package/core/native/physics/voxel_cooking.cpp +1929 -0
  91. package/core/native/physics/voxel_cooking.hpp +395 -0
  92. package/core/native/physics/world.cpp +5290 -854
  93. package/core/native/physics/world.hpp +796 -24
  94. package/core/native/physics/world_abi.cpp +3840 -306
  95. package/core/native/physics/world_abi.hpp +530 -10
  96. package/core/native/physics/world_digest_visitor.hpp +277 -0
  97. package/core/native/physics/world_strong_digest.hpp +557 -0
  98. package/core/native/physics2d/ccd.cpp +1302 -0
  99. package/core/native/physics2d/ccd.hpp +141 -0
  100. package/core/native/physics2d/checkpoint_memory.hpp +349 -0
  101. package/core/native/physics2d/clock_primitives.hpp +138 -0
  102. package/core/native/physics2d/commands.cpp +174 -28
  103. package/core/native/physics2d/commands.hpp +3 -1
  104. package/core/native/physics2d/compound.cpp +581 -0
  105. package/core/native/physics2d/compound.hpp +248 -0
  106. package/core/native/physics2d/contour.cpp +325 -0
  107. package/core/native/physics2d/contour.hpp +143 -0
  108. package/core/native/physics2d/frame_scope.hpp +124 -0
  109. package/core/native/physics2d/joint_phases.hpp +93 -0
  110. package/core/native/physics2d/joints.cpp +587 -150
  111. package/core/native/physics2d/joints.hpp +5 -0
  112. package/core/native/physics2d/memory_private.hpp +125 -0
  113. package/core/native/physics2d/owned_abi.cpp +1354 -879
  114. package/core/native/physics2d/owned_abi.hpp +190 -52
  115. package/core/native/physics2d/phase_test_hooks.hpp +17 -0
  116. package/core/native/physics2d/physics2d.cpp +2073 -120
  117. package/core/native/physics2d/physics2d.hpp +154 -2
  118. package/core/native/physics2d/queries.cpp +1055 -79
  119. package/core/native/physics2d/queries.hpp +71 -5
  120. package/core/native/physics2d/world.cpp +1313 -353
  121. package/core/native/physics2d/world.hpp +124 -13
  122. package/core/native/sha256/sha256_compress_unsigned.hpp +68 -0
  123. package/core/native/sha256/sha256_fips_constants.hpp +24 -0
  124. package/core/native/sha256/sha256_length.hpp +56 -0
  125. package/core/native/sha256/sha256_memo.hpp +48 -0
  126. package/core/native/sha256/sha256_sink.hpp +234 -0
  127. package/core/physics2d-owned.d.ts +466 -126
  128. package/core/runtime.d.ts +192 -19
  129. package/core/scripts/build-native.mjs +34 -0
  130. package/core/scripts/build-wasm-physics.mjs +272 -23
  131. package/core/scripts/extended-physics-profile.mjs +634 -0
  132. package/core/scripts/generate-physics2d-vectors.mjs +59 -0
  133. package/core/src/kinetix-deterministic-math.d.ts +2 -0
  134. package/core/src/kinetix-deterministic-math.mjs +513 -27
  135. package/core/src/kinetix-owned-runtime-adapter.mjs +788 -0
  136. package/core/src/kinetix-runtime-adapter-utils.mjs +54 -6
  137. package/core/src/kinetix-runtime-contract.mjs +55 -9
  138. package/core/src/kinetix-runtime-identity.mjs +12 -1
  139. package/core/src/kinetix-session-config.mjs +7 -2
  140. package/core/src/kinetix-state-report.mjs +36 -0
  141. package/core/src/physics/abi-constants.mjs +5 -4
  142. package/core/src/physics/articulation.d.mts +194 -0
  143. package/core/src/physics/articulation.mjs +1141 -0
  144. package/core/src/physics/buoyancy.d.mts +143 -0
  145. package/core/src/physics/buoyancy.mjs +268 -0
  146. package/core/src/physics/cloth.d.mts +314 -0
  147. package/core/src/physics/cloth.mjs +1156 -0
  148. package/core/src/physics/deformable-query.d.mts +217 -0
  149. package/core/src/physics/deformable-query.mjs +1412 -0
  150. package/core/src/physics/distance.d.mts +160 -0
  151. package/core/src/physics/distance.mjs +175 -0
  152. package/core/src/physics/extended-wasm-instance.d.mts +5 -0
  153. package/core/src/physics/extended-wasm-instance.mjs +48 -0
  154. package/core/src/physics/feature-api.d.mts +74 -0
  155. package/core/src/physics/feature-api.mjs +98 -0
  156. package/core/src/physics/fracture.d.mts +133 -0
  157. package/core/src/physics/fracture.mjs +1324 -0
  158. package/core/src/physics/gear.d.mts +585 -0
  159. package/core/src/physics/gear.mjs +955 -0
  160. package/core/src/physics/lag-compensation.d.mts +101 -0
  161. package/core/src/physics/lag-compensation.mjs +1100 -0
  162. package/core/src/physics/mass-properties.d.mts +114 -0
  163. package/core/src/physics/mass-properties.mjs +137 -468
  164. package/core/src/physics/particles.d.mts +177 -0
  165. package/core/src/physics/particles.mjs +758 -0
  166. package/core/src/physics/path-joint.d.mts +171 -0
  167. package/core/src/physics/path-joint.mjs +1231 -0
  168. package/core/src/physics/physics-extended-wasm-module.generated.mjs +13 -0
  169. package/core/src/physics/physics-profile-wasm-module.generated.mjs +48 -0
  170. package/core/src/physics/physics-wasm-module.generated.mjs +34 -5
  171. package/core/src/physics/powered-ragdoll.d.mts +188 -0
  172. package/core/src/physics/powered-ragdoll.mjs +1043 -0
  173. package/core/src/physics/powertrain.d.mts +260 -0
  174. package/core/src/physics/powertrain.mjs +621 -0
  175. package/core/src/physics/pulley.d.mts +98 -0
  176. package/core/src/physics/pulley.mjs +686 -0
  177. package/core/src/physics/ragdoll.d.mts +289 -0
  178. package/core/src/physics/ragdoll.mjs +1323 -0
  179. package/core/src/physics/rope.d.mts +241 -0
  180. package/core/src/physics/rope.mjs +319 -0
  181. package/core/src/physics/rounded-convex.d.mts +328 -0
  182. package/core/src/physics/rounded-convex.mjs +1404 -0
  183. package/core/src/physics/sdf-geometry.d.mts +117 -0
  184. package/core/src/physics/sdf-geometry.mjs +1204 -0
  185. package/core/src/physics/soft-body.d.mts +144 -0
  186. package/core/src/physics/soft-body.mjs +1285 -0
  187. package/core/src/physics/soft-collision.d.mts +651 -0
  188. package/core/src/physics/soft-collision.mjs +1883 -0
  189. package/core/src/physics/surface-velocity.d.mts +156 -0
  190. package/core/src/physics/surface-velocity.mjs +722 -0
  191. package/core/src/physics/tracks.d.mts +411 -0
  192. package/core/src/physics/tracks.mjs +1074 -0
  193. package/core/src/physics/vehicle.d.mts +3 -0
  194. package/core/src/physics/vehicle.mjs +172 -0
  195. package/core/src/physics/voxel-cooking.d.mts +219 -0
  196. package/core/src/physics/voxel-cooking.mjs +1499 -0
  197. package/core/src/physics/voxel-swept-quad.mjs +110 -0
  198. package/core/src/physics/wasm-instance.mjs +160 -23
  199. package/core/src/physics/world.d.mts +62 -0
  200. package/core/src/physics/world.mjs +1947 -152
  201. package/core/src/physics2d/body-state.mjs +218 -15
  202. package/core/src/physics2d/collision.d.mts +52 -0
  203. package/core/src/physics2d/collision.mjs +234 -0
  204. package/core/src/physics2d/compound.mjs +454 -0
  205. package/core/src/physics2d/contour-state.mjs +771 -0
  206. package/core/src/physics2d/feature-api.d.mts +211 -0
  207. package/core/src/physics2d/feature-api.mjs +3 -0
  208. package/core/src/physics2d/fluid-state.mjs +145 -0
  209. package/core/src/physics2d/joint-state.mjs +1 -1
  210. package/core/src/physics2d/owned-queries.mjs +3 -1
  211. package/core/src/physics2d/owned-transport.mjs +268 -122
  212. package/core/src/physics2d/owned-world.mjs +353 -230
  213. package/core/src/physics2d/particle-fluid.d.mts +152 -0
  214. package/core/src/physics2d/particle-fluid.mjs +233 -0
  215. package/core/src/physics2d/physics2d-wasm-module.generated.mjs +27 -10
  216. package/core/src/physics2d/query-codec.mjs +61 -13
  217. package/core/src/physics2d/submerged-geometry.d.mts +51 -0
  218. package/core/src/physics2d/submerged-geometry.mjs +186 -0
  219. package/core/src/runtime.mjs +23 -0
  220. package/core/src/shared/bytes.d.mts +2 -0
  221. package/core/src/shared/bytes.mjs +33 -0
  222. package/core/src/shared/sha256.d.mts +3 -0
  223. package/core/src/shared/sha256.mjs +72 -22
  224. package/core/units.d.ts +50 -0
  225. package/core/world.d.ts +253 -5
  226. package/dist/authority-room.d.ts +9 -0
  227. package/dist/authority-room.js +45 -16
  228. package/dist/browser.d.ts +6 -5
  229. package/dist/browser.js +4 -3
  230. package/dist/cadence.d.ts +7 -0
  231. package/dist/cadence.js +19 -0
  232. package/dist/canonical.d.ts +1 -0
  233. package/dist/canonical.js +3 -0
  234. package/dist/checksum-policy.d.ts +10 -0
  235. package/dist/checksum-policy.js +14 -0
  236. package/dist/collider-cooking-hull.d.ts +18 -0
  237. package/dist/collider-cooking-hull.js +248 -0
  238. package/dist/collider-cooking.d.ts +140 -0
  239. package/dist/collider-cooking.js +794 -0
  240. package/dist/compat/v5.d.ts +121 -0
  241. package/dist/compat/v5.js +479 -0
  242. package/dist/creator.d.ts +7 -6
  243. package/dist/creator.js +4 -3
  244. package/dist/game-byte-section.d.ts +36 -0
  245. package/dist/game-byte-section.js +350 -0
  246. package/dist/index.d.ts +13 -6
  247. package/dist/index.js +9 -4
  248. package/dist/instant-replay.d.ts +27 -2
  249. package/dist/instant-replay.js +91 -16
  250. package/dist/lag-compensation3d.js +11 -10
  251. package/dist/match-log.d.ts +21 -4
  252. package/dist/match-log.js +92 -9
  253. package/dist/math.d.ts +2 -0
  254. package/dist/math.js +1 -0
  255. package/dist/modules/character-3d.d.ts +16 -1
  256. package/dist/modules/character-3d.js +42 -5
  257. package/dist/modules/combat.js +6 -5
  258. package/dist/movement3d-revision1.d.ts +2 -0
  259. package/dist/movement3d-revision1.js +973 -0
  260. package/dist/movement3d.d.ts +53 -3
  261. package/dist/movement3d.js +917 -247
  262. package/dist/networked-client.d.ts +15 -0
  263. package/dist/networked-client.js +378 -105
  264. package/dist/node.d.ts +3 -2
  265. package/dist/node.js +2 -1
  266. package/dist/physics/2d.d.ts +38 -4
  267. package/dist/physics/2d.js +57 -36
  268. package/dist/physics/3d.d.ts +755 -111
  269. package/dist/physics/3d.js +2355 -158
  270. package/dist/physics/edit-result-graph.d.ts +36 -0
  271. package/dist/physics/edit-result-graph.js +141 -0
  272. package/dist/physics/game-codec3d.d.ts +41 -0
  273. package/dist/physics/game-codec3d.js +544 -0
  274. package/dist/physics/installed-checkpoint3d.d.ts +13 -0
  275. package/dist/physics/installed-checkpoint3d.js +120 -0
  276. package/dist/physics/installed-runtime3d.d.ts +51 -0
  277. package/dist/physics/installed-runtime3d.js +372 -0
  278. package/dist/physics/installed-state-commitment3d.d.ts +2 -0
  279. package/dist/physics/installed-state-commitment3d.js +24 -0
  280. package/dist/physics/units.d.ts +38 -0
  281. package/dist/physics/units.js +56 -0
  282. package/dist/physics/vehicle-state3d.d.ts +93 -0
  283. package/dist/physics/vehicle-state3d.js +1191 -0
  284. package/dist/physics/voxel-body-state.d.ts +61 -0
  285. package/dist/physics/voxel-body-state.js +410 -0
  286. package/dist/r3f-render-adapter.d.ts +59 -1
  287. package/dist/r3f-render-adapter.js +137 -2
  288. package/dist/replay.d.ts +13 -0
  289. package/dist/replay.js +95 -70
  290. package/dist/run-room-transport.js +5 -1
  291. package/dist/runner.d.ts +17 -2
  292. package/dist/runner.js +472 -84
  293. package/dist/runtime-cleanup.d.ts +54 -0
  294. package/dist/runtime-cleanup.js +266 -0
  295. package/dist/runtime-lease.d.ts +11 -1
  296. package/dist/runtime-lease.js +23 -10
  297. package/dist/runtime-room-metadata.d.ts +2 -8
  298. package/dist/runtime-room-metadata.js +11 -14
  299. package/dist/runtime-session.d.ts +8 -0
  300. package/dist/runtime-session.js +222 -58
  301. package/dist/schema-codegen.js +3 -0
  302. package/dist/schema-dsl-binary.d.ts +10 -4
  303. package/dist/schema-dsl-binary.js +375 -76
  304. package/dist/scratch-pool.d.ts +32 -0
  305. package/dist/scratch-pool.js +60 -0
  306. package/dist/sdk-session.d.ts +1 -0
  307. package/dist/sdk-session.js +4 -0
  308. package/dist/secret-config.js +2 -60
  309. package/dist/secret-crypto.js +70 -36
  310. package/dist/session-snapshot.d.ts +15 -4
  311. package/dist/session-snapshot.js +35 -33
  312. package/dist/session-wire.js +14 -22
  313. package/dist/sparse-set.d.ts +1 -0
  314. package/dist/sparse-set.js +22 -0
  315. package/dist/spatial/spatial-grid-3d.d.ts +41 -0
  316. package/dist/spatial/spatial-grid-3d.js +115 -0
  317. package/dist/synctest.d.ts +9 -0
  318. package/dist/synctest.js +106 -17
  319. package/dist/testing-network.d.ts +2 -0
  320. package/dist/testing-network.js +122 -18
  321. package/dist/testing.d.ts +27 -6
  322. package/dist/testing.js +297 -56
  323. package/dist/tools/index.d.ts +3 -2
  324. package/dist/tools/index.js +3 -2
  325. package/dist/tools/module-certification.d.ts +6 -0
  326. package/dist/tools/module-certification.js +26 -2
  327. package/package.json +18 -5
  328. package/core/scripts/run-box3d-benchmark.mjs +0 -350
  329. package/core/src/physics/index.mjs +0 -3169
@@ -1,30 +1,71 @@
1
1
  import { physicsWorldAbiExports } from './wasm-instance.mjs';
2
+ import * as wasmInstance from './wasm-instance.mjs';
2
3
  import {
3
4
  PHYSICS_ABI_VERSION,
4
5
  PHYSICS_BODY_STRIDE,
5
6
  PHYSICS_JOINT_STRIDE,
6
7
  PHYSICS_JOINT_WARM_STATE_STRIDE,
7
8
  PHYSICS_WORLD_ABI_VERSION,
9
+ PHYSICS_WORLD_DIGEST_ALGORITHM_REVISION,
8
10
  PHYSICS_WORLD_STATE_INFO_VALUES,
9
11
  } from './abi-constants.mjs';
10
12
 
11
13
  const WORLD_ABI_VERSION = PHYSICS_WORLD_ABI_VERSION;
12
14
  const STATE_INFO_VALUES = PHYSICS_WORLD_STATE_INFO_VALUES;
13
- const TOPOLOGY_COMMAND_STRIDE = 12;
15
+ const TOPOLOGY_COMMAND_STRIDE = 16;
16
+ const TOPOLOGY_GEOMETRY_ABI_VERSION = 4;
14
17
  const TOPOLOGY_RESULT_STRIDE = 4;
15
- const TOPOLOGY_INFO_STRIDE = 8;
16
- const TOPOLOGY_HEADER_VALUES = 4;
18
+ const TOPOLOGY_INFO_STRIDE = 13;
19
+ const FLUID_RECORD_STRIDE = 20;
20
+ const TOPOLOGY_HEADER_VALUES = 6;
17
21
  const MAX_TOPOLOGY_COMMANDS = 220000;
22
+ const MAX_GEOMETRY_VALUES = 12600000;
18
23
  const WORLD_QUERY_INPUT_STRIDE = 21;
19
24
  const WORLD_QUERY_HIT_STRIDE = 8;
20
25
  const WORLD_QUERY_BODY_ID_STRIDE = 2;
21
- const WORLD_CONTACT_OUTPUT_VALUE_STRIDE = 10;
26
+ const WORLD_CONTACT_OUTPUT_VALUE_STRIDE = 11;
22
27
  const WORLD_CONTACT_OUTPUT_METADATA_STRIDE = 6;
28
+ const WORLD_JOINT_REACTION_VALUE_STRIDE = 6;
29
+ const WORLD_JOINT_REACTION_METADATA_STRIDE = 6;
30
+ const WORLD_JOINT_BREAK_METADATA_STRIDE = 3;
31
+ const WORLD_FLUID_INTERACTION_VALUE_STRIDE = 13;
32
+ const WORLD_FLUID_INTERACTION_METADATA_STRIDE = 5;
33
+ const runtimeAttachmentKey = Symbol.for('rundot.syncplay.physics3d.runtimeAttachment/1');
23
34
  const liveHandles = new WeakMap();
35
+ const committedHandleCell = Object.freeze({ state: 'committed' });
36
+ const intrinsicFreeze = Object.freeze;
37
+ const intrinsicApply = Reflect.apply;
38
+ const intrinsicDescriptor = Object.getOwnPropertyDescriptor;
39
+ const intrinsicDefine = Object.defineProperty;
40
+ const intrinsicCreate = Object.create;
41
+ const intrinsicWeakGet = Function.prototype.call.bind(WeakMap.prototype.get);
42
+ const intrinsicWeakSet = Function.prototype.call.bind(WeakMap.prototype.set);
43
+ const intrinsicWeakDelete = Function.prototype.call.bind(WeakMap.prototype.delete);
44
+ const NativeU32Array = Uint32Array;
45
+ const NativeF64Array = Float64Array;
46
+ const NativeU8Array = Uint8Array;
47
+ const intrinsicU8Set = Function.prototype.call.bind(Uint8Array.prototype.set);
48
+ const intrinsicTypedByteLength = Function.prototype.call.bind(
49
+ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteLength').get);
50
+ const intrinsicU32Set = Function.prototype.call.bind(Uint32Array.prototype.set);
51
+ const intrinsicF64Set = Function.prototype.call.bind(Float64Array.prototype.set);
52
+ const intrinsicIsArray = Array.isArray;
53
+ const intrinsicKeys = Object.keys;
54
+ const intrinsicSetHas = Function.prototype.call.bind(Set.prototype.has);
55
+ const geometryKeepFields = new Set(['type']);
56
+ const geometryInstallFields = new Set(['type', 'values']);
57
+ function appendOwn(array, value) {
58
+ intrinsicDefine(array, array.length, { value, enumerable: true, configurable: true, writable: true });
59
+ }
60
+ function copyF64(values) {
61
+ const copied = new NativeF64Array(values.length);
62
+ intrinsicF64Set(copied, values);
63
+ return copied;
64
+ }
24
65
  const textEncoder = new TextEncoder();
25
66
  const textDecoder = new TextDecoder();
26
- const worldStateFields = new Set(['frame', 'bodies', 'joints', 'geometry', 'contactCache', 'forces', 'jointWarmState', 'topology']);
27
- const topologyFields = new Set(['nextBodyId', 'nextJointId', 'bodies', 'joints']);
67
+ const worldStateFields = new Set(['frame', 'bodies', 'joints', 'geometry', 'contactCache', 'forces', 'jointWarmState', 'topology', 'surfaceVelocities', 'fluids']);
68
+ const topologyFields = new Set(['nextBodyId', 'nextJointId', 'nextFluidId', 'bodies', 'joints', 'fluids']);
28
69
  const topologyJointFields = new Set(['id', 'bodyA', 'bodyB']);
29
70
  const worldErrorNames = [
30
71
  undefined,
@@ -52,12 +93,20 @@ const worldErrorNames = [
52
93
  let worldExports;
53
94
  let worldInitialization;
54
95
 
96
+ export function nativePhysicsSelectedArtifact() {
97
+ return wasmInstance.physicsSelectedArtifact();
98
+ }
99
+
100
+ export function nativePhysicsArtifactMetadata() {
101
+ return wasmInstance.physicsArtifactMetadata();
102
+ }
103
+
55
104
  function fail(detail) {
56
105
  throw new Error(`KINETIX_NATIVE_WORLD_${detail}`);
57
106
  }
58
107
 
59
108
  function requireRecord(value, label) {
60
- if (typeof value !== 'object' || value === null || Array.isArray(value)) fail(`${label}_INVALID`);
109
+ if (typeof value !== 'object' || value === null || intrinsicIsArray(value)) fail(`${label}_INVALID`);
61
110
  return value;
62
111
  }
63
112
 
@@ -72,7 +121,7 @@ function requireFinite(value, label) {
72
121
  }
73
122
 
74
123
  function requireValues(value, label) {
75
- if (!(value instanceof Float64Array)) fail(`${label}_INVALID: use Float64Array`);
124
+ if (!(value instanceof NativeF64Array)) fail(`${label}_INVALID: use Float64Array`);
76
125
  return value;
77
126
  }
78
127
 
@@ -105,23 +154,27 @@ function requireWarmState(value, jointCount, label = 'JOINT_WARM_STATE') {
105
154
  }
106
155
 
107
156
  function rejectUnknownFields(value, allowed, label) {
108
- for (const key of Object.keys(value)) {
109
- if (!allowed.has(key)) fail(`${label}.${key}_INVALID: unsupported field`);
157
+ const fields = intrinsicKeys(value);
158
+ for (let index = 0; index < fields.length; index += 1) {
159
+ if (!intrinsicSetHas(allowed, fields[index])) fail(`${label}.${fields[index]}_INVALID: unsupported field`);
110
160
  }
111
161
  }
112
162
 
113
- function requireTopology(value, bodyValues, jointCount, label = 'TOPOLOGY') {
163
+ function requireTopology(value, bodyValues, jointCount, fluidCount, label = 'TOPOLOGY') {
114
164
  if (value === undefined) return undefined;
115
165
  const topology = requireRecord(value, label);
116
166
  rejectUnknownFields(topology, topologyFields, label);
167
+ const fluidTopology = topology.fluids ?? [];
117
168
  const bodyCount = bodyValues / PHYSICS_BODY_STRIDE;
118
169
  if (!Number.isInteger(bodyCount) || !Number.isInteger(jointCount)
119
170
  || !Array.isArray(topology.bodies) || topology.bodies.length !== bodyCount
120
- || !Array.isArray(topology.joints) || topology.joints.length !== jointCount) {
121
- fail(`${label}_INVALID: topology counts must match the body and joint records`);
171
+ || !Array.isArray(topology.joints) || topology.joints.length !== jointCount
172
+ || !Array.isArray(fluidTopology) || fluidTopology.length !== fluidCount) {
173
+ fail(`${label}_INVALID: topology counts must match the body, joint, and fluid records`);
122
174
  }
123
175
  const nextBodyId = requireLogicalId(topology.nextBodyId, `${label}.nextBodyId`);
124
176
  const nextJointId = requireLogicalId(topology.nextJointId, `${label}.nextJointId`);
177
+ const nextFluidId = requireLogicalId(topology.nextFluidId ?? 1n, `${label}.nextFluidId`);
125
178
  const bodies = topology.bodies.map((id, index) => requireLogicalId(id, `${label}.bodies[${index}]`));
126
179
  const bodyIds = new Set();
127
180
  for (const [index, id] of bodies.entries()) {
@@ -148,13 +201,21 @@ function requireTopology(value, bodyValues, jointCount, label = 'TOPOLOGY') {
148
201
  if (jointIds.has(joint.id)) fail(`${label}.joints[${index}]_INVALID: duplicate joint ID`);
149
202
  jointIds.add(joint.id);
150
203
  }
151
- const values = new Uint32Array(TOPOLOGY_HEADER_VALUES + bodies.length * 2 + joints.length * 6);
204
+ const fluids = fluidTopology.map((id, index) => requireLogicalId(id, `${label}.fluids[${index}]`));
205
+ const fluidIds = new Set();
206
+ for (const [index, id] of fluids.entries()) {
207
+ if (fluidIds.has(id)) fail(`${label}.fluids[${index}]_INVALID: duplicate fluid ID`);
208
+ fluidIds.add(id);
209
+ }
210
+ const values = new Uint32Array(TOPOLOGY_HEADER_VALUES + bodies.length * 2
211
+ + joints.length * 6 + fluids.length * 2);
152
212
  const writeU64 = (offset, value) => {
153
213
  values[offset] = Number(value & 0xffffffffn);
154
214
  values[offset + 1] = Number(value >> 32n);
155
215
  };
156
216
  writeU64(0, nextBodyId);
157
217
  writeU64(2, nextJointId);
218
+ writeU64(4, nextFluidId);
158
219
  bodies.forEach((id, index) => writeU64(TOPOLOGY_HEADER_VALUES + index * 2, id));
159
220
  joints.forEach((joint, index) => {
160
221
  const offset = TOPOLOGY_HEADER_VALUES + bodies.length * 2 + index * 6;
@@ -162,6 +223,8 @@ function requireTopology(value, bodyValues, jointCount, label = 'TOPOLOGY') {
162
223
  writeU64(offset + 2, joint.bodyA);
163
224
  writeU64(offset + 4, joint.bodyB);
164
225
  });
226
+ const fluidOffset = TOPOLOGY_HEADER_VALUES + bodies.length * 2 + joints.length * 6;
227
+ fluids.forEach((id, index) => writeU64(fluidOffset + index * 2, id));
165
228
  return values;
166
229
  }
167
230
 
@@ -184,7 +247,12 @@ function allocate(exports, byteLength) {
184
247
  }
185
248
 
186
249
  function free(exports, pointer) {
187
- if (pointer !== 0) exports.rundot_kinetix_world_buffer_free(pointer);
250
+ if (pointer === 0) return;
251
+ const status = exports.rundot_kinetix_world_buffer_free(pointer);
252
+ if (status === 0) return;
253
+ if (status === -16) fail('BUFFER_REJECTED: scratch release rejected');
254
+ if (status === -17) fail('BUFFER_BUSY: scratch lease is pinned');
255
+ fail(`BUFFER_RELEASE_FAILED: native status ${status}`);
188
256
  }
189
257
 
190
258
  function readNativeError(exports) {
@@ -204,14 +272,23 @@ function readNativeError(exports) {
204
272
 
205
273
  function checkStatus(exports, status, operation) {
206
274
  if (status === 0) return;
207
- const commandIndex = exports.rundot_kinetix_world_error_command_index();
275
+ const commandIndex = exports.rundot_kinetix_world_error_command_index() >>> 0;
208
276
  if (commandIndex !== 0xffffffff) operation += ` command[${commandIndex}]`;
209
- const detail = readNativeError(exports);
277
+ let detail;
278
+ try { detail = readNativeError(exports); }
279
+ catch { detail = `native status ${status}; error detail is unavailable`; }
210
280
  if (status === -3) fail(`STALE_HANDLE: ${operation}: ${detail}`);
211
281
  if (status === -6) fail(`SHORT_BUFFER: ${operation}: ${detail}`);
212
282
  if (status === -7) fail(`ALLOCATION_FAILED: ${operation}: ${detail}`);
213
283
  if (status === -9) fail(`CHECKPOINT_CAPACITY: ${operation}: ${detail}`);
214
284
  if (status === -10) fail(`CHECKPOINT_INVALID: ${operation}: ${detail}`);
285
+ if (status === -11) fail(`WORLD_ATTACHED: ${operation}: ${detail}`);
286
+ if (status === -12) fail(`INITIAL_STATE_MISMATCH: ${operation}: ${detail}`);
287
+ if (status === -13) fail(`CHECKPOINT_TOKEN_EXHAUSTED: ${operation}: ${detail}`);
288
+ if (status === -14) fail(`ATTACHMENT_MISMATCH: ${operation}: ${detail}`);
289
+ if (status === -15) fail(`LEDGER_LIVE: ${operation}: ${detail}`);
290
+ if (status === -16) fail(`BUFFER_REJECTED: ${operation}: ${detail}`);
291
+ if (status === -17) fail(`BUFFER_BUSY: ${operation}: ${detail}`);
215
292
  const worldCode = -status - 100;
216
293
  if (worldCode > 0 && worldCode < worldErrorNames.length) {
217
294
  fail(`WORLD_${worldErrorNames[worldCode]}: ${operation}: ${detail}`);
@@ -223,13 +300,28 @@ function validateExports(exports) {
223
300
  const names = [
224
301
  'rundot_kinetix_world_buffer_allocate',
225
302
  'rundot_kinetix_world_buffer_free',
226
- 'rundot_kinetix_world_create',
303
+ 'rundot_kinetix_instance_ledger_classes',
304
+ 'rundot_kinetix_world_checkpoint_digest',
305
+ 'rundot_kinetix_world_checkpoint_strong_digest',
306
+ 'rundot_kinetix_world_strong_digest_algorithm_revision',
307
+ 'rundot_kinetix_world_checkpoint_import',
308
+ 'rundot_kinetix_world_digest_algorithm_revision',
309
+ 'rundot_kinetix_world_create_with_checkpoint_capacity',
227
310
  'rundot_kinetix_world_destroy',
228
311
  'rundot_kinetix_world_digest',
312
+ 'rundot_kinetix_world_frame',
229
313
  'rundot_kinetix_world_replace_state',
230
314
  'rundot_kinetix_world_step',
231
315
  'rundot_kinetix_world_apply_impulse',
316
+ 'rundot_kinetix_world_set_body_force',
317
+ 'rundot_kinetix_world_apply_force',
318
+ 'rundot_kinetix_world_apply_force_at_point',
319
+ 'rundot_kinetix_world_clear_body_force',
320
+ 'rundot_kinetix_world_set_body_surface_velocity',
321
+ 'rundot_kinetix_world_set_body_linear_velocity',
322
+ 'rundot_kinetix_world_set_body_angular_velocity',
232
323
  'rundot_kinetix_world_query',
324
+ 'rundot_kinetix_world_query_body_ray',
233
325
  'rundot_kinetix_world_state_info',
234
326
  'rundot_kinetix_world_copy_state',
235
327
  'rundot_kinetix_world_joint_warm_state_stride',
@@ -245,28 +337,41 @@ function validateExports(exports) {
245
337
  'rundot_kinetix_world_topology_info',
246
338
  'rundot_kinetix_world_copy_topology',
247
339
  'rundot_kinetix_world_apply_topology_batch',
340
+ 'rundot_kinetix_world_apply_topology_geometry_batch',
248
341
  'rundot_kinetix_world_body_exists',
249
342
  'rundot_kinetix_world_joint_exists',
343
+ 'rundot_kinetix_world_fluid_exists',
250
344
  'rundot_kinetix_world_read_body',
345
+ 'rundot_kinetix_world_body_geometry_info',
346
+ 'rundot_kinetix_world_copy_body_geometry',
251
347
  'rundot_kinetix_world_read_joint',
348
+ 'rundot_kinetix_world_read_fluid',
252
349
  'rundot_kinetix_world_contact_output_info',
253
350
  'rundot_kinetix_world_copy_contact_output',
351
+ 'rundot_kinetix_world_joint_output_info',
352
+ 'rundot_kinetix_world_copy_joint_output',
353
+ 'rundot_kinetix_world_fluid_interaction_info',
354
+ 'rundot_kinetix_world_copy_fluid_interactions',
254
355
  ];
255
356
  if (!(exports.memory instanceof WebAssembly.Memory)
256
357
  || typeof exports.rundot_kinetix_world_abi_version !== 'function'
257
358
  || names.some((name) => typeof exports[name] !== 'function')
258
359
  || exports.rundot_kinetix_world_abi_version() !== WORLD_ABI_VERSION
360
+ || exports.rundot_kinetix_world_digest_algorithm_revision() !== PHYSICS_WORLD_DIGEST_ALGORITHM_REVISION
259
361
  || exports.rundot_kinetix_world_joint_warm_state_stride() !== PHYSICS_JOINT_WARM_STATE_STRIDE) {
260
362
  fail(`ABI_MISMATCH: world ABI ${WORLD_ABI_VERSION}, warm stride ${PHYSICS_JOINT_WARM_STATE_STRIDE} required; rebuild the native world artifact`);
261
363
  }
262
364
  for (const [name, expected] of [
263
- ['topology_abi_version', 1],
264
- ['topology_command_stride', TOPOLOGY_COMMAND_STRIDE],
365
+ ['topology_abi_version', 2],
366
+ ['topology_command_stride', 12],
367
+ ['topology_geometry_abi_version', TOPOLOGY_GEOMETRY_ABI_VERSION],
368
+ ['topology_geometry_command_stride', TOPOLOGY_COMMAND_STRIDE],
265
369
  ['topology_result_stride', TOPOLOGY_RESULT_STRIDE],
266
370
  ['topology_info_stride', TOPOLOGY_INFO_STRIDE],
267
371
  ['topology_max_commands', MAX_TOPOLOGY_COMMANDS],
268
372
  ['topology_body_id_stride', 2],
269
373
  ['topology_joint_identity_stride', 6],
374
+ ['topology_fluid_id_stride', 2],
270
375
  ]) {
271
376
  const fn = exports[`rundot_kinetix_world_${name}`];
272
377
  if (typeof fn !== 'function' || fn() !== expected) fail('TOPOLOGY_ABI_MISMATCH');
@@ -274,17 +379,33 @@ function validateExports(exports) {
274
379
  return exports;
275
380
  }
276
381
 
277
- export async function initNativePhysicsWorld() {
382
+ export async function initNativePhysicsWorld(options) {
383
+ if (options !== undefined && options !== null) {
384
+ if (typeof options !== 'object' || Array.isArray(options)) {
385
+ fail('INVALID_OPTIONS: options must be an object');
386
+ }
387
+ if (options.artifact !== undefined && options.artifact !== 'production' && options.artifact !== 'profile') {
388
+ fail(`INVALID_OPTIONS: unsupported artifact ${String(options.artifact)}`);
389
+ }
390
+ }
391
+ const currentArtifact = nativePhysicsSelectedArtifact() ?? (worldExports !== undefined ? 'production' : null);
392
+ if (currentArtifact && options?.artifact && options.artifact !== currentArtifact) {
393
+ fail(`ARTIFACT_CONFLICT: cannot initialize world with ${options.artifact}; already configured for ${currentArtifact}`);
394
+ }
278
395
  if (worldExports !== undefined) return;
279
396
  if (worldInitialization === undefined) {
280
- worldInitialization = physicsWorldAbiExports()
281
- .then((exports) => { worldExports = validateExports(exports); })
397
+ worldInitialization = physicsWorldAbiExports(options)
398
+ .then((exports) => {
399
+ worldExports = validateExports(exports);
400
+ })
282
401
  .catch((error) => {
283
- worldInitialization = undefined;
284
402
  if (error instanceof Error && error.message.includes('KINETIX_PHYSICS_WASM_ABI_MISMATCH')) {
285
403
  throw new Error(`KINETIX_NATIVE_WORLD_ABI_MISMATCH: physics ABI ${PHYSICS_ABI_VERSION} is required; rebuild the native world artifact`, { cause: error });
286
404
  }
287
405
  throw error;
406
+ })
407
+ .finally(() => {
408
+ worldInitialization = undefined;
288
409
  });
289
410
  }
290
411
  return worldInitialization;
@@ -295,6 +416,33 @@ function requireInitialized() {
295
416
  return worldExports;
296
417
  }
297
418
 
419
+ export function nativePhysicsInstanceMemory() {
420
+ const exports = requireInitialized();
421
+ if (typeof exports.rundot_kinetix_instance_ledger_classes !== 'function') {
422
+ fail('ABI_MISMATCH: native memory classes require world ABI 10');
423
+ }
424
+ const classNames = ['registry', 'world', 'storage', 'geometry', 'material',
425
+ 'checkpoint', 'control', 'metadata', 'scratch'];
426
+ const pointer = allocate(exports, 30 * 8);
427
+ try {
428
+ checkStatus(exports, exports.rundot_kinetix_instance_ledger_info(
429
+ pointer, pointer + 8, pointer + 16, pointer + 24, pointer + 32, pointer + 40));
430
+ checkStatus(exports, exports.rundot_kinetix_instance_ledger_metadata(
431
+ pointer + 48, pointer + 56, pointer + 64, pointer + 72, pointer + 80, pointer + 88));
432
+ checkStatus(exports, exports.rundot_kinetix_instance_ledger_classes(
433
+ pointer + 96, pointer + 168, classNames.length));
434
+ const values = new BigUint64Array(exports.memory.buffer, pointer, 30);
435
+ const classes = Object.freeze(Object.fromEntries(classNames.map((name, index) =>
436
+ [name, Object.freeze({ bytes: values[12 + index], highWaterBytes: values[21 + index] })])));
437
+ return Object.freeze({ liveSlots: values[0], highWaterSlots: values[1],
438
+ checkpointBytes: values[2], geometryBytes: values[3], retainedHighWaterBytes: values[4],
439
+ wasmHeapBytes: values[5], metadataBytes: values[6], retainedBytes: values[9],
440
+ liveWorlds: values[10], imbalance: values[11] !== 0n, classes });
441
+ } finally {
442
+ free(exports, pointer);
443
+ }
444
+ }
445
+
298
446
  function replaceState(exports, handle, input) {
299
447
  const state = requireRecord(input, 'STATE');
300
448
  rejectUnknownFields(state, worldStateFields, 'STATE');
@@ -305,10 +453,18 @@ function replaceState(exports, handle, input) {
305
453
  requireValues(state.geometry, 'GEOMETRY'),
306
454
  requireValues(state.contactCache, 'CONTACT_CACHE'),
307
455
  requireValues(state.forces, 'FORCES'),
456
+ state.surfaceVelocities === undefined ? new Float64Array()
457
+ : requireValues(state.surfaceVelocities, 'SURFACE_VELOCITIES'),
458
+ state.fluids === undefined ? new Float64Array()
459
+ : requireValues(state.fluids, 'FLUIDS'),
308
460
  ];
309
461
  const jointCount = countJointsAndValidate(arrays[1]);
310
462
  const jointWarmState = requireWarmState(state.jointWarmState, jointCount);
311
- const topologyValues = requireTopology(state.topology, arrays[0].length, jointCount);
463
+ if (arrays[6].length % FLUID_RECORD_STRIDE !== 0) {
464
+ fail(`FLUIDS_INVALID: expected ${FLUID_RECORD_STRIDE} values per fluid`);
465
+ }
466
+ const topologyValues = requireTopology(
467
+ state.topology, arrays[0].length, jointCount, arrays[6].length / FLUID_RECORD_STRIDE);
312
468
  if (jointWarmState.byteLength !== 0 && topologyValues === undefined) {
313
469
  fail('TOPOLOGY_REQUIRED: nonempty joint warm state requires explicit topology');
314
470
  }
@@ -350,6 +506,8 @@ function replaceState(exports, handle, input) {
350
506
  jointWarmState.byteLength,
351
507
  topologyValues === undefined ? 0 : allocation + topologyOffset,
352
508
  topologyValues?.length ?? 0,
509
+ pointers[5], arrays[5].length,
510
+ pointers[6], arrays[6].length,
353
511
  );
354
512
  checkStatus(exports, status, 'replace state');
355
513
  } finally {
@@ -370,7 +528,7 @@ function readState(exports, handle) {
370
528
  );
371
529
  const info = new Uint32Array(exports.memory.buffer, infoPointer, STATE_INFO_VALUES);
372
530
  frame = BigInt(info[0]) | (BigInt(info[1]) << 32n);
373
- counts = Array.from(info.slice(2, 7));
531
+ counts = [...info.slice(2, 7), info[8], info[9]];
374
532
  jointWarmBytes = info[7];
375
533
  } finally {
376
534
  free(exports, infoPointer);
@@ -397,6 +555,8 @@ function readState(exports, handle) {
397
555
  pointers[0], counts[0], pointers[1], counts[1], pointers[2], counts[2],
398
556
  pointers[3], counts[3], pointers[4], counts[4],
399
557
  jointWarmBytes === 0 ? 0 : pointer + jointWarmOffset, jointWarmBytes,
558
+ pointers[5], counts[5],
559
+ pointers[6], counts[6],
400
560
  ),
401
561
  'copy state',
402
562
  );
@@ -420,12 +580,16 @@ function readState(exports, handle) {
420
580
  geometry: copy(2),
421
581
  contactCache: copy(3),
422
582
  forces: copy(4),
583
+ surfaceVelocities: copy(5),
584
+ fluids: copy(6),
423
585
  jointWarmState: warm,
424
586
  topology: Object.freeze({
425
587
  nextBodyId: currentTopology.nextBodyId,
426
588
  nextJointId: currentTopology.nextJointId,
589
+ nextFluidId: currentTopology.nextFluidId,
427
590
  bodies: currentTopology.bodies,
428
591
  joints: currentTopology.joints,
592
+ fluids: currentTopology.fluids,
429
593
  }),
430
594
  });
431
595
  } finally {
@@ -434,20 +598,27 @@ function readState(exports, handle) {
434
598
  }
435
599
 
436
600
  function readWorldInfo(exports, handle) {
437
- const pointer = allocate(exports, STATE_INFO_VALUES * 4);
601
+ const pointer = allocate(exports, 8);
438
602
  try {
439
- checkStatus(exports, exports.rundot_kinetix_world_state_info(
440
- handle, pointer, STATE_INFO_VALUES,
603
+ checkStatus(exports, exports.rundot_kinetix_world_frame(
604
+ handle, pointer,
441
605
  ), 'read world info');
442
- const values = new Uint32Array(
443
- exports.memory.buffer, pointer, STATE_INFO_VALUES);
606
+ const frame = readU64(new Uint32Array(
607
+ exports.memory.buffer, pointer, 2), 0);
444
608
  const topology = topologyInfo(exports, handle);
609
+ const metadata = nativePhysicsArtifactMetadata();
610
+ const artifact = nativePhysicsSelectedArtifact() ?? 'production';
445
611
  return Object.freeze({
446
- frame: readU64(values, 0),
612
+ frame,
447
613
  bodyCount: topology.bodyCount,
448
614
  jointCount: topology.jointCount,
615
+ fluidCount: topology.fluidCount,
449
616
  contactCount: readWorldContactCount(exports, handle),
450
617
  restoreEpoch: topology.restoreEpoch,
618
+ artifact,
619
+ artifactHash: metadata?.wasmSha256 ?? '',
620
+ simulationSourceHash: metadata?.simulationSourceHash ?? '',
621
+ digestAlgorithmRevision: metadata?.digestAlgorithmRevision ?? PHYSICS_WORLD_DIGEST_ALGORITHM_REVISION,
451
622
  });
452
623
  } finally {
453
624
  free(exports, pointer);
@@ -493,13 +664,41 @@ function restoreSnapshot(exports, handle, input) {
493
664
  }
494
665
  }
495
666
 
667
+ function checkpointCall(exports, name, handle, checkpoint, ...args) {
668
+ const token = typeof checkpoint !== 'number';
669
+ const selected = token ? `${name}_token` : name;
670
+ requireMotionExport(exports, selected);
671
+ const input = [handle];
672
+ if (token) {
673
+ appendOwn(input, checkpoint.attachment);
674
+ appendOwn(input, checkpoint.slotIndex);
675
+ appendOwn(input, checkpoint.generation);
676
+ } else appendOwn(input, checkpoint);
677
+ for (let index = 0; index < args.length; index += 1) appendOwn(input, args[index]);
678
+ return intrinsicApply(exports[selected], exports, input);
679
+ }
680
+
681
+ function readCheckpointStrongDigest(exports, handle, checkpoint) {
682
+ requireMotionExport(exports, 'rundot_kinetix_world_strong_digest_algorithm_revision');
683
+ if (exports.rundot_kinetix_world_strong_digest_algorithm_revision() !== 1) {
684
+ fail('ABI_MISMATCH: strong checkpoint digest revision');
685
+ }
686
+ const pointer = allocate(exports, 32);
687
+ try {
688
+ checkStatus(exports, checkpointCall(exports, 'rundot_kinetix_world_checkpoint_strong_digest',
689
+ handle, checkpoint, pointer), 'read strong checkpoint digest');
690
+ const bytes = new NativeU8Array(32);
691
+ intrinsicU8Set(bytes, new NativeU8Array(exports.memory.buffer, pointer, 32));
692
+ return bytes;
693
+ } finally { free(exports, pointer); }
694
+ }
695
+
496
696
  function captureCheckpointSnapshot(exports, handle, checkpointHandle) {
497
697
  const requiredPointer = allocate(exports, 4);
498
698
  let byteLength;
499
699
  try {
500
- const status = exports.rundot_kinetix_world_checkpoint_capture_snapshot(
501
- handle, checkpointHandle, 0, 0, requiredPointer,
502
- );
700
+ const status = checkpointCall(exports, 'rundot_kinetix_world_checkpoint_capture_snapshot',
701
+ handle, checkpointHandle, 0, 0, requiredPointer);
503
702
  if (status !== -6) checkStatus(exports, status, 'measure checkpoint snapshot');
504
703
  byteLength = new Uint32Array(exports.memory.buffer, requiredPointer, 1)[0];
505
704
  } finally {
@@ -510,9 +709,8 @@ function captureCheckpointSnapshot(exports, handle, checkpointHandle) {
510
709
  try {
511
710
  checkStatus(
512
711
  exports,
513
- exports.rundot_kinetix_world_checkpoint_capture_snapshot(
514
- handle, checkpointHandle, outputPointer, byteLength, outputPointer + sizeOffset,
515
- ),
712
+ checkpointCall(exports, 'rundot_kinetix_world_checkpoint_capture_snapshot',
713
+ handle, checkpointHandle, outputPointer, byteLength, outputPointer + sizeOffset),
516
714
  'capture checkpoint snapshot',
517
715
  );
518
716
  return Uint8Array.from(new Uint8Array(exports.memory.buffer, outputPointer, byteLength));
@@ -559,6 +757,380 @@ function applyWorldImpulse(exports, handle, bodyId, impulse, point) {
559
757
  checkStatus(exports, status, 'apply impulse');
560
758
  }
561
759
 
760
+ function setWorldBodyForce(exports, handle, bodyId, force, torque) {
761
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
762
+ const value = requireRecord(force, 'FORCE');
763
+ const moment = requireRecord(torque, 'TORQUE');
764
+ const status = exports.rundot_kinetix_world_set_body_force(handle,
765
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
766
+ requireFinite(value.x, 'FORCE_X'), requireFinite(value.y, 'FORCE_Y'), requireFinite(value.z, 'FORCE_Z'),
767
+ requireFinite(moment.x, 'TORQUE_X'), requireFinite(moment.y, 'TORQUE_Y'), requireFinite(moment.z, 'TORQUE_Z'));
768
+ checkStatus(exports, status, 'set body force');
769
+ }
770
+
771
+ function applyWorldForce(exports, handle, bodyId, force, torque) {
772
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
773
+ const value = requireRecord(force, 'FORCE');
774
+ const moment = requireRecord(torque, 'TORQUE');
775
+ const status = exports.rundot_kinetix_world_apply_force(handle,
776
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
777
+ requireFinite(value.x, 'FORCE_X'), requireFinite(value.y, 'FORCE_Y'), requireFinite(value.z, 'FORCE_Z'),
778
+ requireFinite(moment.x, 'TORQUE_X'), requireFinite(moment.y, 'TORQUE_Y'), requireFinite(moment.z, 'TORQUE_Z'));
779
+ checkStatus(exports, status, 'apply force');
780
+ }
781
+
782
+ function applyWorldForceAtPoint(exports, handle, bodyId, force, point) {
783
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
784
+ const value = requireRecord(force, 'FORCE');
785
+ const applicationPoint = requireRecord(point, 'POINT');
786
+ const status = exports.rundot_kinetix_world_apply_force_at_point(handle,
787
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
788
+ requireFinite(value.x, 'FORCE_X'), requireFinite(value.y, 'FORCE_Y'), requireFinite(value.z, 'FORCE_Z'),
789
+ requireFinite(applicationPoint.x, 'POINT_X'), requireFinite(applicationPoint.y, 'POINT_Y'),
790
+ requireFinite(applicationPoint.z, 'POINT_Z'));
791
+ checkStatus(exports, status, 'apply force at point');
792
+ }
793
+
794
+ function clearWorldBodyForce(exports, handle, bodyId) {
795
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
796
+ const status = exports.rundot_kinetix_world_clear_body_force(handle,
797
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n));
798
+ checkStatus(exports, status, 'clear body force');
799
+ }
800
+
801
+ function setWorldBodySurfaceVelocity(exports, handle, bodyId, velocity) {
802
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
803
+ const value = requireRecord(velocity, 'SURFACE_VELOCITY');
804
+ const status = exports.rundot_kinetix_world_set_body_surface_velocity(handle,
805
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
806
+ requireFinite(value.x, 'SURFACE_VELOCITY_X'),
807
+ requireFinite(value.y, 'SURFACE_VELOCITY_Y'),
808
+ requireFinite(value.z, 'SURFACE_VELOCITY_Z'));
809
+ checkStatus(exports, status, 'set body surface velocity');
810
+ }
811
+
812
+ function setWorldBodyLinearVelocity(exports, handle, bodyId, velocity) {
813
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
814
+ const value = requireRecord(velocity, 'LINEAR_VELOCITY');
815
+ const status = exports.rundot_kinetix_world_set_body_linear_velocity(handle,
816
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
817
+ requireFinite(value.x, 'LINEAR_VELOCITY_X'),
818
+ requireFinite(value.y, 'LINEAR_VELOCITY_Y'),
819
+ requireFinite(value.z, 'LINEAR_VELOCITY_Z'));
820
+ checkStatus(exports, status, 'set body linear velocity');
821
+ }
822
+
823
+ function setWorldBodyAngularVelocity(exports, handle, bodyId, velocity) {
824
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
825
+ const value = requireRecord(velocity, 'ANGULAR_VELOCITY');
826
+ const status = exports.rundot_kinetix_world_set_body_angular_velocity(handle,
827
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
828
+ requireFinite(value.x, 'ANGULAR_VELOCITY_X'),
829
+ requireFinite(value.y, 'ANGULAR_VELOCITY_Y'),
830
+ requireFinite(value.z, 'ANGULAR_VELOCITY_Z'));
831
+ checkStatus(exports, status, 'set body angular velocity');
832
+ }
833
+
834
+ const MOTION_MAX_BODIES = 100000;
835
+ const MOTION_POSE_STRIDE = 7;
836
+ const MOTION_VELOCITY_STRIDE = 6;
837
+
838
+ function requireMotionExport(exports, name) {
839
+ if (typeof exports[name] !== 'function') {
840
+ fail('ABI_MISMATCH: native motion channel requires a rebuilt native world artifact');
841
+ }
842
+ }
843
+
844
+ function motionRange(view, bytes) {
845
+ if (bytes === 0) return null;
846
+ return { buffer: view.buffer, start: view.byteOffset, end: view.byteOffset + bytes };
847
+ }
848
+
849
+ function motionRangesOverlap(left, right) {
850
+ if (left == null || right == null || left.buffer !== right.buffer) return false;
851
+ return left.start < right.end && right.start < left.end;
852
+ }
853
+
854
+ export function motionBufferRejection(pose, velocity, ids, status, count) {
855
+ if (!(pose instanceof Float64Array)) return 'MOTION_POSE_TYPE';
856
+ if (!(velocity instanceof Float64Array)) return 'MOTION_VELOCITY_TYPE';
857
+ if (!(ids instanceof BigUint64Array)) return 'MOTION_IDS_TYPE';
858
+ if (!(status instanceof Uint8Array)) return 'MOTION_STATUS_TYPE';
859
+ if (pose.buffer.detached === true || velocity.buffer.detached === true
860
+ || ids.buffer.detached === true || status.buffer.detached === true) {
861
+ return 'MOTION_BUFFER_DETACHED';
862
+ }
863
+ if (!Number.isInteger(count) || count < 0 || count > MOTION_MAX_BODIES) return 'MOTION_COUNT_INVALID';
864
+ if (pose.length < count * MOTION_POSE_STRIDE) return 'MOTION_POSE_SHORT';
865
+ if (velocity.length < count * MOTION_VELOCITY_STRIDE) return 'MOTION_VELOCITY_SHORT';
866
+ if (ids.length < count) return 'MOTION_IDS_SHORT';
867
+ if (status.length < count) return 'MOTION_STATUS_SHORT';
868
+ const ranges = [
869
+ motionRange(pose, count * MOTION_POSE_STRIDE * 8),
870
+ motionRange(velocity, count * MOTION_VELOCITY_STRIDE * 8),
871
+ motionRange(ids, count * 8),
872
+ motionRange(status, count),
873
+ ];
874
+ for (let left = 0; left < ranges.length; left += 1) {
875
+ for (let right = left + 1; right < ranges.length; right += 1) {
876
+ if (motionRangesOverlap(ranges[left], ranges[right])) return 'MOTION_BUFFER_ALIAS';
877
+ }
878
+ }
879
+ return null;
880
+ }
881
+
882
+ function setWorldBodyTransform(exports, handle, bodyId, position, orientation) {
883
+ const place = requireRecord(position, 'POSITION');
884
+ const rotation = requireRecord(orientation, 'ORIENTATION');
885
+ const x = requireFinite(place.x, 'POSITION_X');
886
+ const y = requireFinite(place.y, 'POSITION_Y');
887
+ const z = requireFinite(place.z, 'POSITION_Z');
888
+ const qx = requireFinite(rotation.x, 'ORIENTATION_X');
889
+ const qy = requireFinite(rotation.y, 'ORIENTATION_Y');
890
+ const qz = requireFinite(rotation.z, 'ORIENTATION_Z');
891
+ const qw = requireFinite(rotation.w, 'ORIENTATION_W');
892
+ requireMotionExport(exports, 'rundot_kinetix_world_set_body_transform');
893
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
894
+ const status = exports.rundot_kinetix_world_set_body_transform(handle,
895
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
896
+ x, y, z, qx, qy, qz, qw);
897
+ checkStatus(exports, status, 'set body transform');
898
+ }
899
+
900
+ function setWorldBodyLinearDamping(exports, handle, bodyId, damping) {
901
+ const value = requireFinite(damping, 'LINEAR_DAMPING');
902
+ if (value < 0 || value > 1) fail('LINEAR_DAMPING_RANGE');
903
+ requireMotionExport(exports, 'rundot_kinetix_world_set_body_linear_damping');
904
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
905
+ const status = exports.rundot_kinetix_world_set_body_linear_damping(handle,
906
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n), value);
907
+ checkStatus(exports, status, 'set body linear damping');
908
+ }
909
+
910
+ function wakeWorldBody(exports, handle, bodyId) {
911
+ requireMotionExport(exports, 'rundot_kinetix_world_wake_body');
912
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
913
+ const status = exports.rundot_kinetix_world_wake_body(handle,
914
+ Number(logicalId & 0xffffffffn), Number(logicalId >> 32n));
915
+ checkStatus(exports, status, 'wake body');
916
+ }
917
+
918
+ function writeWorldBodyMotion(exports, handle, pose, velocity, ids, status) {
919
+ const info = topologyInfo(exports, handle);
920
+ const count = info.bodyCount;
921
+ const rejection = motionBufferRejection(pose, velocity, ids, status, count);
922
+ if (rejection !== null) fail(rejection);
923
+ requireMotionExport(exports, 'rundot_kinetix_world_write_body_motion');
924
+ const headerBytes = 24;
925
+ const poseBytes = count * MOTION_POSE_STRIDE * 8;
926
+ const velocityBytes = count * MOTION_VELOCITY_STRIDE * 8;
927
+ const idBytes = count * 8;
928
+ const statusBytes = count;
929
+ const pointer = allocate(exports, headerBytes + poseBytes + velocityBytes + idBytes + statusBytes);
930
+ try {
931
+ const posePointer = count === 0 ? 0 : pointer + headerBytes;
932
+ const velocityPointer = count === 0 ? 0 : posePointer + poseBytes;
933
+ const idPointer = count === 0 ? 0 : velocityPointer + velocityBytes;
934
+ const statusPointer = count === 0 ? 0 : idPointer + idBytes;
935
+ checkStatus(exports, exports.rundot_kinetix_world_write_body_motion(
936
+ handle, posePointer, count * MOTION_POSE_STRIDE, velocityPointer, count * MOTION_VELOCITY_STRIDE,
937
+ idPointer, count * 2, statusPointer, count, pointer, 6,
938
+ ), 'write body motion');
939
+ const memory = exports.memory.buffer;
940
+ const header = new Uint32Array(memory, pointer, 6);
941
+ if (header[0] !== count) fail('MOTION_COUNT_MISMATCH');
942
+ if (header[1] !== 1) fail('MOTION_STATUS_VERSION');
943
+ if (count > 0) {
944
+ pose.set(new Float64Array(memory, posePointer, count * MOTION_POSE_STRIDE));
945
+ velocity.set(new Float64Array(memory, velocityPointer, count * MOTION_VELOCITY_STRIDE));
946
+ ids.set(new BigUint64Array(memory, idPointer, count));
947
+ status.set(new Uint8Array(memory, statusPointer, count));
948
+ }
949
+ return Object.freeze({
950
+ count,
951
+ mutationRevision: BigInt(header[2]) | (BigInt(header[3]) << 32n),
952
+ restoreEpoch: BigInt(header[4]) | (BigInt(header[5]) << 32n),
953
+ });
954
+ } finally {
955
+ free(exports, pointer);
956
+ }
957
+ }
958
+
959
+ function readCheckpointViewInfo(exports, handle, checkpoint) {
960
+ const pointer = allocate(exports, 28);
961
+ try {
962
+ checkStatus(exports, checkpointCall(exports, 'rundot_kinetix_world_checkpoint_view_info', handle, checkpoint, pointer, 7), 'read checkpoint info');
963
+ const words = new Uint32Array(exports.memory.buffer, pointer, 7);
964
+ if (words[2] > MOTION_MAX_BODIES) fail('MOTION_COUNT_INVALID');
965
+ return Object.freeze({ frame: readU64(words, 0), bodyCount: words[2],
966
+ contactCount: words[3], jointReactionCount: words[4], jointBreakCount: words[5], fluidInteractionCount: words[6] });
967
+ } finally { free(exports, pointer); }
968
+ }
969
+
970
+ function writeCheckpointBodyMotion(exports, handle, checkpoint, pose, velocity, ids, status) {
971
+ const info = readCheckpointViewInfo(exports, handle, checkpoint);
972
+ const count = info.bodyCount;
973
+ const rejection = motionBufferRejection(pose, velocity, ids, status, count);
974
+ if (rejection !== null) fail(rejection);
975
+ const poseBytes = count * MOTION_POSE_STRIDE * 8;
976
+ const velocityBytes = count * MOTION_VELOCITY_STRIDE * 8;
977
+ const idBytes = count * 8;
978
+ const pointer = allocate(exports, 24 + poseBytes + velocityBytes + idBytes + count);
979
+ try {
980
+ const afterAllocation = motionBufferRejection(pose, velocity, ids, status, count);
981
+ if (afterAllocation !== null) fail(afterAllocation);
982
+ const posePointer = count === 0 ? 0 : pointer + 24;
983
+ const velocityPointer = count === 0 ? 0 : posePointer + poseBytes;
984
+ const idPointer = count === 0 ? 0 : velocityPointer + velocityBytes;
985
+ const statusPointer = count === 0 ? 0 : idPointer + idBytes;
986
+ checkStatus(exports, checkpointCall(exports, 'rundot_kinetix_world_checkpoint_write_body_motion_into',
987
+ handle, checkpoint, posePointer, count * MOTION_POSE_STRIDE,
988
+ velocityPointer, count * MOTION_VELOCITY_STRIDE, idPointer, count * 2,
989
+ statusPointer, count, pointer, 6), 'write checkpoint motion');
990
+ const memory = exports.memory.buffer;
991
+ const header = new Uint32Array(memory, pointer, 6);
992
+ if (header[0] !== count || header[1] !== 1 || readU64(header, 2) !== info.frame
993
+ || header[4] !== 0 || header[5] !== 0) fail('CHECKPOINT_MOTION_HEADER_INVALID');
994
+ if (count > 0) {
995
+ Float64Array.prototype.set.call(pose, new Float64Array(memory, posePointer, count * MOTION_POSE_STRIDE));
996
+ Float64Array.prototype.set.call(velocity, new Float64Array(memory, velocityPointer, count * MOTION_VELOCITY_STRIDE));
997
+ BigUint64Array.prototype.set.call(ids, new BigUint64Array(memory, idPointer, count));
998
+ Uint8Array.prototype.set.call(status, new Uint8Array(memory, statusPointer, count));
999
+ }
1000
+ return Object.freeze({ count, frame: info.frame });
1001
+ } finally { free(exports, pointer); }
1002
+ }
1003
+
1004
+ const SUPPORT_SPRING_BYTES = 96;
1005
+ const SUPPORT_FORCE_BYTES = 64;
1006
+
1007
+ function requireSupportExport(exports, name) {
1008
+ if (typeof exports[name] !== 'function') {
1009
+ fail('ABI_MISMATCH: native support channel requires a rebuilt native world artifact');
1010
+ }
1011
+ }
1012
+
1013
+ function writeLogicalId(view, offset, id, label) {
1014
+ const logicalId = requireLogicalId(id, label);
1015
+ view.setUint32(offset, Number(logicalId & 0xffffffffn), true);
1016
+ view.setUint32(offset + 4, Number(logicalId >> 32n), true);
1017
+ return logicalId;
1018
+ }
1019
+
1020
+ function writeVec3(view, offset, record, label) {
1021
+ const value = requireRecord(record, label);
1022
+ view.setFloat64(offset, requireFinite(value.x, `${label}_X`), true);
1023
+ view.setFloat64(offset + 8, requireFinite(value.y, `${label}_Y`), true);
1024
+ view.setFloat64(offset + 16, requireFinite(value.z, `${label}_Z`), true);
1025
+ }
1026
+
1027
+ function applyWorldSupport(exports, handle, springs, forces, wakeTarget) {
1028
+ requireSupportExport(exports, 'rundot_kinetix_world_apply_support');
1029
+ if (!Array.isArray(springs) || !Array.isArray(forces)) {
1030
+ fail('SUPPORT_INPUT_INVALID: springs and forces must be arrays');
1031
+ }
1032
+ requireSupportExport(exports, 'rundot_kinetix_world_max_support_records');
1033
+ const capacity = exports.rundot_kinetix_world_max_support_records();
1034
+ if (springs.length + forces.length > capacity) {
1035
+ fail('SUPPORT_INPUT_INVALID: support record count exceeds the native limit');
1036
+ }
1037
+ let wake = 0n;
1038
+ if (wakeTarget != null && wakeTarget !== 0n) wake = requireLogicalId(wakeTarget, 'WAKE_BODY_ID');
1039
+ const byteLength = springs.length * SUPPORT_SPRING_BYTES + forces.length * SUPPORT_FORCE_BYTES;
1040
+ const pointer = allocate(exports, byteLength);
1041
+ try {
1042
+ if (byteLength > 0) {
1043
+ const view = new DataView(exports.memory.buffer, pointer, byteLength);
1044
+ springs.forEach((spring, index) => {
1045
+ const offset = index * SUPPORT_SPRING_BYTES;
1046
+ writeLogicalId(view, offset, spring?.body, 'BODY_ID');
1047
+ writeLogicalId(view, offset + 8, spring?.support, 'SUPPORT_ID');
1048
+ writeVec3(view, offset + 16, spring?.point, 'POINT');
1049
+ writeVec3(view, offset + 40, spring?.normal, 'NORMAL');
1050
+ view.setFloat64(offset + 64, requireFinite(spring?.compression, 'COMPRESSION'), true);
1051
+ view.setFloat64(offset + 72, requireFinite(spring?.travel, 'TRAVEL'), true);
1052
+ view.setFloat64(offset + 80, requireFinite(spring?.stiffness, 'STIFFNESS'), true);
1053
+ view.setFloat64(offset + 88, requireFinite(spring?.damping, 'DAMPING'), true);
1054
+ });
1055
+ const forceBase = springs.length * SUPPORT_SPRING_BYTES;
1056
+ forces.forEach((force, index) => {
1057
+ const offset = forceBase + index * SUPPORT_FORCE_BYTES;
1058
+ writeLogicalId(view, offset, force?.body, 'BODY_ID');
1059
+ writeLogicalId(view, offset + 8, force?.support, 'SUPPORT_ID');
1060
+ writeVec3(view, offset + 16, force?.force, 'FORCE');
1061
+ writeVec3(view, offset + 40, force?.point, 'POINT');
1062
+ });
1063
+ }
1064
+ const springPointer = springs.length === 0 ? 0 : pointer;
1065
+ const forcePointer = forces.length === 0 ? 0 : pointer + springs.length * SUPPORT_SPRING_BYTES;
1066
+ checkStatus(exports, exports.rundot_kinetix_world_apply_support(
1067
+ handle, springPointer, springs.length, forcePointer, forces.length,
1068
+ Number(wake & 0xffffffffn), Number(wake >> 32n),
1069
+ ), 'apply support');
1070
+ } finally {
1071
+ free(exports, pointer);
1072
+ }
1073
+ }
1074
+
1075
+ function readWorldSurfaceVelocity(exports, handle, bodyId) {
1076
+ requireSupportExport(exports, 'rundot_kinetix_world_read_surface_velocity');
1077
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
1078
+ const pointer = allocate(exports, 24);
1079
+ try {
1080
+ checkStatus(exports, exports.rundot_kinetix_world_read_surface_velocity(
1081
+ handle, Number(logicalId & 0xffffffffn), Number(logicalId >> 32n), pointer,
1082
+ ), `read surface velocity ${logicalId}`);
1083
+ const values = Float64Array.from(new Float64Array(exports.memory.buffer, pointer, 3));
1084
+ return Object.freeze({ x: values[0], y: values[1], z: values[2] });
1085
+ } finally {
1086
+ free(exports, pointer);
1087
+ }
1088
+ }
1089
+
1090
+ function readWorldBodyMobility(exports, handle, bodyId) {
1091
+ requireSupportExport(exports, 'rundot_kinetix_world_read_body_mobility');
1092
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
1093
+ const pointer = allocate(exports, 72);
1094
+ try {
1095
+ checkStatus(exports, exports.rundot_kinetix_world_read_body_mobility(
1096
+ handle, Number(logicalId & 0xffffffffn), Number(logicalId >> 32n), pointer, pointer + 24,
1097
+ ), `read body mobility ${logicalId}`);
1098
+ const linear = Float64Array.from(new Float64Array(exports.memory.buffer, pointer, 3));
1099
+ const angular = Float64Array.from(new Float64Array(exports.memory.buffer, pointer + 24, 6));
1100
+ return Object.freeze({
1101
+ inverseLinear: Object.freeze({ x: linear[0], y: linear[1], z: linear[2] }),
1102
+ inverseAngular: Object.freeze([...angular]),
1103
+ });
1104
+ } finally {
1105
+ free(exports, pointer);
1106
+ }
1107
+ }
1108
+
1109
+ // Tick-start sample for virtual-velocity prediction.
1110
+ // The sample does not integrate, wake, or clear records.
1111
+ // Native code still rejects substeps above 64.
1112
+ function readWorldPendingSupportImpulse(exports, handle, bodyId, dt, substeps) {
1113
+ requireSupportExport(exports, 'rundot_kinetix_world_read_pending_support_impulse');
1114
+ const logicalId = requireLogicalId(bodyId, 'BODY_ID');
1115
+ const pointer = allocate(exports, 56);
1116
+ try {
1117
+ checkStatus(exports, exports.rundot_kinetix_world_read_pending_support_impulse(
1118
+ handle, Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
1119
+ requireFinite(dt, 'DT'), requireU32(substeps, 'SUBSTEPS', 1), pointer, pointer + 24, pointer + 48,
1120
+ ), `read pending support impulse ${logicalId}`);
1121
+ const linear = Float64Array.from(new Float64Array(exports.memory.buffer, pointer, 3));
1122
+ const angular = Float64Array.from(new Float64Array(exports.memory.buffer, pointer + 24, 3));
1123
+ const belowBound = new Uint32Array(exports.memory.buffer, pointer + 48, 1)[0];
1124
+ return Object.freeze({
1125
+ linear: Object.freeze({ x: linear[0], y: linear[1], z: linear[2] }),
1126
+ angular: Object.freeze({ x: angular[0], y: angular[1], z: angular[2] }),
1127
+ belowBound,
1128
+ });
1129
+ } finally {
1130
+ free(exports, pointer);
1131
+ }
1132
+ }
1133
+
562
1134
  function readU64(values, offset) {
563
1135
  return BigInt(values[offset]) | (BigInt(values[offset + 1]) << 32n);
564
1136
  }
@@ -577,7 +1149,8 @@ function topologyInfo(exports, handle) {
577
1149
  const values = new Uint32Array(exports.memory.buffer, pointer, TOPOLOGY_INFO_STRIDE);
578
1150
  return {
579
1151
  restoreEpoch: readU64(values, 0), nextBodyId: readU64(values, 2), nextJointId: readU64(values, 4),
580
- bodyCount: values[6], jointCount: values[7],
1152
+ nextFluidId: readU64(values, 6), bodyCount: values[8], jointCount: values[9],
1153
+ fluidCount: values[10], mutationRevision: readU64(values, 11),
581
1154
  };
582
1155
  } finally { free(exports, pointer); }
583
1156
  }
@@ -586,19 +1159,25 @@ function readTopology(exports, handle) {
586
1159
  const info = topologyInfo(exports, handle);
587
1160
  const bodyValues = info.bodyCount * 2;
588
1161
  const jointValues = info.jointCount * 6;
589
- const pointer = allocate(exports, (bodyValues + jointValues) * 4);
1162
+ const fluidValues = info.fluidCount * 2;
1163
+ const pointer = allocate(exports, (bodyValues + jointValues + fluidValues) * 4);
590
1164
  try {
591
1165
  checkStatus(exports, exports.rundot_kinetix_world_copy_topology(
592
1166
  handle, pointer, bodyValues, pointer + bodyValues * 4, jointValues,
1167
+ pointer + (bodyValues + jointValues) * 4, fluidValues,
593
1168
  ), 'copy topology');
594
- const values = new Uint32Array(exports.memory.buffer, pointer, bodyValues + jointValues);
1169
+ const values = new Uint32Array(exports.memory.buffer, pointer,
1170
+ bodyValues + jointValues + fluidValues);
595
1171
  return Object.freeze({
596
- restoreEpoch: info.restoreEpoch, nextBodyId: info.nextBodyId, nextJointId: info.nextJointId,
1172
+ restoreEpoch: info.restoreEpoch, nextBodyId: info.nextBodyId,
1173
+ nextJointId: info.nextJointId, nextFluidId: info.nextFluidId,
597
1174
  bodies: Object.freeze(Array.from({ length: info.bodyCount }, (_, index) => readU64(values, index * 2))),
598
1175
  joints: Object.freeze(Array.from({ length: info.jointCount }, (_, index) => {
599
1176
  const offset = bodyValues + index * 6;
600
1177
  return Object.freeze({ id: readU64(values, offset), bodyA: readU64(values, offset + 2), bodyB: readU64(values, offset + 4) });
601
1178
  })),
1179
+ fluids: Object.freeze(Array.from({ length: info.fluidCount }, (_, index) =>
1180
+ readU64(values, bodyValues + jointValues + index * 2))),
602
1181
  });
603
1182
  } finally { free(exports, pointer); }
604
1183
  }
@@ -653,6 +1232,8 @@ function worldQueryFlags(query) {
653
1232
 
654
1233
  function runWorldQuery(exports, handle, kind, input) {
655
1234
  const query = requireRecord(input, 'QUERY');
1235
+ if (query.onlyBody !== undefined && kind !== 1) fail('QUERY_ONLY_BODY_INVALID: only rays support a selected body');
1236
+ const onlyBody = query.onlyBody === undefined ? 0n : requireLogicalId(query.onlyBody, 'QUERY_ONLY_BODY');
656
1237
  const isOverlap = kind === 2;
657
1238
  const isDirectional = kind === 1 || kind === 3;
658
1239
  const shape = isOverlap || kind === 3
@@ -677,7 +1258,7 @@ function runWorldQuery(exports, handle, kind, input) {
677
1258
  const excludedBody = query.excludeBody === undefined
678
1259
  ? 0n
679
1260
  : requireLogicalId(query.excludeBody, 'QUERY_EXCLUDE_BODY');
680
- const bodyCount = topologyInfo(exports, handle).bodyCount;
1261
+ const bodyCount = onlyBody === 0n ? topologyInfo(exports, handle).bodyCount : 1;
681
1262
  const queryBytes = WORLD_QUERY_INPUT_STRIDE * 8;
682
1263
  const hitBytes = bodyCount * WORLD_QUERY_HIT_STRIDE * 8;
683
1264
  const idBytes = bodyCount * WORLD_QUERY_BODY_ID_STRIDE * 4;
@@ -685,6 +1266,7 @@ function runWorldQuery(exports, handle, kind, input) {
685
1266
  const pointer = allocate(exports, requiredOffset + 4);
686
1267
  try {
687
1268
  const values = new Float64Array(exports.memory.buffer, pointer, WORLD_QUERY_INPUT_STRIDE);
1269
+ values.fill(0);
688
1270
  values.set(shape, 0);
689
1271
  values[7] = requireFinite(query.x, 'QUERY_X');
690
1272
  values[8] = requireFinite(query.y, 'QUERY_Y');
@@ -702,8 +1284,11 @@ function runWorldQuery(exports, handle, kind, input) {
702
1284
  values[20] = -1;
703
1285
  const hitPointer = pointer + queryBytes;
704
1286
  const idPointer = hitPointer + hitBytes;
705
- const status = exports.rundot_kinetix_world_query(
706
- handle, kind, pointer, WORLD_QUERY_INPUT_STRIDE,
1287
+ const runQuery = onlyBody === 0n
1288
+ ? (...args) => exports.rundot_kinetix_world_query(handle, kind, ...args)
1289
+ : (...args) => exports.rundot_kinetix_world_query_body_ray(handle,
1290
+ Number(onlyBody & 0xffffffffn), Number(onlyBody >> 32n), ...args);
1291
+ const status = runQuery(pointer, WORLD_QUERY_INPUT_STRIDE,
707
1292
  Number(excludedBody & 0xffffffffn), Number(excludedBody >> 32n),
708
1293
  bodyCount === 0 ? 0 : hitPointer, bodyCount * WORLD_QUERY_HIT_STRIDE,
709
1294
  bodyCount === 0 ? 0 : idPointer, bodyCount * WORLD_QUERY_BODY_ID_STRIDE,
@@ -731,9 +1316,47 @@ function runWorldQuery(exports, handle, kind, input) {
731
1316
  }
732
1317
  }
733
1318
 
734
- function makeLiveHandle(owner, kind, id, epoch) {
735
- const result = Object.freeze({ id });
736
- liveHandles.set(result, { owner, kind, id, epoch });
1319
+ function readCheckpointLatestOutputs(exports, handle, checkpoint) {
1320
+ const info = readCheckpointViewInfo(exports, handle, checkpoint);
1321
+ const contacts = info.contactCount;
1322
+ const reactions = info.jointReactionCount;
1323
+ const breaks = info.jointBreakCount;
1324
+ const fluids = info.fluidInteractionCount;
1325
+ const contactValues = contacts * WORLD_CONTACT_OUTPUT_VALUE_STRIDE;
1326
+ const reactionValues = reactions * WORLD_JOINT_REACTION_VALUE_STRIDE;
1327
+ const fluidValues = fluids * WORLD_FLUID_INTERACTION_VALUE_STRIDE;
1328
+ const valueBytes = (contactValues + reactionValues + fluidValues) * 8;
1329
+ const contactWords = contacts * WORLD_CONTACT_OUTPUT_METADATA_STRIDE;
1330
+ const reactionWords = reactions * WORLD_JOINT_REACTION_METADATA_STRIDE;
1331
+ const breakWords = breaks * WORLD_JOINT_BREAK_METADATA_STRIDE;
1332
+ const fluidWords = fluids * WORLD_FLUID_INTERACTION_METADATA_STRIDE;
1333
+ const byteLength = valueBytes + (contactWords + reactionWords + breakWords + fluidWords) * 4;
1334
+ if (!Number.isSafeInteger(byteLength) || byteLength > 0x7ffffff0) fail('CHECKPOINT_OUTPUT_LENGTH_INVALID');
1335
+ if (byteLength === 0) return Object.freeze({ frame: info.frame,
1336
+ contacts: Object.freeze([]), reactions: Object.freeze([]), breaks: Object.freeze([]), fluids: Object.freeze([]) });
1337
+ const pointer = allocate(exports, byteLength);
1338
+ try {
1339
+ checkStatus(exports, checkpointCall(exports, 'rundot_kinetix_world_checkpoint_copy_latest_output', handle, checkpoint, pointer, byteLength), 'read checkpoint outputs');
1340
+ const memory = exports.memory.buffer;
1341
+ const contactData = new Float64Array(memory, pointer, contactValues);
1342
+ const reactionData = new Float64Array(memory, pointer + contactValues * 8, reactionValues);
1343
+ const fluidData = new Float64Array(memory, pointer + (contactValues + reactionValues) * 8, fluidValues);
1344
+ const metaPointer = pointer + valueBytes;
1345
+ const contactMeta = new Uint32Array(memory, metaPointer, contactWords);
1346
+ const reactionMeta = new Uint32Array(memory, metaPointer + contactWords * 4, reactionWords);
1347
+ const breakMeta = new Uint32Array(memory, metaPointer + (contactWords + reactionWords) * 4, breakWords);
1348
+ const fluidMeta = new Uint32Array(memory, metaPointer + (contactWords + reactionWords + breakWords) * 4, fluidWords);
1349
+ const joints = decodeWorldJointOutput(reactionData, reactionMeta, breakMeta, reactions, breaks);
1350
+ return Object.freeze({ frame: info.frame,
1351
+ contacts: decodeWorldContactOutput(contactData, contactMeta, contacts),
1352
+ reactions: joints.reactions, breaks: joints.breaks,
1353
+ fluids: decodeWorldFluidInteractions(fluidData, fluidMeta, fluids) });
1354
+ } finally { free(exports, pointer); }
1355
+ }
1356
+
1357
+ function makeLiveHandle(owner, kind, id, epoch, cell = committedHandleCell) {
1358
+ const result = intrinsicFreeze({ id });
1359
+ intrinsicWeakSet(liveHandles, result, { owner, kind, id, epoch, cell });
737
1360
  return result;
738
1361
  }
739
1362
 
@@ -758,17 +1381,46 @@ function readWorldBody(exports, handle, id) {
758
1381
  }
759
1382
  }
760
1383
 
1384
+ function readWorldGeometry(exports, handle, id) {
1385
+ const logicalId = requireLogicalId(id, 'BODY_ID');
1386
+ const low = Number(logicalId & 0xffffffffn);
1387
+ const high = Number(logicalId >> 32n);
1388
+ const infoPointer = allocate(exports, 24);
1389
+ let info;
1390
+ try {
1391
+ checkStatus(exports, exports.rundot_kinetix_world_body_geometry_info(
1392
+ handle, low, high, infoPointer, 6,
1393
+ ), `read body geometry ${logicalId}`);
1394
+ info = [...new Uint32Array(exports.memory.buffer, infoPointer, 6)];
1395
+ } finally { free(exports, infoPointer); }
1396
+ const [version, kind, count, format, featureOffset, scalarCount] = info;
1397
+ if (version !== 1 || kind < 3 || kind > 6 || count === 0
1398
+ || scalarCount !== count * 3 || scalarCount > MAX_GEOMETRY_VALUES) fail('BODY_GEOMETRY_INFO_INVALID');
1399
+ const pointer = allocate(exports, scalarCount * 8);
1400
+ try {
1401
+ checkStatus(exports, exports.rundot_kinetix_world_copy_body_geometry(
1402
+ handle, low, high, pointer, scalarCount,
1403
+ ), `copy body geometry ${logicalId}`);
1404
+ return Object.freeze({
1405
+ kind, count, format, featureOffset,
1406
+ values: Float64Array.from(new Float64Array(exports.memory.buffer, pointer, scalarCount)),
1407
+ });
1408
+ } finally { free(exports, pointer); }
1409
+ }
1410
+
761
1411
  function readWorldJoint(exports, handle, id) {
762
1412
  const logicalId = requireLogicalId(id, 'JOINT_ID');
763
- const endpointOffset = PHYSICS_JOINT_STRIDE * 8;
1413
+ const maxJointValues = 3 * PHYSICS_JOINT_STRIDE;
1414
+ const endpointOffset = maxJointValues * 8;
764
1415
  const pointer = allocate(exports, endpointOffset + 16);
765
1416
  try {
766
1417
  checkStatus(exports, exports.rundot_kinetix_world_read_joint(
767
1418
  handle, Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
768
- pointer, PHYSICS_JOINT_STRIDE, pointer + endpointOffset, 4,
1419
+ pointer, maxJointValues, pointer + endpointOffset, 4,
769
1420
  ), `read joint ${logicalId}`);
1421
+ const kind = new Float64Array(exports.memory.buffer, pointer, 1)[0];
770
1422
  const values = new Float64Array(new Float64Array(
771
- exports.memory.buffer, pointer, PHYSICS_JOINT_STRIDE));
1423
+ exports.memory.buffer, pointer, kind === 10 ? maxJointValues : PHYSICS_JOINT_STRIDE));
772
1424
  const endpoints = new Uint32Array(exports.memory.buffer, pointer + endpointOffset, 4);
773
1425
  return Object.freeze({
774
1426
  values,
@@ -780,6 +1432,21 @@ function readWorldJoint(exports, handle, id) {
780
1432
  }
781
1433
  }
782
1434
 
1435
+ function readWorldFluid(exports, handle, id) {
1436
+ const logicalId = requireLogicalId(id, 'FLUID_ID');
1437
+ const pointer = allocate(exports, FLUID_RECORD_STRIDE * 8);
1438
+ try {
1439
+ checkStatus(exports, exports.rundot_kinetix_world_read_fluid(
1440
+ handle, Number(logicalId & 0xffffffffn), Number(logicalId >> 32n),
1441
+ pointer, FLUID_RECORD_STRIDE,
1442
+ ), `read fluid ${logicalId}`);
1443
+ return new Float64Array(new Float64Array(
1444
+ exports.memory.buffer, pointer, FLUID_RECORD_STRIDE));
1445
+ } finally {
1446
+ free(exports, pointer);
1447
+ }
1448
+ }
1449
+
783
1450
  function readWorldContactCount(exports, handle) {
784
1451
  const countPointer = allocate(exports, 4);
785
1452
  try {
@@ -792,6 +1459,40 @@ function readWorldContactCount(exports, handle) {
792
1459
  }
793
1460
  }
794
1461
 
1462
+ function decodeWorldContactOutput(values, metadata, count) {
1463
+ return Object.freeze(Array.from({ length: count }, (_, index) => {
1464
+ const valueOffset = index * WORLD_CONTACT_OUTPUT_VALUE_STRIDE;
1465
+ const metadataOffset = index * WORLD_CONTACT_OUTPUT_METADATA_STRIDE;
1466
+ const flags = metadata[metadataOffset + 5];
1467
+ const type = metadata[metadataOffset] === 1 ? 'enter'
1468
+ : metadata[metadataOffset] === 2 ? 'stay'
1469
+ : metadata[metadataOffset] === 3 ? 'exit' : undefined;
1470
+ if (type === undefined) fail('CONTACT_OUTPUT_INVALID');
1471
+ return Object.freeze({
1472
+ type,
1473
+ bodyA: readU64(metadata, metadataOffset + 1),
1474
+ bodyB: readU64(metadata, metadataOffset + 3),
1475
+ trigger: (flags & 1) !== 0,
1476
+ sensor: (flags & 2) !== 0,
1477
+ normalImpulse: values[valueOffset],
1478
+ tangentImpulse1: values[valueOffset + 1],
1479
+ tangentImpulse2: values[valueOffset + 2],
1480
+ point: Object.freeze({
1481
+ x: values[valueOffset + 3],
1482
+ y: values[valueOffset + 4],
1483
+ z: values[valueOffset + 5],
1484
+ }),
1485
+ normal: Object.freeze({
1486
+ x: values[valueOffset + 6],
1487
+ y: values[valueOffset + 7],
1488
+ z: values[valueOffset + 8],
1489
+ }),
1490
+ penetration: values[valueOffset + 9],
1491
+ closingSpeed: values[valueOffset + 10],
1492
+ });
1493
+ }));
1494
+ }
1495
+
795
1496
  function readWorldContactOutput(exports, handle) {
796
1497
  const count = readWorldContactCount(exports, handle);
797
1498
  if (count === 0) return Object.freeze([]);
@@ -809,64 +1510,168 @@ function readWorldContactOutput(exports, handle) {
809
1510
  const metadata = new Uint32Array(
810
1511
  exports.memory.buffer, pointer + valueBytes,
811
1512
  count * WORLD_CONTACT_OUTPUT_METADATA_STRIDE);
812
- return Object.freeze(Array.from({ length: count }, (_, index) => {
813
- const valueOffset = index * WORLD_CONTACT_OUTPUT_VALUE_STRIDE;
814
- const metadataOffset = index * WORLD_CONTACT_OUTPUT_METADATA_STRIDE;
815
- const flags = metadata[metadataOffset + 5];
816
- const type = metadata[metadataOffset] === 1 ? 'enter'
817
- : metadata[metadataOffset] === 2 ? 'stay'
818
- : metadata[metadataOffset] === 3 ? 'exit' : undefined;
819
- if (type === undefined) fail('CONTACT_OUTPUT_INVALID');
820
- return Object.freeze({
821
- type,
822
- bodyA: readU64(metadata, metadataOffset + 1),
823
- bodyB: readU64(metadata, metadataOffset + 3),
824
- trigger: (flags & 1) !== 0,
825
- sensor: (flags & 2) !== 0,
826
- normalImpulse: values[valueOffset],
827
- tangentImpulse1: values[valueOffset + 1],
828
- tangentImpulse2: values[valueOffset + 2],
829
- point: Object.freeze({
830
- x: values[valueOffset + 3],
831
- y: values[valueOffset + 4],
832
- z: values[valueOffset + 5],
833
- }),
834
- normal: Object.freeze({
835
- x: values[valueOffset + 6],
836
- y: values[valueOffset + 7],
837
- z: values[valueOffset + 8],
838
- }),
839
- penetration: values[valueOffset + 9],
840
- });
841
- }));
1513
+ return decodeWorldContactOutput(values, metadata, count);
1514
+ } finally {
1515
+ free(exports, pointer);
1516
+ }
1517
+ }
1518
+
1519
+ function decodeWorldJointOutput(values, metadata, breakMetadata, reactionCount, breakCount) {
1520
+ const reactions = Object.freeze(Array.from({ length: reactionCount }, (_, index) => {
1521
+ const valueOffset = index * WORLD_JOINT_REACTION_VALUE_STRIDE;
1522
+ const metadataOffset = index * WORLD_JOINT_REACTION_METADATA_STRIDE;
1523
+ return Object.freeze({
1524
+ jointId: readU64(metadata, metadataOffset),
1525
+ bodyA: readU64(metadata, metadataOffset + 2),
1526
+ bodyB: readU64(metadata, metadataOffset + 4),
1527
+ force: Object.freeze({ x: values[valueOffset], y: values[valueOffset + 1], z: values[valueOffset + 2] }),
1528
+ torque: Object.freeze({ x: values[valueOffset + 3], y: values[valueOffset + 4], z: values[valueOffset + 5] }),
1529
+ });
1530
+ }));
1531
+ const breaks = Object.freeze(Array.from({ length: breakCount }, (_, index) => {
1532
+ const metadataOffset = index * WORLD_JOINT_BREAK_METADATA_STRIDE;
1533
+ const reasonBits = breakMetadata[metadataOffset + 2];
1534
+ const reason = reasonBits === 1 ? 'impulse'
1535
+ : reasonBits === 2 ? 'force'
1536
+ : reasonBits === 4 ? 'torque'
1537
+ : reasonBits === 6 ? 'force-and-torque' : undefined;
1538
+ if (reason === undefined) fail('JOINT_OUTPUT_INVALID');
1539
+ return Object.freeze({
1540
+ jointId: readU64(breakMetadata, metadataOffset),
1541
+ reason,
1542
+ });
1543
+ }));
1544
+ return Object.freeze({ reactions, breaks });
1545
+ }
1546
+
1547
+ function readWorldJointOutput(exports, handle) {
1548
+ const countPointer = allocate(exports, 8);
1549
+ let reactionCount;
1550
+ let breakCount;
1551
+ try {
1552
+ checkStatus(exports, exports.rundot_kinetix_world_joint_output_info(
1553
+ handle, countPointer, countPointer + 4,
1554
+ ), 'read joint output counts');
1555
+ const counts = new Uint32Array(exports.memory.buffer, countPointer, 2);
1556
+ reactionCount = counts[0];
1557
+ breakCount = counts[1];
1558
+ } finally {
1559
+ free(exports, countPointer);
1560
+ }
1561
+ if (reactionCount === 0 && breakCount === 0) {
1562
+ return Object.freeze({ reactions: Object.freeze([]), breaks: Object.freeze([]) });
1563
+ }
1564
+ const valueBytes = reactionCount * WORLD_JOINT_REACTION_VALUE_STRIDE * 8;
1565
+ const reactionMetadataBytes = reactionCount * WORLD_JOINT_REACTION_METADATA_STRIDE * 4;
1566
+ const breakMetadataBytes = breakCount * WORLD_JOINT_BREAK_METADATA_STRIDE * 4;
1567
+ const pointer = allocate(exports, valueBytes + reactionMetadataBytes + breakMetadataBytes);
1568
+ try {
1569
+ checkStatus(exports, exports.rundot_kinetix_world_copy_joint_output(
1570
+ handle,
1571
+ pointer, reactionCount * WORLD_JOINT_REACTION_VALUE_STRIDE,
1572
+ pointer + valueBytes, reactionCount * WORLD_JOINT_REACTION_METADATA_STRIDE,
1573
+ pointer + valueBytes + reactionMetadataBytes,
1574
+ breakCount * WORLD_JOINT_BREAK_METADATA_STRIDE,
1575
+ ), 'copy joint output');
1576
+ const values = new Float64Array(exports.memory.buffer, pointer,
1577
+ reactionCount * WORLD_JOINT_REACTION_VALUE_STRIDE);
1578
+ const metadata = new Uint32Array(exports.memory.buffer, pointer + valueBytes,
1579
+ reactionCount * WORLD_JOINT_REACTION_METADATA_STRIDE);
1580
+ const breakMetadata = new Uint32Array(exports.memory.buffer,
1581
+ pointer + valueBytes + reactionMetadataBytes,
1582
+ breakCount * WORLD_JOINT_BREAK_METADATA_STRIDE);
1583
+ return decodeWorldJointOutput(values, metadata, breakMetadata, reactionCount, breakCount);
1584
+ } finally {
1585
+ free(exports, pointer);
1586
+ }
1587
+ }
1588
+
1589
+ function decodeWorldFluidInteractions(values, metadata, count) {
1590
+ return Object.freeze(Array.from({ length: count }, (_, index) => {
1591
+ const valueOffset = index * WORLD_FLUID_INTERACTION_VALUE_STRIDE;
1592
+ const metadataOffset = index * WORLD_FLUID_INTERACTION_METADATA_STRIDE;
1593
+ return Object.freeze({
1594
+ bodyId: readU64(metadata, metadataOffset),
1595
+ fluidId: readU64(metadata, metadataOffset + 2),
1596
+ submergedVolume: values[valueOffset],
1597
+ centerOfBuoyancy: Object.freeze({
1598
+ x: values[valueOffset + 1], y: values[valueOffset + 2], z: values[valueOffset + 3],
1599
+ }),
1600
+ totalForce: Object.freeze({
1601
+ x: values[valueOffset + 4], y: values[valueOffset + 5], z: values[valueOffset + 6],
1602
+ }),
1603
+ totalTorque: Object.freeze({
1604
+ x: values[valueOffset + 7], y: values[valueOffset + 8], z: values[valueOffset + 9],
1605
+ }),
1606
+ relativeVelocity: Object.freeze({
1607
+ x: values[valueOffset + 10], y: values[valueOffset + 11], z: values[valueOffset + 12],
1608
+ }),
1609
+ shouldWake: metadata[metadataOffset + 4] !== 0,
1610
+ });
1611
+ }));
1612
+ }
1613
+
1614
+ function readWorldFluidInteractions(exports, handle) {
1615
+ const countPointer = allocate(exports, 4);
1616
+ let count;
1617
+ try {
1618
+ checkStatus(exports, exports.rundot_kinetix_world_fluid_interaction_info(
1619
+ handle, countPointer,
1620
+ ), 'read fluid interaction count');
1621
+ count = new Uint32Array(exports.memory.buffer, countPointer, 1)[0];
1622
+ } finally {
1623
+ free(exports, countPointer);
1624
+ }
1625
+ if (count === 0) return Object.freeze([]);
1626
+ const valueBytes = count * WORLD_FLUID_INTERACTION_VALUE_STRIDE * 8;
1627
+ const metadataBytes = count * WORLD_FLUID_INTERACTION_METADATA_STRIDE * 4;
1628
+ const pointer = allocate(exports, valueBytes + metadataBytes);
1629
+ try {
1630
+ checkStatus(exports, exports.rundot_kinetix_world_copy_fluid_interactions(
1631
+ handle,
1632
+ pointer, count * WORLD_FLUID_INTERACTION_VALUE_STRIDE,
1633
+ pointer + valueBytes, count * WORLD_FLUID_INTERACTION_METADATA_STRIDE,
1634
+ ), 'copy fluid interactions');
1635
+ const values = new Float64Array(exports.memory.buffer, pointer,
1636
+ count * WORLD_FLUID_INTERACTION_VALUE_STRIDE);
1637
+ const metadata = new Uint32Array(exports.memory.buffer,
1638
+ pointer + valueBytes, count * WORLD_FLUID_INTERACTION_METADATA_STRIDE);
1639
+ return decodeWorldFluidInteractions(values, metadata, count);
842
1640
  } finally {
843
1641
  free(exports, pointer);
844
1642
  }
845
1643
  }
846
1644
 
847
1645
  function topologyReference(exports, handle, owner, epoch, kind, input, label) {
848
- if (typeof input === 'bigint') return [kind === 'body' ? 2 : 4, requireLogicalId(input, label)];
1646
+ const existingTag = kind === 'body' ? 2 : kind === 'joint' ? 4 : 6;
1647
+ const createdTag = kind === 'body' ? 1 : kind === 'joint' ? 3 : 5;
1648
+ if (typeof input === 'bigint') return [existingTag, requireLogicalId(input, label)];
849
1649
  const value = requireRecord(input, label);
850
1650
  const live = liveHandles.get(value);
851
1651
  if (live) {
1652
+ if (live.cell.state !== 'committed') fail(`HANDLE_UNPUBLISHED: ${label}: use a committed handle`);
852
1653
  if (live.owner !== owner) fail(`HANDLE_WRONG_WORLD: ${label}: obtain a handle from this world`);
853
1654
  if (live.kind !== kind) fail(`HANDLE_KIND_INVALID: ${label}: use a ${kind} handle`);
854
1655
  if (live.epoch !== epoch) fail(`HANDLE_STALE: ${label}: obtain a new handle after restore or replace`);
855
1656
  checkIdentityExists(exports, handle, kind, live.id);
856
- return [kind === 'body' ? 2 : 4, live.id];
1657
+ return [existingTag, live.id];
857
1658
  }
858
- const key = kind === 'body' ? 'createdBody' : 'createdJoint';
859
- return [kind === 'body' ? 1 : 3, BigInt(requireU32(value[key], `${label}.${key}`, 1))];
1659
+ const key = kind === 'body' ? 'createdBody'
1660
+ : kind === 'joint' ? 'createdJoint' : 'createdFluid';
1661
+ return [createdTag, BigInt(requireU32(value[key], `${label}.${key}`, 1))];
860
1662
  }
861
1663
 
862
- function applyTopologyBatch(exports, handle, owner, commands) {
863
- if (!Array.isArray(commands) || commands.length > MAX_TOPOLOGY_COMMANDS) {
1664
+ function encodeTopologyBatch(commands, referenceReader) {
1665
+ if (!intrinsicIsArray(commands) || commands.length > MAX_TOPOLOGY_COMMANDS) {
864
1666
  fail(`TOPOLOGY_COMMANDS_INVALID: supply an array with at most ${MAX_TOPOLOGY_COMMANDS} commands`);
865
1667
  }
866
- const info = topologyInfo(exports, handle);
867
- const encoded = new Uint32Array(commands.length * TOPOLOGY_COMMAND_STRIDE);
1668
+ const encoded = new NativeU32Array(commands.length * TOPOLOGY_COMMAND_STRIDE);
868
1669
  const bodies = [];
869
1670
  const joints = [];
1671
+ const fluids = [];
1672
+ const geometry = [];
1673
+ let jointSlotCount = 0;
1674
+ let geometryValueCount = 0;
870
1675
  let resultCount = 0;
871
1676
  const writeRef = (offset, reference) => {
872
1677
  encoded[offset] = reference[0];
@@ -877,24 +1682,55 @@ function applyTopologyBatch(exports, handle, owner, commands) {
877
1682
  const label = `command[${index}]`;
878
1683
  const command = requireRecord(commands[index], label);
879
1684
  const offset = index * TOPOLOGY_COMMAND_STRIDE;
880
- const ref = (kind, value, field) => topologyReference(exports, handle, owner, info.restoreEpoch, kind, value, `${label}.${field}`);
1685
+ const ref = (kind, value, field) => referenceReader(kind, value, `${label}.${field}`);
881
1686
  const record = (records, stride) => {
882
1687
  const values = requireValues(command.values, `${label}.values`);
883
1688
  if (values.length !== stride) fail(`TOPOLOGY_RECORD_INVALID: ${label}.values: expected ${stride} doubles`);
884
1689
  encoded[offset + 10] = records.length;
885
- records.push(Float64Array.from(values));
1690
+ appendOwn(records, copyF64(values));
886
1691
  };
1692
+ const recordGeometry = () => {
1693
+ if (command.geometry === undefined) return;
1694
+ const action = requireRecord(command.geometry, `${label}.geometry`);
1695
+ switch (action.type) {
1696
+ case 'keep':
1697
+ rejectUnknownFields(action, geometryKeepFields, `${label}.geometry`);
1698
+ break;
1699
+ case 'clear':
1700
+ rejectUnknownFields(action, geometryKeepFields, `${label}.geometry`);
1701
+ encoded[offset + 12] = 2;
1702
+ break;
1703
+ case 'install': {
1704
+ rejectUnknownFields(action, geometryInstallFields, `${label}.geometry`);
1705
+ const values = requireValues(action.values, `${label}.geometry.values`);
1706
+ if (values.length === 0 || values.length % 3 !== 0
1707
+ || values.length > MAX_GEOMETRY_VALUES - geometryValueCount) fail('TOPOLOGY_GEOMETRY_INVALID');
1708
+ encoded[offset + 12] = 1;
1709
+ encoded[offset + 13] = geometryValueCount;
1710
+ encoded[offset + 14] = values.length;
1711
+ geometryValueCount += values.length;
1712
+ appendOwn(geometry, copyF64(values));
1713
+ break;
1714
+ }
1715
+ default: fail(`TOPOLOGY_GEOMETRY_INVALID: ${label}.geometry.type: use keep, install, or clear`);
1716
+ }
1717
+ };
1718
+ if (command.geometry !== undefined && command.type !== 'createBody' && command.type !== 'editBody') {
1719
+ fail(`TOPOLOGY_GEOMETRY_INVALID: ${label}: only body create and edit commands accept geometry`);
1720
+ }
887
1721
  switch (command.type) {
888
1722
  case 'createBody':
889
1723
  encoded[offset] = 1;
890
1724
  writeRef(offset + 1, [1, BigInt(requireU32(command.key, `${label}.key`, 1))]);
891
1725
  record(bodies, PHYSICS_BODY_STRIDE);
1726
+ recordGeometry();
892
1727
  resultCount += 1;
893
1728
  break;
894
1729
  case 'editBody':
895
1730
  encoded[offset] = 2;
896
1731
  writeRef(offset + 1, ref('body', command.body, 'body'));
897
1732
  record(bodies, PHYSICS_BODY_STRIDE);
1733
+ recordGeometry();
898
1734
  break;
899
1735
  case 'removeBody':
900
1736
  encoded[offset] = 3;
@@ -909,7 +1745,14 @@ function applyTopologyBatch(exports, handle, owner, commands) {
909
1745
  : ref('joint', command.joint, 'joint'));
910
1746
  writeRef(offset + 4, ref('body', command.bodyA, 'bodyA'));
911
1747
  writeRef(offset + 7, ref('body', command.bodyB, 'bodyB'));
912
- record(joints, PHYSICS_JOINT_STRIDE);
1748
+ {
1749
+ const values = requireValues(command.values, `${label}.values`);
1750
+ const stride = values[0] === 10 ? 3 * PHYSICS_JOINT_STRIDE : PHYSICS_JOINT_STRIDE;
1751
+ if (values.length !== stride) fail(`TOPOLOGY_RECORD_INVALID: ${label}.values: expected ${stride} doubles`);
1752
+ encoded[offset + 10] = jointSlotCount;
1753
+ jointSlotCount += stride / PHYSICS_JOINT_STRIDE;
1754
+ appendOwn(joints, copyF64(values));
1755
+ }
913
1756
  if (command.type === 'createJoint') resultCount += 1;
914
1757
  break;
915
1758
  case 'removeJoint':
@@ -917,44 +1760,120 @@ function applyTopologyBatch(exports, handle, owner, commands) {
917
1760
  writeRef(offset + 1, ref('joint', command.joint, 'joint'));
918
1761
  encoded[offset + 10] = 0xffffffff;
919
1762
  break;
920
- default: fail(`TOPOLOGY_COMMAND_INVALID: ${label}.type: use createBody, editBody, removeBody, createJoint, editJoint, or removeJoint`);
1763
+ case 'createFluid':
1764
+ encoded[offset] = 7;
1765
+ writeRef(offset + 1, [5, BigInt(requireU32(command.key, `${label}.key`, 1))]);
1766
+ record(fluids, FLUID_RECORD_STRIDE);
1767
+ resultCount += 1;
1768
+ break;
1769
+ case 'editFluid':
1770
+ encoded[offset] = 8;
1771
+ writeRef(offset + 1, ref('fluid', command.fluid, 'fluid'));
1772
+ record(fluids, FLUID_RECORD_STRIDE);
1773
+ break;
1774
+ case 'removeFluid':
1775
+ encoded[offset] = 9;
1776
+ writeRef(offset + 1, ref('fluid', command.fluid, 'fluid'));
1777
+ encoded[offset + 10] = 0xffffffff;
1778
+ break;
1779
+ default: fail(`TOPOLOGY_COMMAND_INVALID: ${label}.type: use a body, joint, or fluid topology command`);
921
1780
  }
922
1781
  }
923
1782
  const bodyOffset = encoded.byteLength;
924
1783
  const jointOffset = bodyOffset + bodies.length * PHYSICS_BODY_STRIDE * 8;
925
- const resultOffset = jointOffset + joints.length * PHYSICS_JOINT_STRIDE * 8;
1784
+ const fluidOffset = jointOffset + jointSlotCount * PHYSICS_JOINT_STRIDE * 8;
1785
+ const geometryOffset = fluidOffset + fluids.length * FLUID_RECORD_STRIDE * 8;
1786
+ const resultOffset = geometryOffset + geometryValueCount * 8;
926
1787
  const requiredOffset = resultOffset + resultCount * TOPOLOGY_RESULT_STRIDE * 4;
1788
+ return { encoded, bodies, joints, fluids, geometry, jointSlotCount, geometryValueCount,
1789
+ resultCount, bodyOffset, jointOffset, fluidOffset, geometryOffset, resultOffset, requiredOffset,
1790
+ commandCount: commands.length };
1791
+ }
1792
+
1793
+ function writeTopologyScratch(exports, pointer, packet) {
1794
+ const { encoded, bodies, joints, fluids, geometry, bodyOffset, jointOffset, fluidOffset,
1795
+ geometryOffset } = packet;
1796
+ intrinsicU32Set(new NativeU32Array(exports.memory.buffer, pointer, encoded.length), encoded);
1797
+ for (let index = 0; index < bodies.length; index += 1) {
1798
+ intrinsicF64Set(new NativeF64Array(exports.memory.buffer,
1799
+ pointer + bodyOffset + index * PHYSICS_BODY_STRIDE * 8, PHYSICS_BODY_STRIDE), bodies[index]);
1800
+ }
1801
+ let jointPointer = pointer + jointOffset;
1802
+ for (let index = 0; index < joints.length; index += 1) {
1803
+ const values = joints[index];
1804
+ intrinsicF64Set(new NativeF64Array(exports.memory.buffer, jointPointer, values.length), values);
1805
+ jointPointer += values.byteLength;
1806
+ }
1807
+ for (let index = 0; index < fluids.length; index += 1) {
1808
+ intrinsicF64Set(new NativeF64Array(exports.memory.buffer,
1809
+ pointer + fluidOffset + index * FLUID_RECORD_STRIDE * 8, FLUID_RECORD_STRIDE), fluids[index]);
1810
+ }
1811
+ let geometryPointer = pointer + geometryOffset;
1812
+ for (let index = 0; index < geometry.length; index += 1) {
1813
+ const values = geometry[index];
1814
+ intrinsicF64Set(new NativeF64Array(exports.memory.buffer, geometryPointer, values.length), values);
1815
+ geometryPointer += values.byteLength;
1816
+ }
1817
+ }
1818
+
1819
+ function applyTopologyBatch(exports, handle, owner, commands) {
1820
+ const info = topologyInfo(exports, handle);
1821
+ const packet = encodeTopologyBatch(commands,
1822
+ (kind, input, label) => topologyReference(exports, handle, owner, info.restoreEpoch, kind, input, label));
1823
+ const { bodyOffset, jointOffset, fluidOffset, geometryOffset, resultOffset, requiredOffset,
1824
+ bodies, jointSlotCount, fluids, geometryValueCount, resultCount } = packet;
927
1825
  const pointer = allocate(exports, requiredOffset + 4);
928
1826
  try {
929
- new Uint32Array(exports.memory.buffer, pointer, encoded.length).set(encoded);
930
- for (let index = 0; index < bodies.length; index += 1) {
931
- new Float64Array(exports.memory.buffer, pointer + bodyOffset + index * PHYSICS_BODY_STRIDE * 8, PHYSICS_BODY_STRIDE).set(bodies[index]);
932
- }
933
- for (let index = 0; index < joints.length; index += 1) {
934
- new Float64Array(exports.memory.buffer, pointer + jointOffset + index * PHYSICS_JOINT_STRIDE * 8, PHYSICS_JOINT_STRIDE).set(joints[index]);
935
- }
936
- checkStatus(exports, exports.rundot_kinetix_world_apply_topology_batch(
937
- handle, pointer, commands.length, pointer + bodyOffset, bodies.length, pointer + jointOffset, joints.length,
1827
+ writeTopologyScratch(exports, pointer, packet);
1828
+ checkStatus(exports, exports.rundot_kinetix_world_apply_topology_geometry_batch(
1829
+ handle, TOPOLOGY_GEOMETRY_ABI_VERSION,
1830
+ pointer, commands.length, pointer + bodyOffset, bodies.length, pointer + jointOffset, jointSlotCount,
1831
+ pointer + fluidOffset, fluids.length,
1832
+ pointer + geometryOffset, geometryValueCount,
938
1833
  pointer + resultOffset, resultCount * TOPOLOGY_RESULT_STRIDE, pointer + requiredOffset,
939
1834
  ), 'apply topology batch');
940
1835
  const count = new Uint32Array(exports.memory.buffer, pointer + requiredOffset, 1)[0];
941
1836
  if (count > resultCount * TOPOLOGY_RESULT_STRIDE || count % TOPOLOGY_RESULT_STRIDE !== 0) fail('TOPOLOGY_RESULT_INVALID');
942
1837
  const values = new Uint32Array(exports.memory.buffer, pointer + resultOffset, count);
943
- const result = { bodies: [], joints: [] };
1838
+ const result = { bodies: [], joints: [], fluids: [] };
944
1839
  for (let offset = 0; offset < count; offset += TOPOLOGY_RESULT_STRIDE) {
945
- const kind = values[offset] === 1 ? 'body' : values[offset] === 2 ? 'joint' : undefined;
1840
+ const kind = values[offset] === 1 ? 'body'
1841
+ : values[offset] === 2 ? 'joint'
1842
+ : values[offset] === 3 ? 'fluid' : undefined;
946
1843
  if (kind === undefined) fail('TOPOLOGY_RESULT_INVALID');
947
1844
  const id = readU64(values, offset + 2);
948
- result[kind === 'body' ? 'bodies' : 'joints'].push(Object.freeze({
1845
+ const collection = kind === 'body' ? 'bodies'
1846
+ : kind === 'joint' ? 'joints' : 'fluids';
1847
+ result[collection].push(Object.freeze({
949
1848
  key: values[offset + 1], id, handle: makeLiveHandle(owner, kind, id, info.restoreEpoch),
950
1849
  }));
951
1850
  }
952
- return Object.freeze({ bodies: Object.freeze(result.bodies), joints: Object.freeze(result.joints) });
1851
+ return Object.freeze({ bodies: Object.freeze(result.bodies),
1852
+ joints: Object.freeze(result.joints), fluids: Object.freeze(result.fluids) });
953
1853
  } finally { free(exports, pointer); }
954
1854
  }
955
1855
 
1856
+ export function attachNativePhysicsWorld(world, expectedInitialDigest) {
1857
+ if (world === null || typeof world !== 'object') fail('WORLD_INVALID');
1858
+ const descriptor = intrinsicDescriptor(world, runtimeAttachmentKey);
1859
+ if (typeof descriptor?.value !== 'function') fail('WORLD_INVALID: use a native physics world');
1860
+ return intrinsicApply(descriptor.value, world, [expectedInitialDigest]);
1861
+ }
1862
+
1863
+ export function bindNativePhysicsWorldFacade(facade, nativeWorld) {
1864
+ const descriptor = intrinsicDescriptor(nativeWorld, runtimeAttachmentKey);
1865
+ if (typeof descriptor?.value !== 'function') fail('WORLD_INVALID');
1866
+ intrinsicDefine(facade, runtimeAttachmentKey, { value(expectedDigest) {
1867
+ if (this !== facade) fail('WORLD_INVALID: use the original physics world');
1868
+ return intrinsicApply(descriptor.value, nativeWorld, [expectedDigest]);
1869
+ } });
1870
+ }
1871
+
956
1872
  export function createNativePhysicsWorld(options) {
957
- const exports = requireInitialized();
1873
+ return createNativePhysicsWorldWithExports(requireInitialized(), options);
1874
+ }
1875
+
1876
+ export function createNativePhysicsWorldWithExports(exports, options) {
958
1877
  const config = requireRecord(options, 'PROFILE');
959
1878
  if (typeof config.profileId !== 'string' || config.profileId.length === 0) fail('PROFILE_ID_INVALID');
960
1879
  const profileId = textEncoder.encode(config.profileId);
@@ -964,32 +1883,111 @@ export function createNativePhysicsWorld(options) {
964
1883
  }
965
1884
  const digestOffset = profileId.byteLength;
966
1885
  const handleOffset = (digestOffset + 32 + 3) & ~3;
967
- const allocation = allocate(exports, handleOffset + 4);
1886
+ const capacity = config.capacity === undefined
1887
+ ? {} : requireRecord(config.capacity, 'CAPACITY');
1888
+ const checkpointCapacity = requireU32(capacity.checkpoints ?? 64, 'CHECKPOINT_CAPACITY', 1);
1889
+ if (checkpointCapacity > 4096) fail('CHECKPOINT_CAPACITY_INVALID: maximum is 4096');
1890
+ const bodyCapacity = requireU32(capacity.bodies ?? 100000, 'BODY_CAPACITY', 1);
1891
+ const jointCapacity = requireU32(capacity.joints ?? 10000, 'JOINT_CAPACITY');
1892
+ const fluidCapacity = requireU32(capacity.fluids ?? 64, 'FLUID_CAPACITY');
1893
+ const fluidInteractionCapacity = requireU32(
1894
+ capacity.fluidInteractions ?? 0, 'FLUID_INTERACTION_CAPACITY');
1895
+ const scratch = new Map();
1896
+ function acquireScratch(kind, bytes) {
1897
+ const pointer = allocate(exports, bytes);
1898
+ scratch.set(kind, pointer);
1899
+ return pointer;
1900
+ }
1901
+ function growScratch(kind, bytes) {
1902
+ const pointer = allocate(exports, bytes);
1903
+ try { free(exports, scratch.get(kind)); }
1904
+ catch (error) {
1905
+ try { free(exports, pointer); }
1906
+ catch (cleanup) { throw new AggregateError([error, cleanup], 'Scratch growth cleanup failed.', { cause: error }); }
1907
+ throw error;
1908
+ }
1909
+ scratch.set(kind, pointer);
1910
+ return pointer;
1911
+ }
1912
+ function releaseScratch() {
1913
+ const errors = [];
1914
+ for (const [kind, pointer] of [...scratch].reverse()) {
1915
+ try {
1916
+ free(exports, pointer);
1917
+ scratch.delete(kind);
1918
+ } catch (error) { errors.push(error); }
1919
+ }
1920
+ if (errors.length !== 0) throw new AggregateError(errors, 'Scratch release failed.');
1921
+ }
1922
+ let allocation = allocate(exports, handleOffset + 4);
968
1923
  let handle;
1924
+ let bodyScratch;
1925
+ let topoScratch;
1926
+ let jointScratch;
1927
+ let fluidScratch;
1928
+ let topoScratchCapacity = 4096;
1929
+ let jointScratchCapacity = 1024;
1930
+ let fluidScratchCapacity = 1024;
969
1931
  try {
1932
+ bodyScratch = acquireScratch('body', Math.max(PHYSICS_BODY_STRIDE * 8, TOPOLOGY_INFO_STRIDE * 4));
1933
+ topoScratch = acquireScratch('topology', topoScratchCapacity * 8);
1934
+ jointScratch = acquireScratch('joint', jointScratchCapacity * 6 * 4);
1935
+ fluidScratch = acquireScratch('fluid', fluidScratchCapacity * 2 * 4);
970
1936
  new Uint8Array(exports.memory.buffer, allocation, profileId.byteLength).set(profileId);
971
1937
  new Uint8Array(exports.memory.buffer, allocation + digestOffset, 32).set(config.geometryDigest);
972
1938
  checkStatus(
973
1939
  exports,
974
- exports.rundot_kinetix_world_create(
1940
+ exports.rundot_kinetix_world_create_with_checkpoint_capacity(
975
1941
  requireU32(config.abiVersion ?? PHYSICS_ABI_VERSION, 'ABI_VERSION', 1),
976
1942
  requireU32(config.numericProfile ?? 1, 'NUMERIC_PROFILE', 1),
977
1943
  allocation,
978
1944
  profileId.byteLength,
979
1945
  allocation + digestOffset,
980
1946
  32,
1947
+ bodyCapacity,
1948
+ jointCapacity,
1949
+ fluidCapacity,
1950
+ fluidInteractionCapacity,
1951
+ checkpointCapacity,
981
1952
  allocation + handleOffset,
982
1953
  ),
983
1954
  'create',
984
1955
  );
985
1956
  handle = new Uint32Array(exports.memory.buffer, allocation + handleOffset, 1)[0];
986
- } finally {
987
1957
  free(exports, allocation);
1958
+ allocation = 0;
1959
+ } catch (error) {
1960
+ const failures = [error];
1961
+ if (handle !== undefined) {
1962
+ try { checkStatus(exports, exports.rundot_kinetix_world_destroy(handle), 'construction cleanup'); }
1963
+ catch (cleanup) { failures.push(cleanup); }
1964
+ }
1965
+ try { releaseScratch(); }
1966
+ catch (cleanup) {
1967
+ if (cleanup instanceof AggregateError) {
1968
+ for (const sub of cleanup.errors) failures.push(sub);
1969
+ } else {
1970
+ failures.push(cleanup);
1971
+ }
1972
+ }
1973
+ try { free(exports, allocation); }
1974
+ catch (cleanup) { failures.push(cleanup); }
1975
+ if (failures.length > 1) throw new AggregateError(failures, 'World construction cleanup failed.', { cause: error });
1976
+ throw error;
988
1977
  }
989
1978
  let disposed = false;
990
1979
  let activeOperation;
1980
+ let runtimeReadScope;
991
1981
  const owner = {};
992
1982
  const checkpoints = new WeakMap();
1983
+ let pendingCheckpointCleanup;
1984
+ let runtimeAttachment;
1985
+ const legacyCleanup = { buffers: undefined };
1986
+ const legacyExports = runtimeExports(legacyCleanup);
1987
+ let cachedMemoryBuffer = exports.memory.buffer;
1988
+ let cachedMemoryF64 = new Float64Array(cachedMemoryBuffer);
1989
+ let cachedMemoryU32 = new Uint32Array(cachedMemoryBuffer);
1990
+ const bodyScratchIndex = bodyScratch >> 3;
993
1991
 
994
1992
  function mutate(operation, action) {
995
1993
  ensureActive(disposed);
@@ -999,40 +1997,619 @@ export function createNativePhysicsWorld(options) {
999
1997
  finally { activeOperation = undefined; }
1000
1998
  }
1001
1999
 
2000
+ function ensureReadable() {
2001
+ ensureActive(disposed);
2002
+ if (runtimeReadScope !== undefined) fail('REENTRY: use a checkpoint view during a read-only runtime callback');
2003
+ }
2004
+
1002
2005
  function checkpointHandle(checkpoint) {
1003
- const checkpointHandle = checkpoint !== null && typeof checkpoint === 'object'
1004
- ? checkpoints.get(checkpoint)
2006
+ const record = checkpoint !== null && typeof checkpoint === 'object'
2007
+ ? intrinsicWeakGet(checkpoints, checkpoint)
1005
2008
  : undefined;
1006
- if (checkpointHandle === undefined) fail('CHECKPOINT_INVALID');
1007
- return checkpointHandle;
2009
+ if (record === undefined || record.state !== 'active' || record.mode !== 'legacy') fail('CHECKPOINT_INVALID');
2010
+ return record.id;
2011
+ }
2012
+
2013
+ function removeCheckpointCleanup(record) {
2014
+ if (pendingCheckpointCleanup === record) pendingCheckpointCleanup = record.next;
2015
+ else {
2016
+ let previous = pendingCheckpointCleanup;
2017
+ while (previous !== undefined && previous.next !== record) previous = previous.next;
2018
+ if (previous !== undefined) previous.next = record.next;
2019
+ }
2020
+ record.next = undefined;
2021
+ }
2022
+
2023
+ function cleanCheckpointRecord(record) {
2024
+ const errors = [];
2025
+ if (record.id !== 0 || record.generation !== 0) {
2026
+ try {
2027
+ const selected = record.mode === 'legacy' ? record.id : record;
2028
+ checkStatus(record.cleanupExports, checkpointCall(record.cleanupExports, 'rundot_kinetix_world_checkpoint_release', handle, selected),
2029
+ 'release unpublished checkpoint');
2030
+ record.id = 0;
2031
+ record.generation = 0;
2032
+ removeRuntimeCheckpoint(record);
2033
+ } catch (error) { errors.push(error); }
2034
+ }
2035
+ if (record.pointer !== 0) {
2036
+ try { free(exports, record.pointer); record.pointer = 0; }
2037
+ catch (error) { errors.push(error); }
2038
+ }
2039
+ if (record.runtimeOwner === undefined) {
2040
+ try { cleanRuntimeBuffers(record); }
2041
+ catch (error) { appendOwn(errors, error); }
2042
+ }
2043
+ if (record.id === 0 && record.generation === 0 && record.pointer === 0
2044
+ && record.buffers === undefined) removeCheckpointCleanup(record);
2045
+ return errors;
2046
+ }
2047
+
2048
+ function cleanPendingCheckpoints() {
2049
+ const errors = [];
2050
+ try { cleanRuntimeBuffers(legacyCleanup); }
2051
+ catch (error) { errors.push(error); }
2052
+ let record = pendingCheckpointCleanup;
2053
+ while (record !== undefined) {
2054
+ const next = record.next;
2055
+ const failures = cleanCheckpointRecord(record);
2056
+ for (let index = 0; index < failures.length; index += 1) errors.push(failures[index]);
2057
+ record = next;
2058
+ }
2059
+ if (errors.length !== 0) throw new AggregateError(errors, 'Checkpoint cleanup failed.');
2060
+ }
2061
+
2062
+ function removeRuntimeCheckpoint(record) {
2063
+ const cell = record.runtimeOwner;
2064
+ if (cell === undefined) return;
2065
+ if (record.runtimePrevious === undefined) cell.captures = record.runtimeNext;
2066
+ else record.runtimePrevious.runtimeNext = record.runtimeNext;
2067
+ if (record.runtimeNext !== undefined) record.runtimeNext.runtimePrevious = record.runtimePrevious;
2068
+ record.runtimeOwner = undefined;
2069
+ record.runtimeNext = undefined;
2070
+ record.runtimePrevious = undefined;
2071
+ }
2072
+
2073
+ function publishCheckpoint(byteLength, produce, attachment = 0, runtimeOwner) {
2074
+ cleanPendingCheckpoints();
2075
+ const checkpoint = intrinsicFreeze({});
2076
+ const record = { mode: attachment === 0 ? 'legacy' : 'token', attachment, slotIndex: 0, generation: 0,
2077
+ runtimeOwner, runtimeNext: runtimeOwner?.captures, runtimePrevious: undefined,
2078
+ id: 0, pointer: 0, state: 'building', next: pendingCheckpointCleanup, buffers: undefined, cleanupExports: undefined };
2079
+ record.cleanupExports = runtimeOwner?.cleanupExports ?? legacyExports;
2080
+ intrinsicWeakSet(checkpoints, checkpoint, record);
2081
+ pendingCheckpointCleanup = record;
2082
+ if (runtimeOwner !== undefined) {
2083
+ if (runtimeOwner.captures !== undefined) runtimeOwner.captures.runtimePrevious = record;
2084
+ runtimeOwner.captures = record;
2085
+ }
2086
+ try {
2087
+ record.pointer = allocate(exports, byteLength);
2088
+ produce(record);
2089
+ free(exports, record.pointer);
2090
+ record.pointer = 0;
2091
+ record.state = 'active';
2092
+ removeCheckpointCleanup(record);
2093
+ return checkpoint;
2094
+ } catch (error) {
2095
+ record.state = 'failed';
2096
+ intrinsicWeakDelete(checkpoints, checkpoint);
2097
+ const errors = cleanCheckpointRecord(record);
2098
+ if (runtimeOwner === undefined) {
2099
+ try { cleanRuntimeBuffers(legacyCleanup); }
2100
+ catch (cleanup) { errors.push(cleanup); }
2101
+ }
2102
+ if (record.id === 0 && record.generation === 0) removeRuntimeCheckpoint(record);
2103
+ if (errors.length !== 0) throw new AggregateError([error, ...errors],
2104
+ 'Checkpoint publication cleanup failed.', { cause: error });
2105
+ throw error;
2106
+ }
2107
+ }
2108
+
2109
+ function releaseDisposedScratch() {
2110
+ const errors = [];
2111
+ try { cleanPendingCheckpoints(); }
2112
+ catch (error) {
2113
+ if (error instanceof AggregateError) {
2114
+ for (const sub of error.errors) errors.push(sub);
2115
+ } else {
2116
+ errors.push(error);
2117
+ }
2118
+ }
2119
+ try { releaseScratch(); }
2120
+ catch (error) {
2121
+ if (error instanceof AggregateError) {
2122
+ for (const sub of error.errors) errors.push(sub);
2123
+ } else {
2124
+ errors.push(error);
2125
+ }
2126
+ }
2127
+ if (errors.length !== 0) throw new AggregateError(errors, 'Disposed world cleanup failed.');
2128
+ }
2129
+
2130
+ function removeRuntimeBuffer(cell, selected) {
2131
+ if (cell.buffers === selected) cell.buffers = selected.next;
2132
+ else {
2133
+ let previous = cell.buffers;
2134
+ while (previous !== undefined && previous.next !== selected) previous = previous.next;
2135
+ if (previous !== undefined) previous.next = selected.next;
2136
+ }
2137
+ selected.next = undefined;
2138
+ }
2139
+
2140
+ function cleanRuntimeBuffers(cell) {
2141
+ const errors = [];
2142
+ let record = cell.buffers;
2143
+ while (record !== undefined) {
2144
+ const next = record.next;
2145
+ try { free(exports, record.pointer); removeRuntimeBuffer(cell, record); }
2146
+ catch (error) { appendOwn(errors, error); }
2147
+ record = next;
2148
+ }
2149
+ if (errors.length !== 0) throw new AggregateError(errors, 'Runtime buffer cleanup failed.');
2150
+ }
2151
+
2152
+ function runtimeExports(cell) {
2153
+ const selected = intrinsicCreate(exports);
2154
+ intrinsicDefine(selected, 'rundot_kinetix_world_buffer_allocate', {
2155
+ value(bytes) {
2156
+ const record = { pointer: 0, next: cell.buffers };
2157
+ const pointer = exports.rundot_kinetix_world_buffer_allocate(bytes);
2158
+ if (Number.isInteger(pointer) && pointer > 0) {
2159
+ record.pointer = pointer;
2160
+ cell.buffers = record;
2161
+ }
2162
+ return pointer;
2163
+ },
2164
+ });
2165
+ intrinsicDefine(selected, 'rundot_kinetix_world_buffer_free', {
2166
+ value(pointer) {
2167
+ const status = exports.rundot_kinetix_world_buffer_free(pointer);
2168
+ if (status === 0) {
2169
+ let record = cell.buffers;
2170
+ while (record !== undefined && record.pointer !== pointer) record = record.next;
2171
+ if (record !== undefined) removeRuntimeBuffer(cell, record);
2172
+ }
2173
+ return status;
2174
+ },
2175
+ });
2176
+ return selected;
2177
+ }
2178
+
2179
+ function cleanUnpublishedAttachment(cell) {
2180
+ const errors = [];
2181
+ drainRuntimeCaptures(cell, errors);
2182
+ if (cell.token !== 0) {
2183
+ try {
2184
+ checkStatus(cell.cleanupExports, exports.rundot_kinetix_world_detach(handle, cell.token), 'detach unpublished runtime');
2185
+ cell.token = 0;
2186
+ } catch (error) { appendOwn(errors, error); }
2187
+ }
2188
+ if (cell.pointer !== 0) {
2189
+ try { free(exports, cell.pointer); cell.pointer = 0; }
2190
+ catch (error) { appendOwn(errors, error); }
2191
+ }
2192
+ try { cleanRuntimeBuffers(cell); }
2193
+ catch (error) { appendOwn(errors, error); }
2194
+ if (cell.token === 0 && cell.pointer === 0 && cell.buffers === undefined && cell.captures === undefined) {
2195
+ cell.state = 'detached';
2196
+ runtimeAttachment = undefined;
2197
+ }
2198
+ if (errors.length !== 0) throw new AggregateError(errors, 'Runtime attachment cleanup failed.');
2199
+ }
2200
+
2201
+ function drainRuntimeCaptures(cell, errors) {
2202
+ try { cleanRuntimeBuffers(cell); }
2203
+ catch (error) { appendOwn(errors, error); }
2204
+ try { cleanPendingCheckpoints(); }
2205
+ catch (error) { appendOwn(errors, error); }
2206
+ let record = cell.captures;
2207
+ while (record !== undefined) {
2208
+ const next = record.runtimeNext;
2209
+ try {
2210
+ checkStatus(cell.cleanupExports,
2211
+ checkpointCall(cell.cleanupExports, 'rundot_kinetix_world_checkpoint_release', handle, record),
2212
+ 'release retained runtime checkpoint');
2213
+ record.generation = 0; record.state = 'released';
2214
+ removeRuntimeCheckpoint(record);
2215
+ } catch (error) { appendOwn(errors, error); }
2216
+ record = next;
2217
+ }
2218
+ }
2219
+
2220
+ function acquireRuntimeController(expectedDigest) {
2221
+ return mutate('attach runtime', () => {
2222
+ if (typeof expectedDigest !== 'bigint' || expectedDigest < 0n || expectedDigest > 0xffffffffffffffffn) {
2223
+ fail('INITIAL_DIGEST_INVALID: use an unsigned 64-bit digest');
2224
+ }
2225
+ if (runtimeAttachment !== undefined) {
2226
+ if (runtimeAttachment.state === 'active') fail('WORLD_ATTACHED');
2227
+ cleanUnpublishedAttachment(runtimeAttachment);
2228
+ }
2229
+ cleanPendingCheckpoints();
2230
+ const names = ['attach', 'detach', 'revision', 'checkpoint_capture_token', 'checkpoint_restore_token',
2231
+ 'checkpoint_release_token', 'checkpoint_capture_snapshot_token', 'checkpoint_import_token',
2232
+ 'checkpoint_strong_digest_token', 'checkpoint_digest_token', 'checkpoint_view_info_token', 'checkpoint_write_body_motion_into_token',
2233
+ 'checkpoint_copy_latest_output_token', 'checkpoint_capacity', 'checkpoint_live_count', 'checkpoint_preflight'];
2234
+ for (let index = 0; index < names.length; index += 1) {
2235
+ if (typeof exports[`rundot_kinetix_world_${names[index]}`] !== 'function') fail('ABI_MISMATCH: runtime token exports are required');
2236
+ }
2237
+ const cell = { token: 0, pointer: 0, state: 'building', buffers: undefined, captures: undefined,
2238
+ capacity: 0, cleanupExports: undefined };
2239
+ runtimeAttachment = cell;
2240
+ try {
2241
+ const selectedExports = runtimeExports(cell);
2242
+ cell.cleanupExports = selectedExports;
2243
+ const active = (cleanBuffers) => {
2244
+ ensureActive(disposed);
2245
+ if (cell.state !== 'active') fail('RUNTIME_DETACHED');
2246
+ if (cleanBuffers) cleanRuntimeBuffers(cell);
2247
+ };
2248
+ const selected = checkpoint => {
2249
+ const record = checkpoint !== null && typeof checkpoint === 'object'
2250
+ ? intrinsicWeakGet(checkpoints, checkpoint) : undefined;
2251
+ if (record === undefined || record.state !== 'active' || record.mode !== 'token'
2252
+ || record.attachment !== cell.token) fail('CHECKPOINT_INVALID');
2253
+ return record;
2254
+ };
2255
+ const readScalar = (name, wide) => {
2256
+ const pointer = allocate(selectedExports, wide ? 8 : 4);
2257
+ try {
2258
+ checkStatus(selectedExports, exports[name](handle, pointer), 'read runtime metadata');
2259
+ const words = new NativeU32Array(exports.memory.buffer, pointer, wide ? 2 : 1);
2260
+ return wide ? readU64(words, 0) : words[0];
2261
+ } finally { free(selectedExports, pointer); }
2262
+ };
2263
+ const operate = (name, action, cleanBuffers = true) => mutate(name, () => { active(cleanBuffers); return action(); });
2264
+ const readOperation = (name, action) => {
2265
+ if (runtimeReadScope !== undefined && activeOperation === runtimeReadScope) {
2266
+ active(true);
2267
+ return action();
2268
+ }
2269
+ return operate(name, action);
2270
+ };
2271
+ const controller = intrinsicFreeze({
2272
+ get checkpointCapacity() { return cell.capacity; },
2273
+ get detached() { return cell.state === 'detached'; },
2274
+ captureCheckpoint() {
2275
+ return operate('capture runtime checkpoint', () => publishCheckpoint(8, record => {
2276
+ checkStatus(selectedExports, exports.rundot_kinetix_world_checkpoint_capture_token(
2277
+ handle, cell.token, record.pointer, record.pointer + 4), 'capture runtime checkpoint');
2278
+ const words = new NativeU32Array(exports.memory.buffer, record.pointer, 2);
2279
+ record.slotIndex = words[0]; record.generation = words[1];
2280
+ }, cell.token, cell));
2281
+ },
2282
+ importCheckpoint(input) {
2283
+ return operate('import runtime checkpoint', () => {
2284
+ if (!(input instanceof NativeU8Array)) fail('SNAPSHOT_INVALID');
2285
+ const byteLength = intrinsicTypedByteLength(input);
2286
+ if (byteLength === 0) fail('SNAPSHOT_INVALID');
2287
+ const outputOffset = Math.ceil(byteLength / 4) * 4;
2288
+ return publishCheckpoint(outputOffset + 8, record => {
2289
+ intrinsicU8Set(new NativeU8Array(exports.memory.buffer, record.pointer, byteLength), input);
2290
+ checkStatus(selectedExports, exports.rundot_kinetix_world_checkpoint_import_token(
2291
+ handle, cell.token, record.pointer, byteLength,
2292
+ record.pointer + outputOffset, record.pointer + outputOffset + 4), 'import runtime checkpoint');
2293
+ const words = new NativeU32Array(exports.memory.buffer, record.pointer + outputOffset, 2);
2294
+ record.slotIndex = words[0]; record.generation = words[1];
2295
+ }, cell.token, cell);
2296
+ });
2297
+ },
2298
+ restoreCheckpoint(checkpoint) {
2299
+ return operate('restore runtime checkpoint', () => checkStatus(selectedExports,
2300
+ checkpointCall(selectedExports, 'rundot_kinetix_world_checkpoint_restore', handle, selected(checkpoint)),
2301
+ 'restore runtime checkpoint'));
2302
+ },
2303
+ releaseCheckpoint(checkpoint) {
2304
+ return operate('release runtime checkpoint', () => {
2305
+ const record = selected(checkpoint);
2306
+ const errors = [];
2307
+ try { cleanRuntimeBuffers(cell); }
2308
+ catch (error) { appendOwn(errors, error); }
2309
+ try {
2310
+ checkStatus(selectedExports,
2311
+ checkpointCall(selectedExports, 'rundot_kinetix_world_checkpoint_release', handle, record),
2312
+ 'release runtime checkpoint');
2313
+ record.generation = 0; record.state = 'released';
2314
+ removeRuntimeCheckpoint(record);
2315
+ intrinsicWeakDelete(checkpoints, checkpoint);
2316
+ } catch (error) { appendOwn(errors, error); }
2317
+ if (errors.length === 1) throw errors[0];
2318
+ if (errors.length !== 0) throw new AggregateError(errors, 'Runtime checkpoint release failed.');
2319
+ }, false);
2320
+ },
2321
+ serializeCheckpoint(checkpoint) {
2322
+ return readOperation('serialize runtime checkpoint', () =>
2323
+ captureCheckpointSnapshot(selectedExports, handle, selected(checkpoint)));
2324
+ },
2325
+ digestCheckpoint(checkpoint) {
2326
+ return readOperation('digest runtime checkpoint', () => {
2327
+ const record = selected(checkpoint);
2328
+ const pointer = allocate(selectedExports, 8);
2329
+ try {
2330
+ checkStatus(selectedExports, checkpointCall(selectedExports,
2331
+ 'rundot_kinetix_world_checkpoint_digest', handle, record, pointer), 'digest runtime checkpoint');
2332
+ return readU64(new NativeU32Array(exports.memory.buffer, pointer, 2), 0);
2333
+ } finally { free(selectedExports, pointer); }
2334
+ });
2335
+ },
2336
+ strongDigestCheckpoint(checkpoint) {
2337
+ return readOperation('strong digest runtime checkpoint', () =>
2338
+ readCheckpointStrongDigest(selectedExports, handle, selected(checkpoint)));
2339
+ },
2340
+ checkpointInfo(checkpoint) {
2341
+ return readOperation('read runtime checkpoint', () =>
2342
+ readCheckpointViewInfo(selectedExports, handle, selected(checkpoint)));
2343
+ },
2344
+ checkpointLatest(checkpoint) {
2345
+ return readOperation('read runtime checkpoint output', () =>
2346
+ readCheckpointLatestOutputs(selectedExports, handle, selected(checkpoint)));
2347
+ },
2348
+ writeCheckpointBodyMotionInto(checkpoint, pose, velocity, ids, status) {
2349
+ return readOperation('read runtime checkpoint motion', () =>
2350
+ writeCheckpointBodyMotion(selectedExports, handle, selected(checkpoint), pose, velocity, ids, status));
2351
+ },
2352
+ mutationRevision() {
2353
+ return readOperation('read runtime revision', () => readScalar('rundot_kinetix_world_revision', true));
2354
+ },
2355
+ liveCheckpointCount() {
2356
+ return readOperation('read runtime checkpoint count', () => readScalar('rundot_kinetix_world_checkpoint_live_count', false));
2357
+ },
2358
+ checkpointPreflight(requiredSlots) {
2359
+ return operate('preflight runtime checkpoints', () => {
2360
+ const slots = requireU32(requiredSlots, 'CHECKPOINT_SLOTS');
2361
+ const pointer = allocate(selectedExports, 4);
2362
+ try {
2363
+ checkStatus(selectedExports,
2364
+ exports.rundot_kinetix_world_checkpoint_preflight(handle, slots, pointer),
2365
+ 'preflight runtime checkpoints');
2366
+ if (new NativeU32Array(exports.memory.buffer, pointer, 1)[0] !== 1) fail('CHECKPOINT_CAPACITY');
2367
+ } finally { free(selectedExports, pointer); }
2368
+ });
2369
+ },
2370
+ releaseAllCheckpoints() {
2371
+ if (cell.state === 'detached') return;
2372
+ return operate('release runtime checkpoints', () => {
2373
+ const errors = [];
2374
+ drainRuntimeCaptures(cell, errors);
2375
+ if (errors.length !== 0) throw new AggregateError(errors, 'Runtime checkpoint cleanup failed.');
2376
+ }, false);
2377
+ },
2378
+ detach() {
2379
+ if (cell.state === 'detached') return;
2380
+ if (cell.state === 'failed') return mutate('retry runtime detach', () => cleanUnpublishedAttachment(cell));
2381
+ return operate('detach runtime', () => {
2382
+ const errors = [];
2383
+ try { cleanRuntimeBuffers(cell); }
2384
+ catch (error) { appendOwn(errors, error); }
2385
+ try { cleanPendingCheckpoints(); }
2386
+ catch (error) { appendOwn(errors, error); }
2387
+ try {
2388
+ checkStatus(selectedExports, exports.rundot_kinetix_world_detach(handle, cell.token), 'detach runtime');
2389
+ cell.token = 0;
2390
+ cell.state = cell.buffers === undefined ? 'detached' : 'failed';
2391
+ if (cell.state === 'detached') runtimeAttachment = undefined;
2392
+ } catch (error) { appendOwn(errors, error); }
2393
+ if (errors.length === 1) throw errors[0];
2394
+ if (errors.length !== 0) throw new AggregateError(errors, 'Runtime detach failed.');
2395
+ }, false);
2396
+ },
2397
+ close() {
2398
+ if (cell.state === 'detached') return;
2399
+ return mutate('close runtime', () => {
2400
+ cell.state = 'failed';
2401
+ cleanUnpublishedAttachment(cell);
2402
+ });
2403
+ },
2404
+ readOnly(action) {
2405
+ return readOperation('read-only runtime callback', () => {
2406
+ if (typeof action !== 'function') fail('RUNTIME_CALLBACK_INVALID');
2407
+ const previousReadScope = runtimeReadScope;
2408
+ runtimeReadScope = activeOperation;
2409
+ try { return action(); }
2410
+ finally { runtimeReadScope = previousReadScope; }
2411
+ });
2412
+ },
2413
+ });
2414
+ cell.capacity = readScalar('rundot_kinetix_world_checkpoint_capacity', false);
2415
+ cell.pointer = allocate(exports, 4);
2416
+ checkStatus(selectedExports, exports.rundot_kinetix_world_attach(handle,
2417
+ Number(expectedDigest & 0xffffffffn), Number(expectedDigest >> 32n), cell.pointer), 'attach runtime');
2418
+ cell.token = new NativeU32Array(exports.memory.buffer, cell.pointer, 1)[0];
2419
+ free(exports, cell.pointer); cell.pointer = 0;
2420
+ cell.state = 'active';
2421
+ return controller;
2422
+ } catch (error) {
2423
+ cell.state = 'failed';
2424
+ try { cleanUnpublishedAttachment(cell); }
2425
+ catch (cleanup) { throw new AggregateError([error, cleanup], 'Runtime acquisition cleanup failed.', { cause: error }); }
2426
+ throw error;
2427
+ }
2428
+ });
1008
2429
  }
1009
2430
  const api = {
1010
2431
  read() {
1011
- ensureActive(disposed);
2432
+ ensureReadable();
1012
2433
  return readState(exports, handle);
1013
2434
  },
1014
2435
  topology() {
1015
- ensureActive(disposed);
2436
+ ensureReadable();
1016
2437
  return readTopology(exports, handle);
1017
2438
  },
2439
+ writeBodyTransformsInto(outTransforms, outStatusMask) {
2440
+ ensureReadable();
2441
+ if (!(outTransforms instanceof Float32Array)) {
2442
+ fail('TRANSFORMS_BUFFER_INVALID');
2443
+ }
2444
+ if (outStatusMask !== undefined && !(outStatusMask instanceof Uint8Array)) {
2445
+ fail('STATUS_MASK_BUFFER_INVALID');
2446
+ }
2447
+
2448
+ if (cachedMemoryBuffer !== exports.memory.buffer) {
2449
+ cachedMemoryBuffer = exports.memory.buffer;
2450
+ cachedMemoryF64 = new Float64Array(cachedMemoryBuffer);
2451
+ cachedMemoryU32 = new Uint32Array(cachedMemoryBuffer);
2452
+ }
2453
+
2454
+ checkStatus(
2455
+ exports,
2456
+ exports.rundot_kinetix_world_topology_info(handle, bodyScratch, TOPOLOGY_INFO_STRIDE),
2457
+ 'read topology',
2458
+ );
2459
+ const count = cachedMemoryU32[(bodyScratch >> 2) + 8];
2460
+ const jointCount = cachedMemoryU32[(bodyScratch >> 2) + 9];
2461
+ const fluidCount = cachedMemoryU32[(bodyScratch >> 2) + 10];
2462
+
2463
+ if (outTransforms.length < count * 7) {
2464
+ fail("BUFFER_OVERFLOW: outTransforms length " + outTransforms.length + " is less than required " + (count * 7));
2465
+ }
2466
+ if (outStatusMask !== undefined && outStatusMask.length < count) {
2467
+ fail("BUFFER_OVERFLOW: outStatusMask length " + outStatusMask.length + " is less than required " + count);
2468
+ }
2469
+
2470
+ if (count === 0) return 0;
2471
+
2472
+ if (count > topoScratchCapacity) {
2473
+ const capacity = Math.max(count * 2, topoScratchCapacity * 2);
2474
+ topoScratch = growScratch('topology', capacity * 8);
2475
+ topoScratchCapacity = capacity;
2476
+ }
2477
+ if (jointCount > jointScratchCapacity) {
2478
+ const capacity = Math.max(jointCount * 2, jointScratchCapacity * 2);
2479
+ jointScratch = growScratch('joint', capacity * 6 * 4);
2480
+ jointScratchCapacity = capacity;
2481
+ }
2482
+ if (fluidCount > fluidScratchCapacity) {
2483
+ const capacity = Math.max(fluidCount * 2, fluidScratchCapacity * 2);
2484
+ fluidScratch = growScratch('fluid', capacity * 2 * 4);
2485
+ fluidScratchCapacity = capacity;
2486
+ }
2487
+
2488
+ if (cachedMemoryBuffer !== exports.memory.buffer) {
2489
+ cachedMemoryBuffer = exports.memory.buffer;
2490
+ cachedMemoryF64 = new Float64Array(cachedMemoryBuffer);
2491
+ cachedMemoryU32 = new Uint32Array(cachedMemoryBuffer);
2492
+ }
2493
+
2494
+ const bodyValues = count * 2;
2495
+ const jointValues = jointCount * 6;
2496
+ const fluidValues = fluidCount * 2;
2497
+ checkStatus(
2498
+ exports,
2499
+ exports.rundot_kinetix_world_copy_topology(
2500
+ handle,
2501
+ topoScratch,
2502
+ bodyValues,
2503
+ jointValues > 0 ? jointScratch : 0,
2504
+ jointValues,
2505
+ fluidValues > 0 ? fluidScratch : 0,
2506
+ fluidValues,
2507
+ ),
2508
+ 'copy topology',
2509
+ );
2510
+
2511
+ if (outStatusMask !== undefined) {
2512
+ outStatusMask.fill(0);
2513
+ }
2514
+
2515
+ const topoIndex = topoScratch >> 2;
2516
+ for (let i = 0; i < count; i += 1) {
2517
+ const low = cachedMemoryU32[topoIndex + i * 2];
2518
+ const high = cachedMemoryU32[topoIndex + i * 2 + 1];
2519
+ const status = exports.rundot_kinetix_world_read_body(
2520
+ handle,
2521
+ low,
2522
+ high,
2523
+ bodyScratch,
2524
+ PHYSICS_BODY_STRIDE,
2525
+ );
2526
+ if (status !== 0) {
2527
+ if (outStatusMask !== undefined) {
2528
+ outStatusMask[i] |= (1 << 1);
2529
+ }
2530
+ continue;
2531
+ }
2532
+
2533
+ const base = i * 7;
2534
+ outTransforms[base + 0] = cachedMemoryF64[bodyScratchIndex + 0];
2535
+ outTransforms[base + 1] = cachedMemoryF64[bodyScratchIndex + 1];
2536
+ outTransforms[base + 2] = cachedMemoryF64[bodyScratchIndex + 2];
2537
+ outTransforms[base + 3] = cachedMemoryF64[bodyScratchIndex + 22];
2538
+ outTransforms[base + 4] = cachedMemoryF64[bodyScratchIndex + 23];
2539
+ outTransforms[base + 5] = cachedMemoryF64[bodyScratchIndex + 24];
2540
+ outTransforms[base + 6] = cachedMemoryF64[bodyScratchIndex + 25];
2541
+
2542
+ if (outStatusMask !== undefined) {
2543
+ const motion = cachedMemoryF64[bodyScratchIndex + 9];
2544
+ const isAwake = (motion & 16) === 0;
2545
+ if (isAwake) {
2546
+ outStatusMask[i] |= (1 << 0);
2547
+ }
2548
+ }
2549
+ }
2550
+ return count;
2551
+ },
1018
2552
  info() {
1019
- ensureActive(disposed);
2553
+ ensureReadable();
1020
2554
  return readWorldInfo(exports, handle);
1021
2555
  },
1022
2556
  body(id) {
1023
- ensureActive(disposed);
2557
+ ensureReadable();
1024
2558
  requireLogicalId(id, 'BODY_ID');
1025
2559
  checkIdentityExists(exports, handle, 'body', id);
1026
2560
  return makeLiveHandle(owner, 'body', id, topologyInfo(exports, handle).restoreEpoch);
1027
2561
  },
1028
2562
  joint(id) {
1029
- ensureActive(disposed);
2563
+ ensureReadable();
1030
2564
  requireLogicalId(id, 'JOINT_ID');
1031
2565
  checkIdentityExists(exports, handle, 'joint', id);
1032
2566
  return makeLiveHandle(owner, 'joint', id, topologyInfo(exports, handle).restoreEpoch);
1033
2567
  },
2568
+ fluid(id) {
2569
+ ensureReadable();
2570
+ requireLogicalId(id, 'FLUID_ID');
2571
+ checkIdentityExists(exports, handle, 'fluid', id);
2572
+ return makeLiveHandle(owner, 'fluid', id,
2573
+ topologyInfo(exports, handle).restoreEpoch);
2574
+ },
2575
+ handleInfo(reference) {
2576
+ if (typeof reference !== 'object' || reference === null) return undefined;
2577
+ const live = liveHandles.get(reference);
2578
+ if (!live || live.owner !== owner) return undefined;
2579
+ return { kind: live.kind, id: live.id, epoch: live.epoch };
2580
+ },
2581
+ validateBody(reference) {
2582
+ ensureReadable();
2583
+ if (typeof reference === 'bigint') {
2584
+ checkIdentityExists(exports, handle, 'body', requireLogicalId(reference, 'BODY_ID'));
2585
+ return;
2586
+ }
2587
+ const [kind] = topologyReference(exports, handle, owner,
2588
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY');
2589
+ if (kind !== 2) fail('BODY_REFERENCE_INVALID: resolve a live body first');
2590
+ },
2591
+ validateJoint(reference) {
2592
+ ensureReadable();
2593
+ if (typeof reference === 'bigint') {
2594
+ checkIdentityExists(exports, handle, 'joint', requireLogicalId(reference, 'JOINT_ID'));
2595
+ return;
2596
+ }
2597
+ const [kind] = topologyReference(exports, handle, owner,
2598
+ topologyInfo(exports, handle).restoreEpoch, 'joint', reference, 'JOINT');
2599
+ if (kind !== 4) fail('JOINT_REFERENCE_INVALID: resolve a live joint first');
2600
+ },
2601
+ validateFluid(reference) {
2602
+ ensureReadable();
2603
+ if (typeof reference === 'bigint') {
2604
+ checkIdentityExists(exports, handle, 'fluid', requireLogicalId(reference, 'FLUID_ID'));
2605
+ return;
2606
+ }
2607
+ const [kind] = topologyReference(exports, handle, owner,
2608
+ topologyInfo(exports, handle).restoreEpoch, 'fluid', reference, 'FLUID');
2609
+ if (kind !== 6) fail('FLUID_REFERENCE_INVALID: resolve a live fluid first');
2610
+ },
1034
2611
  readBody(reference) {
1035
- ensureActive(disposed);
2612
+ ensureReadable();
1036
2613
  const id = typeof reference === 'bigint'
1037
2614
  ? reference
1038
2615
  : topologyReference(exports, handle, owner,
@@ -1041,7 +2618,7 @@ export function createNativePhysicsWorld(options) {
1041
2618
  return readWorldBody(exports, handle, logicalId);
1042
2619
  },
1043
2620
  readJoint(reference) {
1044
- ensureActive(disposed);
2621
+ ensureReadable();
1045
2622
  const id = typeof reference === 'bigint'
1046
2623
  ? reference
1047
2624
  : topologyReference(exports, handle, owner,
@@ -1049,6 +2626,25 @@ export function createNativePhysicsWorld(options) {
1049
2626
  const logicalId = Array.isArray(id) ? id[1] : id;
1050
2627
  return readWorldJoint(exports, handle, logicalId);
1051
2628
  },
2629
+ readFluid(reference) {
2630
+ ensureReadable();
2631
+ const id = typeof reference === 'bigint'
2632
+ ? reference
2633
+ : topologyReference(exports, handle, owner,
2634
+ topologyInfo(exports, handle).restoreEpoch, 'fluid', reference,
2635
+ 'FLUID');
2636
+ const logicalId = Array.isArray(id) ? id[1] : id;
2637
+ return readWorldFluid(exports, handle, logicalId);
2638
+ },
2639
+ readGeometry(reference) {
2640
+ ensureReadable();
2641
+ const id = typeof reference === 'bigint'
2642
+ ? reference
2643
+ : topologyReference(exports, handle, owner,
2644
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY');
2645
+ if (Array.isArray(id) && id[0] !== 2) fail('BODY_REFERENCE_INVALID: resolve a live body first');
2646
+ return readWorldGeometry(exports, handle, Array.isArray(id) ? id[1] : id);
2647
+ },
1052
2648
  applyBatch(commands) {
1053
2649
  return mutate('apply batch', () => applyTopologyBatch(exports, handle, owner, commands));
1054
2650
  },
@@ -1067,28 +2663,179 @@ export function createNativePhysicsWorld(options) {
1067
2663
  return applyWorldImpulse(exports, handle, id, impulse, point);
1068
2664
  });
1069
2665
  },
2666
+ setBodyForce(reference, force, torque = { x: 0, y: 0, z: 0 }) {
2667
+ return mutate('set body force', () => {
2668
+ const id = typeof reference === 'bigint'
2669
+ ? requireLogicalId(reference, 'BODY_ID')
2670
+ : topologyReference(exports, handle, owner,
2671
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2672
+ return setWorldBodyForce(exports, handle, id, force, torque);
2673
+ });
2674
+ },
2675
+ applyForce(reference, force, torque = { x: 0, y: 0, z: 0 }) {
2676
+ return mutate('apply force', () => {
2677
+ const id = typeof reference === 'bigint'
2678
+ ? requireLogicalId(reference, 'BODY_ID')
2679
+ : topologyReference(exports, handle, owner,
2680
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2681
+ return applyWorldForce(exports, handle, id, force, torque);
2682
+ });
2683
+ },
2684
+ applyForceAtPoint(reference, force, point) {
2685
+ return mutate('apply force at point', () => {
2686
+ const id = typeof reference === 'bigint'
2687
+ ? requireLogicalId(reference, 'BODY_ID')
2688
+ : topologyReference(exports, handle, owner,
2689
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2690
+ return applyWorldForceAtPoint(exports, handle, id, force, point);
2691
+ });
2692
+ },
2693
+ clearBodyForce(reference) {
2694
+ return mutate('clear body force', () => {
2695
+ const id = typeof reference === 'bigint'
2696
+ ? requireLogicalId(reference, 'BODY_ID')
2697
+ : topologyReference(exports, handle, owner,
2698
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2699
+ return clearWorldBodyForce(exports, handle, id);
2700
+ });
2701
+ },
2702
+ setBodySurfaceVelocity(reference, velocity) {
2703
+ return mutate('set body surface velocity', () => {
2704
+ const id = typeof reference === 'bigint'
2705
+ ? requireLogicalId(reference, 'BODY_ID')
2706
+ : topologyReference(exports, handle, owner,
2707
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2708
+ return setWorldBodySurfaceVelocity(exports, handle, id, velocity);
2709
+ });
2710
+ },
2711
+ setBodyLinearVelocity(reference, velocity) {
2712
+ return mutate('set body linear velocity', () => {
2713
+ const id = typeof reference === 'bigint'
2714
+ ? requireLogicalId(reference, 'BODY_ID')
2715
+ : topologyReference(exports, handle, owner,
2716
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2717
+ return setWorldBodyLinearVelocity(exports, handle, id, velocity);
2718
+ });
2719
+ },
2720
+ setBodyAngularVelocity(reference, velocity) {
2721
+ return mutate('set body angular velocity', () => {
2722
+ const id = typeof reference === 'bigint'
2723
+ ? requireLogicalId(reference, 'BODY_ID')
2724
+ : topologyReference(exports, handle, owner,
2725
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2726
+ return setWorldBodyAngularVelocity(exports, handle, id, velocity);
2727
+ });
2728
+ },
2729
+ setBodyTransform(reference, position, orientation) {
2730
+ return mutate('set body transform', () => {
2731
+ const id = typeof reference === 'bigint'
2732
+ ? requireLogicalId(reference, 'BODY_ID')
2733
+ : topologyReference(exports, handle, owner,
2734
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2735
+ return setWorldBodyTransform(exports, handle, id, position, orientation);
2736
+ });
2737
+ },
2738
+ setBodyLinearDamping(reference, damping) {
2739
+ return mutate('set body linear damping', () => {
2740
+ const id = typeof reference === 'bigint'
2741
+ ? requireLogicalId(reference, 'BODY_ID')
2742
+ : topologyReference(exports, handle, owner,
2743
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2744
+ return setWorldBodyLinearDamping(exports, handle, id, damping);
2745
+ });
2746
+ },
2747
+ wakeBody(reference) {
2748
+ return mutate('wake body', () => {
2749
+ const id = typeof reference === 'bigint'
2750
+ ? requireLogicalId(reference, 'BODY_ID')
2751
+ : topologyReference(exports, handle, owner,
2752
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1];
2753
+ return wakeWorldBody(exports, handle, id);
2754
+ });
2755
+ },
2756
+ writeBodyMotionInto(pose, velocity, ids, status) {
2757
+ ensureReadable();
2758
+ return writeWorldBodyMotion(exports, handle, pose, velocity, ids, status);
2759
+ },
2760
+ applySupport(springs, forces = [], wakeTarget = 0n) {
2761
+ return mutate('apply support', () => {
2762
+ const resolveId = (reference, label) => (typeof reference === 'bigint'
2763
+ ? requireLogicalId(reference, label)
2764
+ : topologyReference(exports, handle, owner,
2765
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY')[1]);
2766
+ const springInputs = springs.map((spring) => ({
2767
+ ...spring,
2768
+ body: resolveId(spring.body, 'BODY_ID'),
2769
+ support: resolveId(spring.support, 'SUPPORT_ID'),
2770
+ }));
2771
+ const forceInputs = forces.map((force) => ({
2772
+ ...force,
2773
+ body: resolveId(force.body, 'BODY_ID'),
2774
+ support: resolveId(force.support, 'SUPPORT_ID'),
2775
+ }));
2776
+ const wake = wakeTarget == null || wakeTarget === 0n
2777
+ ? 0n
2778
+ : resolveId(wakeTarget, 'WAKE_BODY_ID');
2779
+ return applyWorldSupport(exports, handle, springInputs, forceInputs, wake);
2780
+ });
2781
+ },
2782
+ readBodyMobility(reference) {
2783
+ ensureReadable();
2784
+ const id = typeof reference === 'bigint'
2785
+ ? reference
2786
+ : topologyReference(exports, handle, owner,
2787
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY');
2788
+ const logicalId = Array.isArray(id) ? id[1] : id;
2789
+ return readWorldBodyMobility(exports, handle, logicalId);
2790
+ },
2791
+ readEffectiveSurfaceVelocity(reference) {
2792
+ ensureReadable();
2793
+ const id = typeof reference === 'bigint'
2794
+ ? reference
2795
+ : topologyReference(exports, handle, owner,
2796
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY');
2797
+ const logicalId = Array.isArray(id) ? id[1] : id;
2798
+ return readWorldSurfaceVelocity(exports, handle, logicalId);
2799
+ },
2800
+ readPendingSupportImpulse(reference, dt, substeps) {
2801
+ ensureReadable();
2802
+ const id = typeof reference === 'bigint'
2803
+ ? reference
2804
+ : topologyReference(exports, handle, owner,
2805
+ topologyInfo(exports, handle).restoreEpoch, 'body', reference, 'BODY');
2806
+ const logicalId = Array.isArray(id) ? id[1] : id;
2807
+ return readWorldPendingSupportImpulse(exports, handle, logicalId, dt, substeps);
2808
+ },
1070
2809
  latestContacts() {
1071
- ensureActive(disposed);
2810
+ ensureReadable();
1072
2811
  return readWorldContactOutput(exports, handle);
1073
2812
  },
2813
+ latestJointOutputs() {
2814
+ ensureReadable();
2815
+ return readWorldJointOutput(exports, handle);
2816
+ },
2817
+ latestFluidInteractions() {
2818
+ ensureReadable();
2819
+ return readWorldFluidInteractions(exports, handle);
2820
+ },
1074
2821
  raycast(query) {
1075
- ensureActive(disposed);
2822
+ ensureReadable();
1076
2823
  return runWorldQuery(exports, handle, 1, query);
1077
2824
  },
1078
2825
  overlap(query) {
1079
- ensureActive(disposed);
2826
+ ensureReadable();
1080
2827
  return runWorldQuery(exports, handle, 2, query);
1081
2828
  },
1082
2829
  shapeCast(query) {
1083
- ensureActive(disposed);
2830
+ ensureReadable();
1084
2831
  return runWorldQuery(exports, handle, 3, query);
1085
2832
  },
1086
2833
  closestPoint(query) {
1087
- ensureActive(disposed);
2834
+ ensureReadable();
1088
2835
  return runWorldQuery(exports, handle, 4, query);
1089
2836
  },
1090
2837
  digest() {
1091
- ensureActive(disposed);
2838
+ ensureReadable();
1092
2839
  const pointer = allocate(exports, 8);
1093
2840
  try {
1094
2841
  checkStatus(exports, exports.rundot_kinetix_world_digest(handle, pointer), 'digest');
@@ -1098,56 +2845,99 @@ export function createNativePhysicsWorld(options) {
1098
2845
  }
1099
2846
  },
1100
2847
  capture() {
1101
- ensureActive(disposed);
2848
+ ensureReadable();
1102
2849
  return captureSnapshot(exports, handle);
1103
2850
  },
1104
2851
  captureCheckpoint() {
1105
- return mutate('capture checkpoint', () => {
1106
- const pointer = allocate(exports, 4);
1107
- try {
1108
- checkStatus(
1109
- exports,
1110
- exports.rundot_kinetix_world_checkpoint_capture(handle, pointer),
1111
- 'capture checkpoint',
1112
- );
1113
- const checkpointHandle = new Uint32Array(exports.memory.buffer, pointer, 1)[0];
1114
- const checkpoint = Object.freeze({});
1115
- checkpoints.set(checkpoint, checkpointHandle);
1116
- return checkpoint;
1117
- } finally {
1118
- free(exports, pointer);
1119
- }
1120
- });
2852
+ return mutate('capture checkpoint', () => publishCheckpoint(4, record => {
2853
+ checkStatus(record.cleanupExports, exports.rundot_kinetix_world_checkpoint_capture(handle, record.pointer),
2854
+ 'capture checkpoint');
2855
+ record.id = new NativeU32Array(exports.memory.buffer, record.pointer, 1)[0];
2856
+ }));
1121
2857
  },
1122
2858
  restoreCheckpoint(checkpoint) {
1123
2859
  return mutate('restore checkpoint', () => checkStatus(
1124
- exports,
2860
+ legacyExports,
1125
2861
  exports.rundot_kinetix_world_checkpoint_restore(handle, checkpointHandle(checkpoint)),
1126
2862
  'restore checkpoint',
1127
2863
  ));
1128
2864
  },
1129
2865
  serializeCheckpoint(checkpoint) {
1130
- ensureActive(disposed);
1131
- return captureCheckpointSnapshot(exports, handle, checkpointHandle(checkpoint));
2866
+ ensureReadable();
2867
+ return captureCheckpointSnapshot(legacyExports, handle, checkpointHandle(checkpoint));
2868
+ },
2869
+ checkpointLatest(checkpoint) {
2870
+ ensureReadable();
2871
+ return readCheckpointLatestOutputs(legacyExports, handle, checkpointHandle(checkpoint));
2872
+ },
2873
+ checkpointInfo(checkpoint) {
2874
+ ensureReadable();
2875
+ return readCheckpointViewInfo(legacyExports, handle, checkpointHandle(checkpoint));
2876
+ },
2877
+ writeCheckpointBodyMotionInto(checkpoint, pose, velocity, ids, status) {
2878
+ ensureReadable();
2879
+ return writeCheckpointBodyMotion(legacyExports, handle, checkpointHandle(checkpoint), pose, velocity, ids, status);
2880
+ },
2881
+ digestCheckpoint(checkpoint) {
2882
+ ensureReadable();
2883
+ const selected = checkpointHandle(checkpoint);
2884
+ if (typeof exports.rundot_kinetix_world_checkpoint_digest !== 'function') {
2885
+ fail('ABI_MISMATCH: saved checkpoint digest requires a rebuilt native world artifact');
2886
+ }
2887
+ const pointer = allocate(legacyExports, 8);
2888
+ try {
2889
+ checkStatus(legacyExports,
2890
+ exports.rundot_kinetix_world_checkpoint_digest(handle, selected, pointer),
2891
+ 'digest checkpoint');
2892
+ return new DataView(exports.memory.buffer, pointer, 8).getBigUint64(0, true);
2893
+ } finally { free(legacyExports, pointer); }
2894
+ },
2895
+ strongDigestCheckpoint(checkpoint) {
2896
+ ensureReadable();
2897
+ return readCheckpointStrongDigest(legacyExports, handle, checkpointHandle(checkpoint));
2898
+ },
2899
+ importCheckpoint(input) {
2900
+ return mutate('import checkpoint', () => {
2901
+ if (!(input instanceof NativeU8Array)) fail('SNAPSHOT_INVALID');
2902
+ const byteLength = intrinsicTypedByteLength(input);
2903
+ if (byteLength === 0) fail('SNAPSHOT_INVALID');
2904
+ if (typeof exports.rundot_kinetix_world_checkpoint_import !== 'function') {
2905
+ fail('ABI_MISMATCH: detached checkpoint import requires a rebuilt native world artifact');
2906
+ }
2907
+ const outputOffset = Math.ceil(byteLength / 4) * 4;
2908
+ return publishCheckpoint(outputOffset + 4, record => {
2909
+ intrinsicU8Set(new NativeU8Array(exports.memory.buffer, record.pointer, byteLength), input);
2910
+ checkStatus(record.cleanupExports, exports.rundot_kinetix_world_checkpoint_import(
2911
+ handle, record.pointer, byteLength, record.pointer + outputOffset), 'import checkpoint');
2912
+ record.id = new NativeU32Array(exports.memory.buffer, record.pointer + outputOffset, 1)[0];
2913
+ });
2914
+ });
1132
2915
  },
1133
2916
  releaseCheckpoint(checkpoint) {
1134
2917
  return mutate('release checkpoint', () => {
1135
2918
  checkStatus(
1136
- exports,
2919
+ legacyExports,
1137
2920
  exports.rundot_kinetix_world_checkpoint_release(handle, checkpointHandle(checkpoint)),
1138
2921
  'release checkpoint',
1139
2922
  );
1140
- checkpoints.delete(checkpoint);
2923
+ const record = intrinsicWeakGet(checkpoints, checkpoint);
2924
+ record.id = 0;
2925
+ record.state = 'released';
2926
+ intrinsicWeakDelete(checkpoints, checkpoint);
1141
2927
  });
1142
2928
  },
1143
2929
  restore(bytes) {
1144
2930
  return mutate('restore', () => restoreSnapshot(exports, handle, bytes));
1145
2931
  },
1146
2932
  dispose() {
1147
- if (disposed) return;
2933
+ if (disposed) return releaseDisposedScratch();
1148
2934
  return mutate('dispose', () => {
2935
+ if (runtimeAttachment?.state === 'failed') cleanUnpublishedAttachment(runtimeAttachment);
1149
2936
  checkStatus(exports, exports.rundot_kinetix_world_destroy(handle), 'dispose');
1150
2937
  disposed = true;
2938
+ let record = pendingCheckpointCleanup;
2939
+ while (record !== undefined) { record.id = 0; record.generation = 0; record = record.next; }
2940
+ releaseDisposedScratch();
1151
2941
  });
1152
2942
  },
1153
2943
  get disposed() {
@@ -1158,9 +2948,14 @@ export function createNativePhysicsWorld(options) {
1158
2948
  try {
1159
2949
  api.replace(config.state);
1160
2950
  } catch (error) {
1161
- api.dispose();
2951
+ try { api.dispose(); }
2952
+ catch (cleanup) { throw new AggregateError([error, cleanup], 'Initial state cleanup failed.', { cause: error }); }
1162
2953
  throw error;
1163
2954
  }
1164
2955
  }
2956
+ intrinsicDefine(api, runtimeAttachmentKey, { value(expectedDigest) {
2957
+ if (this !== api) fail('WORLD_INVALID: use the original native physics world');
2958
+ return acquireRuntimeController(expectedDigest);
2959
+ } });
1165
2960
  return Object.freeze(api);
1166
2961
  }