@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,4 +1,6 @@
1
1
  #include "world.hpp"
2
+ #include "contour.hpp"
3
+ #include "clock_primitives.hpp"
2
4
 
3
5
  #include <algorithm>
4
6
  #include <array>
@@ -11,20 +13,18 @@
11
13
  #include <new>
12
14
  #include <utility>
13
15
 
14
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
15
- extern "C" void* rundot_physics2d_test_allocate(std::size_t size);
16
- extern "C" void rundot_physics2d_test_free(void* value);
17
- #endif
18
-
19
16
  namespace rundot::kinetix::physics2d {
20
17
  namespace {
21
18
 
22
- constexpr std::size_t kBodySnapshotBytes = 280;
19
+ using memory_private::LedgerClass;
20
+
21
+ constexpr std::size_t kBodySnapshotBytes = 296;
23
22
  constexpr std::size_t kJointSnapshotBytes = 288;
24
23
  constexpr std::size_t kFluidSnapshotBytes = 112;
25
24
  constexpr std::size_t kTelemetrySnapshotBytes = 80;
26
25
  constexpr std::size_t kBreakSnapshotBytes = 16;
27
26
  constexpr std::size_t kGearReactionSnapshotBytes = 64;
27
+ constexpr std::size_t kContactEventSnapshotBytes = 32;
28
28
 
29
29
  static_assert(kBodySnapshotBytes == sizeof(Body) + sizeof(PolygonGeometry));
30
30
  static_assert(kJointSnapshotBytes == sizeof(JointRecord2D) + sizeof(JointState2D));
@@ -32,21 +32,23 @@ static_assert(kFluidSnapshotBytes == sizeof(FluidRegion2D));
32
32
  static_assert(kTelemetrySnapshotBytes == sizeof(JointTelemetry2D));
33
33
  static_assert(kBreakSnapshotBytes == sizeof(JointBreakEvent2D));
34
34
  static_assert(kGearReactionSnapshotBytes == sizeof(GearReactionEntry2D));
35
+ static_assert(kContactEventSnapshotBytes == sizeof(ContactEvent2D));
35
36
  static_assert(kOwnedWorld2DMaxSnapshotBytes == kOwnedWorld2DSnapshotHeaderBytes
36
37
  + kBodySnapshotBytes * kMaxBodies + kJointSnapshotBytes * kMaxJoints
37
38
  + kFluidSnapshotBytes * kMaxFluidRegions
38
39
  + kTelemetrySnapshotBytes * kMaxJoints
39
40
  + kBreakSnapshotBytes * kMaxJointEvents
40
- + kGearReactionSnapshotBytes * kMaxGearReactionEntries);
41
+ + kGearReactionSnapshotBytes * kMaxGearReactionEntries
42
+ + 2 * kContactEventSnapshotBytes * kMaxCandidatePairs
43
+ + 8 + sizeof(ContourEdge2D) * kMaxWorldContourEdges);
41
44
 
42
45
  std::atomic<std::uint64_t> nextOwnerToken{1};
43
- std::atomic<std::uint32_t> nextCheckpointToken{1};
44
46
 
45
- constexpr std::uint32_t kCheckpointCapacity = 64;
46
47
  constexpr std::uint64_t kDigestOffset = 1469598103934665603ull;
47
48
  constexpr std::uint64_t kDigestPrime = 1099511628211ull;
48
49
 
49
50
  void digestBytes(std::uint64_t& digest, const void* source, std::size_t byteCount) {
51
+ if (byteCount == 0) return;
50
52
  const auto* bytes = static_cast<const std::uint8_t*>(source);
51
53
  for (std::size_t index = 0; index < byteCount; index += 1) {
52
54
  digest = (digest ^ bytes[index]) * kDigestPrime;
@@ -58,29 +60,6 @@ void digestValue(std::uint64_t& digest, const T& value) {
58
60
  digestBytes(digest, &value, sizeof(value));
59
61
  }
60
62
 
61
- struct RetainedCheckpoint2D {
62
- std::uint8_t* bytes = nullptr;
63
- std::size_t byteCapacity = 0;
64
- std::size_t byteCount = 0;
65
- std::uint64_t ownerToken = 0;
66
- std::uint64_t frame = 0;
67
- std::uint32_t nextBodyId = 1;
68
- std::uint32_t nextJointId = 1;
69
- std::uint32_t nextFluidId = 1;
70
- std::uint32_t bodyCount = 0;
71
- std::uint32_t jointCount = 0;
72
- std::uint32_t fluidCount = 0;
73
- std::uint32_t telemetryCount = 0;
74
- std::uint32_t breakEventCount = 0;
75
- std::uint32_t gearReactionCount = 0;
76
- StepOptions latestStepOptions{};
77
- Gravity2D currentGravity{};
78
- std::uint32_t token = 0;
79
- bool live = false;
80
- };
81
-
82
- using CheckpointRing2D = std::array<RetainedCheckpoint2D, kCheckpointCapacity>;
83
-
84
63
  WorldResult2D result(WorldStatus2D status, std::int32_t nativeStatus = kStepOk) {
85
64
  return {status, nativeStatus};
86
65
  }
@@ -130,40 +109,59 @@ bool validConfig(const WorldConfig2D& config) {
130
109
  return config.bodyCapacity <= kMaxBodies
131
110
  && config.jointCapacity <= kMaxJoints
132
111
  && config.fluidCapacity <= kMaxFluidRegions
112
+ && config.contactCapacity <= maximumContactPairs2D(config.bodyCapacity)
113
+ && config.contourEdgeCapacity <= kMaxWorldContourEdges
114
+ && config.checkpointCapacity >= kMinCheckpointCapacity
115
+ && config.checkpointCapacity <= kMaxCheckpointCapacity
133
116
  && config.physicsProfile == kOwnedWorld2DPhysicsProfile
134
117
  && validTiming(config.fixedTiming)
135
118
  && validGravity(config.initialGravity);
136
119
  }
137
120
 
138
121
  template <typename T>
139
- T* allocatePod(std::size_t count) {
140
- if (count == 0) return nullptr;
141
- if (count > std::numeric_limits<std::size_t>::max() / sizeof(T)) return nullptr;
142
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
143
- T* value = static_cast<T*>(rundot_physics2d_test_allocate(count * sizeof(T)));
144
- if (value != nullptr) {
145
- std::fill_n(reinterpret_cast<unsigned char*>(value), count * sizeof(T), 0);
146
- }
147
- return value;
148
- #else
149
- return static_cast<T*>(std::calloc(count, sizeof(T)));
150
- #endif
122
+ T* allocatePod(LedgerClass category, std::size_t count) {
123
+ return memory_private::allocateArray<T>(category, count, true);
151
124
  }
152
125
 
153
126
  void freePod(void* value) {
154
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
155
- rundot_physics2d_test_free(value);
156
- #else
157
- std::free(value);
158
- #endif
127
+ memory_private::deallocate(value);
128
+ }
129
+
130
+ void discardCheckpointCandidate(
131
+ std::uint8_t* replacement,
132
+ bool slotClaimed) noexcept {
133
+ if (replacement != nullptr) freePod(replacement);
134
+ if (slotClaimed) InstanceCheckpointLedger2D::instance().releaseSlot();
135
+ }
136
+
137
+ void freeInstalledPayload(RetainedCheckpointSlot2D& slot) noexcept {
138
+ if (slot.bytes == nullptr) {
139
+ slot.byteCapacity = 0;
140
+ slot.byteCount = 0;
141
+ return;
142
+ }
143
+ std::uint8_t* payload = slot.bytes;
144
+ slot.bytes = nullptr;
145
+ slot.byteCapacity = 0;
146
+ slot.byteCount = 0;
147
+ freePod(payload);
148
+ }
149
+
150
+ void clearPublishedCredential(RetainedCheckpointSlot2D& slot) noexcept {
151
+ slot.resetFields();
152
+ slot.token = 0;
153
+ slot.generation = 0;
154
+ slot.credentialKind = CheckpointCredentialKind2D::None;
155
+ slot.live = false;
159
156
  }
160
157
 
161
158
  bool rangeIsValid(const void* pointer, std::size_t bytes, std::size_t alignment) {
162
159
  if (bytes == 0) return true;
163
- if (pointer == nullptr) return false;
160
+ if (pointer == nullptr || alignment == 0) return false;
164
161
  const std::uintptr_t address = reinterpret_cast<std::uintptr_t>(pointer);
165
- return address % alignment == 0
166
- && address <= std::numeric_limits<std::uintptr_t>::max() - bytes;
162
+ if (address % alignment != 0) return false;
163
+ if (address > std::numeric_limits<std::uintptr_t>::max() - bytes) return false;
164
+ return wasmHeapContains(pointer, bytes);
167
165
  }
168
166
 
169
167
  bool rangesOverlap(
@@ -472,6 +470,7 @@ class Reader {
472
470
  }
473
471
 
474
472
  std::size_t remaining() const { return size_ - position_; }
473
+ std::size_t position() const { return position_; }
475
474
 
476
475
  private:
477
476
  const std::uint8_t* bytes_;
@@ -715,6 +714,8 @@ bool writeBodyAndGeometry(Writer& writer, const Body& body, const PolygonGeometr
715
714
  body.halfX, body.halfY, body.radius, body.friction, body.restitution,
716
715
  };
717
716
  for (double value : bodyValues) if (!writer.f64(value)) return false;
717
+ if (!writer.u32(body.layer) || !writer.u32(body.mask)
718
+ || !writer.u32(body.filterFlags) || !writer.u32(body.ccd)) return false;
718
719
  if (!writer.u32(geometry.vertexCount) || !writer.u32(geometry.reserved)) return false;
719
720
  for (const Vec2& vertex : geometry.vertices) {
720
721
  if (!writer.f64(vertex.x) || !writer.f64(vertex.y)) return false;
@@ -735,6 +736,8 @@ bool readBodyAndGeometry(Reader& reader, Body& body, PolygonGeometry& geometry)
735
736
  &body.halfX, &body.halfY, &body.radius, &body.friction, &body.restitution,
736
737
  };
737
738
  for (double* value : bodyValues) if (!reader.f64(*value)) return false;
739
+ if (!reader.u32(body.layer) || !reader.u32(body.mask)
740
+ || !reader.u32(body.filterFlags) || !reader.u32(body.ccd)) return false;
738
741
  if (!reader.u32(geometry.vertexCount) || !reader.u32(geometry.reserved)) return false;
739
742
  for (Vec2& vertex : geometry.vertices) {
740
743
  if (!reader.f64(vertex.x) || !reader.f64(vertex.y)) return false;
@@ -853,20 +856,123 @@ bool readGearReaction(Reader& reader, GearReactionEntry2D& value) {
853
856
  && reader.f64(value.maximumSubstepTorque);
854
857
  }
855
858
 
859
+ bool validContactPair(const ContactEvent2D& value) {
860
+ return value.bodyA != 0 && value.bodyA < value.bodyB
861
+ && value.type == ContactEventType2D::Active
862
+ && (value.flags & ~kFilterFlagsMask) == 0
863
+ && finite(value.friction) && value.friction >= 0.0
864
+ && finite(value.restitution) && value.restitution >= 0.0;
865
+ }
866
+
867
+ bool writeContourEdge(Writer& writer, const ContourEdge2D& edge) {
868
+ return writer.u32(edge.kind)
869
+ && writer.u32(edge.quadrant)
870
+ && writer.f64(edge.from.x) && writer.f64(edge.from.y)
871
+ && writer.f64(edge.to.x) && writer.f64(edge.to.y)
872
+ && writer.f64(edge.center.x) && writer.f64(edge.center.y)
873
+ && writer.f64(edge.arcRadius)
874
+ && writer.u32(edge.loopIndex)
875
+ && writer.u32(edge.flags);
876
+ }
877
+
878
+ bool readContourEdge(Reader& reader, ContourEdge2D& edge) {
879
+ return reader.u32(edge.kind)
880
+ && reader.u32(edge.quadrant)
881
+ && reader.f64(edge.from.x) && reader.f64(edge.from.y)
882
+ && reader.f64(edge.to.x) && reader.f64(edge.to.y)
883
+ && reader.f64(edge.center.x) && reader.f64(edge.center.y)
884
+ && reader.f64(edge.arcRadius)
885
+ && reader.u32(edge.loopIndex)
886
+ && reader.u32(edge.flags);
887
+ }
888
+
889
+ bool writeContactPair(Writer& writer, const ContactEvent2D& value) {
890
+ return writer.u32(value.bodyA) && writer.u32(value.bodyB)
891
+ && writer.u32(static_cast<std::uint32_t>(value.type))
892
+ && writer.u32(value.flags) && writer.f64(value.friction)
893
+ && writer.f64(value.restitution);
894
+ }
895
+
896
+ bool readContactPair(Reader& reader, ContactEvent2D& value) {
897
+ std::uint32_t type = 0;
898
+ if (!reader.u32(value.bodyA) || !reader.u32(value.bodyB)
899
+ || !reader.u32(type) || !reader.u32(value.flags)
900
+ || !reader.f64(value.friction) || !reader.f64(value.restitution)) return false;
901
+ value.type = static_cast<ContactEventType2D>(type);
902
+ return validContactPair(value);
903
+ }
904
+
905
+ bool contactPairLess(const ContactEvent2D& left, const ContactEvent2D& right) {
906
+ return left.bodyA < right.bodyA
907
+ || (left.bodyA == right.bodyA && left.bodyB < right.bodyB);
908
+ }
909
+
910
+ bool validContactPairs(const ContactEvent2D* values, std::uint32_t count) {
911
+ if (count > 0 && values == nullptr) return false;
912
+ for (std::uint32_t index = 0; index < count; index += 1) {
913
+ if (!validContactPair(values[index])
914
+ || (index > 0 && !contactPairLess(values[index - 1], values[index]))) return false;
915
+ }
916
+ return true;
917
+ }
918
+
919
+ std::uint32_t buildWorldDisabledPairs(
920
+ const JointRecord2D* joints,
921
+ const JointState2D* states,
922
+ std::uint32_t jointCount,
923
+ DisabledContactPair2D* output) {
924
+ std::uint32_t count = 0;
925
+ for (std::uint32_t index = 0; index < jointCount; index += 1) {
926
+ const JointRecord2D& joint = joints[index];
927
+ if (joint.type == JointType2D::Gear || (joint.flags & kJointEnabled) == 0
928
+ || (joint.flags & kJointCollideConnected) != 0
929
+ || (states[index].stateFlags & kJointBroken) != 0) continue;
930
+ PrimitiveJointHeader2D header{};
931
+ std::memcpy(&header, &joint.payload, sizeof(header));
932
+ if (header.endpointA.kind != EndpointKind2D::Body
933
+ || header.endpointB.kind != EndpointKind2D::Body) continue;
934
+ output[count++] = {
935
+ std::min(header.endpointA.bodyId, header.endpointB.bodyId),
936
+ std::max(header.endpointA.bodyId, header.endpointB.bodyId),
937
+ };
938
+ }
939
+ if (count > 1) {
940
+ std::sort(output, output + count,
941
+ [](const DisabledContactPair2D& left, const DisabledContactPair2D& right) {
942
+ return left.firstBodyId < right.firstBodyId
943
+ || (left.firstBodyId == right.firstBodyId
944
+ && left.secondBodyId < right.secondBodyId);
945
+ });
946
+ }
947
+ if (count == 0) return 0;
948
+ const auto last = std::unique(output, output + count,
949
+ [](const DisabledContactPair2D& left, const DisabledContactPair2D& right) {
950
+ return left.firstBodyId == right.firstBodyId
951
+ && left.secondBodyId == right.secondBodyId;
952
+ });
953
+ return static_cast<std::uint32_t>(last - output);
954
+ }
955
+
856
956
  std::size_t snapshotSize(
857
957
  std::uint32_t bodyCount,
858
958
  std::uint32_t jointCount,
859
959
  std::uint32_t fluidCount,
860
960
  std::uint32_t telemetryCount,
861
961
  std::uint32_t breakCount,
862
- std::uint32_t gearReactionCount) {
962
+ std::uint32_t gearReactionCount,
963
+ std::uint32_t activePairCount,
964
+ std::uint32_t priorPairCount,
965
+ std::uint32_t contourEdgeCount = 0) {
863
966
  return kOwnedWorld2DSnapshotHeaderBytes
864
967
  + static_cast<std::size_t>(bodyCount) * kBodySnapshotBytes
865
968
  + static_cast<std::size_t>(jointCount) * kJointSnapshotBytes
866
969
  + static_cast<std::size_t>(fluidCount) * kFluidSnapshotBytes
867
970
  + static_cast<std::size_t>(telemetryCount) * kTelemetrySnapshotBytes
868
971
  + static_cast<std::size_t>(breakCount) * kBreakSnapshotBytes
869
- + static_cast<std::size_t>(gearReactionCount) * kGearReactionSnapshotBytes;
972
+ + static_cast<std::size_t>(gearReactionCount) * kGearReactionSnapshotBytes
973
+ + static_cast<std::size_t>(activePairCount + priorPairCount)
974
+ * kContactEventSnapshotBytes
975
+ + 8 + static_cast<std::size_t>(contourEdgeCount) * sizeof(ContourEdge2D);
870
976
  }
871
977
 
872
978
  } // namespace
@@ -888,11 +994,23 @@ struct World2D::Storage {
888
994
  JointBreakEvent2D* stagedBreakEvents = nullptr;
889
995
  GearReactionEntry2D* gearReactions = nullptr;
890
996
  GearReactionEntry2D* stagedGearReactions = nullptr;
997
+ ContactEvent2D* activePairs = nullptr;
998
+ ContactEvent2D* stagedActivePairs = nullptr;
999
+ ContactEvent2D* priorPairs = nullptr;
1000
+ ContactEvent2D* stagedPriorPairs = nullptr;
1001
+ DisabledContactPair2D* disabledPairs = nullptr;
891
1002
  PhysicsContext2D* physics = nullptr;
892
1003
  PhysicsContext2D* stagedPhysics = nullptr;
893
1004
  SolverContext2D* solver = nullptr;
894
1005
  QueryContext2D* query = nullptr;
895
- CheckpointRing2D* checkpoints = nullptr;
1006
+ checkpoint_private::LegacyIdEntry* legacyIds = nullptr;
1007
+ std::uint32_t legacyIdCapacity = 0;
1008
+ RetainedCheckpointSlot2D* slots = nullptr;
1009
+ std::uint32_t slotCapacity = 0;
1010
+ std::uint32_t firstFreeSlot = kCheckpointFreeListEnd;
1011
+ std::uint32_t liveCheckpointCount = 0;
1012
+ ContourEdge2D* contourEdges = nullptr;
1013
+ ContourEdge2D* stagedContourEdges = nullptr;
896
1014
 
897
1015
  std::uint32_t bodyCount = 0;
898
1016
  std::uint32_t stagedBodyCount = 0;
@@ -906,6 +1024,12 @@ struct World2D::Storage {
906
1024
  std::uint32_t stagedBreakEventCount = 0;
907
1025
  std::uint32_t gearReactionCount = 0;
908
1026
  std::uint32_t stagedGearReactionCount = 0;
1027
+ std::uint32_t activePairCount = 0;
1028
+ std::uint32_t stagedActivePairCount = 0;
1029
+ std::uint32_t priorPairCount = 0;
1030
+ std::uint32_t stagedPriorPairCount = 0;
1031
+ std::uint32_t contourEdgeCount = 0;
1032
+ std::uint32_t stagedContourEdgeCount = 0;
909
1033
  std::uint64_t frame = 0;
910
1034
  std::uint64_t stagedFrame = 0;
911
1035
  std::uint32_t nextBodyId = 1;
@@ -920,20 +1044,18 @@ struct World2D::Storage {
920
1044
  Gravity2D stagedCurrentGravity{};
921
1045
  std::uint64_t ownerToken = 0;
922
1046
  std::uint64_t restoreEpoch = 0;
923
- };
924
-
925
- std::uint32_t acquireCheckpointToken() {
926
- std::uint32_t current = nextCheckpointToken.load(std::memory_order_relaxed);
927
- while (current != 0) {
928
- const std::uint32_t next = current == std::numeric_limits<std::uint32_t>::max()
929
- ? 0 : current + 1;
930
- if (nextCheckpointToken.compare_exchange_weak(
931
- current, next, std::memory_order_relaxed, std::memory_order_relaxed)) {
932
- return current;
1047
+ std::uint64_t mutationRevision = 1;
1048
+ bool isAttached = false;
1049
+ bool registered = false;
1050
+ std::uint32_t attachmentToken = 0;
1051
+
1052
+ bool credentialValid(std::uint32_t token) const noexcept {
1053
+ if (isAttached) {
1054
+ return token != 0 && token == attachmentToken;
933
1055
  }
1056
+ return token == 0;
934
1057
  }
935
- return 0;
936
- }
1058
+ };
937
1059
 
938
1060
  std::size_t retainedCheckpointBytes(
939
1061
  std::uint32_t bodyCount,
@@ -941,7 +1063,10 @@ std::size_t retainedCheckpointBytes(
941
1063
  std::uint32_t fluidCount,
942
1064
  std::uint32_t telemetryCount,
943
1065
  std::uint32_t breakEventCount,
944
- std::uint32_t gearReactionCount) {
1066
+ std::uint32_t gearReactionCount,
1067
+ std::uint32_t activePairCount,
1068
+ std::uint32_t priorPairCount,
1069
+ std::uint32_t contourEdgeCount = 0) {
945
1070
  return static_cast<std::size_t>(bodyCount)
946
1071
  * (sizeof(Body) + sizeof(PolygonGeometry))
947
1072
  + static_cast<std::size_t>(jointCount)
@@ -949,7 +1074,10 @@ std::size_t retainedCheckpointBytes(
949
1074
  + static_cast<std::size_t>(fluidCount) * sizeof(FluidRegion2D)
950
1075
  + static_cast<std::size_t>(telemetryCount) * sizeof(JointTelemetry2D)
951
1076
  + static_cast<std::size_t>(breakEventCount) * sizeof(JointBreakEvent2D)
952
- + static_cast<std::size_t>(gearReactionCount) * sizeof(GearReactionEntry2D);
1077
+ + static_cast<std::size_t>(gearReactionCount) * sizeof(GearReactionEntry2D)
1078
+ + static_cast<std::size_t>(activePairCount + priorPairCount)
1079
+ * sizeof(ContactEvent2D)
1080
+ + static_cast<std::size_t>(contourEdgeCount) * sizeof(ContourEdge2D);
953
1081
  }
954
1082
 
955
1083
  World2D::World2D(const WorldConfig2D& config) : config_(config) {
@@ -958,7 +1086,7 @@ World2D::World2D(const WorldConfig2D& config) : config_(config) {
958
1086
  constructionResult_ = result(WorldStatus2D::InvalidConfig);
959
1087
  return;
960
1088
  }
961
- storage_ = new (std::nothrow) Storage();
1089
+ storage_ = memory_private::allocateObject<Storage>(LedgerClass::Storage);
962
1090
  if (storage_ == nullptr) {
963
1091
  constructionResult_ = result(WorldStatus2D::AllocationFailure);
964
1092
  return;
@@ -966,27 +1094,42 @@ World2D::World2D(const WorldConfig2D& config) : config_(config) {
966
1094
  storage_->currentGravity = config_.initialGravity;
967
1095
  storage_->stagedCurrentGravity = config_.initialGravity;
968
1096
  const std::size_t gearCapacity = static_cast<std::size_t>(config_.jointCapacity) * 4;
969
- storage_->bodies = allocatePod<Body>(config_.bodyCapacity);
970
- storage_->stagedBodies = allocatePod<Body>(config_.bodyCapacity);
971
- storage_->geometries = allocatePod<PolygonGeometry>(config_.bodyCapacity);
972
- storage_->stagedGeometries = allocatePod<PolygonGeometry>(config_.bodyCapacity);
973
- storage_->joints = allocatePod<JointRecord2D>(config_.jointCapacity);
974
- storage_->stagedJoints = allocatePod<JointRecord2D>(config_.jointCapacity);
975
- storage_->jointStates = allocatePod<JointState2D>(config_.jointCapacity);
976
- storage_->stagedJointStates = allocatePod<JointState2D>(config_.jointCapacity);
977
- storage_->fluids = allocatePod<FluidRegion2D>(config_.fluidCapacity);
978
- storage_->stagedFluids = allocatePod<FluidRegion2D>(config_.fluidCapacity);
979
- storage_->telemetry = allocatePod<JointTelemetry2D>(config_.jointCapacity);
980
- storage_->stagedTelemetry = allocatePod<JointTelemetry2D>(config_.jointCapacity);
981
- storage_->breakEvents = allocatePod<JointBreakEvent2D>(config_.jointCapacity);
982
- storage_->stagedBreakEvents = allocatePod<JointBreakEvent2D>(config_.jointCapacity);
983
- storage_->gearReactions = allocatePod<GearReactionEntry2D>(gearCapacity);
984
- storage_->stagedGearReactions = allocatePod<GearReactionEntry2D>(gearCapacity);
985
- storage_->physics = new (std::nothrow) PhysicsContext2D(config_.bodyCapacity);
986
- storage_->stagedPhysics = new (std::nothrow) PhysicsContext2D(config_.bodyCapacity);
987
- storage_->solver = new (std::nothrow) SolverContext2D(
988
- config_.bodyCapacity, config_.jointCapacity);
989
- storage_->query = allocatePod<QueryContext2D>(1);
1097
+ storage_->bodies = allocatePod<Body>(LedgerClass::Storage, config_.bodyCapacity);
1098
+ storage_->stagedBodies = allocatePod<Body>(LedgerClass::Storage, config_.bodyCapacity);
1099
+ storage_->geometries = allocatePod<PolygonGeometry>(LedgerClass::Geometry, config_.bodyCapacity);
1100
+ storage_->stagedGeometries = allocatePod<PolygonGeometry>(LedgerClass::Geometry, config_.bodyCapacity);
1101
+ storage_->joints = allocatePod<JointRecord2D>(LedgerClass::Storage, config_.jointCapacity);
1102
+ storage_->stagedJoints = allocatePod<JointRecord2D>(LedgerClass::Storage, config_.jointCapacity);
1103
+ storage_->jointStates = allocatePod<JointState2D>(LedgerClass::Storage, config_.jointCapacity);
1104
+ storage_->stagedJointStates = allocatePod<JointState2D>(LedgerClass::Storage, config_.jointCapacity);
1105
+ storage_->fluids = allocatePod<FluidRegion2D>(LedgerClass::Storage, config_.fluidCapacity);
1106
+ storage_->stagedFluids = allocatePod<FluidRegion2D>(LedgerClass::Storage, config_.fluidCapacity);
1107
+ storage_->telemetry = allocatePod<JointTelemetry2D>(LedgerClass::Storage, config_.jointCapacity);
1108
+ storage_->stagedTelemetry = allocatePod<JointTelemetry2D>(LedgerClass::Storage, config_.jointCapacity);
1109
+ storage_->breakEvents = allocatePod<JointBreakEvent2D>(LedgerClass::Storage, config_.jointCapacity);
1110
+ storage_->stagedBreakEvents = allocatePod<JointBreakEvent2D>(LedgerClass::Storage, config_.jointCapacity);
1111
+ storage_->gearReactions = allocatePod<GearReactionEntry2D>(LedgerClass::Storage, gearCapacity);
1112
+ storage_->stagedGearReactions = allocatePod<GearReactionEntry2D>(LedgerClass::Storage, gearCapacity);
1113
+ storage_->activePairs = allocatePod<ContactEvent2D>(LedgerClass::Storage, config_.contactCapacity);
1114
+ storage_->stagedActivePairs = allocatePod<ContactEvent2D>(LedgerClass::Storage, config_.contactCapacity);
1115
+ storage_->priorPairs = allocatePod<ContactEvent2D>(LedgerClass::Storage, config_.contactCapacity);
1116
+ storage_->stagedPriorPairs = allocatePod<ContactEvent2D>(LedgerClass::Storage, config_.contactCapacity);
1117
+ storage_->contourEdges = allocatePod<ContourEdge2D>(LedgerClass::Geometry, config_.contourEdgeCapacity);
1118
+ storage_->stagedContourEdges = allocatePod<ContourEdge2D>(LedgerClass::Geometry, config_.contourEdgeCapacity);
1119
+ storage_->disabledPairs = allocatePod<DisabledContactPair2D>(LedgerClass::Storage, config_.jointCapacity);
1120
+ storage_->physics = memory_private::allocateObject<PhysicsContext2D>(
1121
+ LedgerClass::Storage, config_.bodyCapacity);
1122
+ storage_->stagedPhysics = memory_private::allocateObject<PhysicsContext2D>(
1123
+ LedgerClass::Storage, config_.bodyCapacity);
1124
+ storage_->solver = memory_private::allocateObject<SolverContext2D>(
1125
+ LedgerClass::Storage, config_.bodyCapacity, config_.jointCapacity);
1126
+ storage_->query = allocatePod<QueryContext2D>(LedgerClass::Storage, 1);
1127
+ storage_->slots = allocatePod<RetainedCheckpointSlot2D>(
1128
+ LedgerClass::Metadata, config_.checkpointCapacity);
1129
+
1130
+ storage_->legacyIdCapacity = checkpoint_private::legacyTableCapacity(config_.checkpointCapacity);
1131
+ storage_->legacyIds = allocatePod<checkpoint_private::LegacyIdEntry>(
1132
+ LedgerClass::Metadata, storage_->legacyIdCapacity);
990
1133
 
991
1134
  const bool buffersReady = (config_.bodyCapacity == 0 || (storage_->bodies != nullptr
992
1135
  && storage_->stagedBodies != nullptr && storage_->geometries != nullptr
@@ -998,7 +1141,14 @@ World2D::World2D(const WorldConfig2D& config) : config_(config) {
998
1141
  && storage_->stagedBreakEvents != nullptr && storage_->gearReactions != nullptr
999
1142
  && storage_->stagedGearReactions != nullptr))
1000
1143
  && (config_.fluidCapacity == 0 || (storage_->fluids != nullptr
1001
- && storage_->stagedFluids != nullptr));
1144
+ && storage_->stagedFluids != nullptr))
1145
+ && (config_.contactCapacity == 0 || (storage_->activePairs != nullptr
1146
+ && storage_->stagedActivePairs != nullptr && storage_->priorPairs != nullptr
1147
+ && storage_->stagedPriorPairs != nullptr))
1148
+ && (config_.contourEdgeCapacity == 0 || (storage_->contourEdges != nullptr
1149
+ && storage_->stagedContourEdges != nullptr))
1150
+ && (config_.jointCapacity == 0 || storage_->disabledPairs != nullptr)
1151
+ && (storage_->slots != nullptr && storage_->legacyIds != nullptr);
1002
1152
  if (!buffersReady || storage_->physics == nullptr || storage_->stagedPhysics == nullptr
1003
1153
  || storage_->solver == nullptr || storage_->query == nullptr
1004
1154
  || !storage_->physics->ready() || !storage_->stagedPhysics->ready()
@@ -1007,6 +1157,29 @@ World2D::World2D(const WorldConfig2D& config) : config_(config) {
1007
1157
  release();
1008
1158
  return;
1009
1159
  }
1160
+ storage_->slotCapacity = config_.checkpointCapacity;
1161
+ storage_->firstFreeSlot = 0;
1162
+ storage_->liveCheckpointCount = 0;
1163
+ for (std::uint32_t i = 0; i < config_.checkpointCapacity; ++i) {
1164
+ storage_->slots[i].slotIndex = i;
1165
+ storage_->slots[i].nextFree = (i + 1 < config_.checkpointCapacity) ? (i + 1) : kCheckpointFreeListEnd;
1166
+ storage_->slots[i].live = false;
1167
+ storage_->slots[i].bytes = nullptr;
1168
+ storage_->slots[i].byteCapacity = 0;
1169
+ storage_->slots[i].byteCount = 0;
1170
+ storage_->slots[i].ownerToken = 0;
1171
+ storage_->slots[i].generation = 0;
1172
+ storage_->slots[i].token = 0;
1173
+ storage_->slots[i].reserved = 0;
1174
+ storage_->slots[i].credentialKind = CheckpointCredentialKind2D::None;
1175
+ }
1176
+ if (!InstanceCheckpointLedger2D::instance().registerWorld()) {
1177
+ constructionResult_ = result(WorldStatus2D::AllocationFailure);
1178
+ release();
1179
+ return;
1180
+ }
1181
+ storage_->registered = true;
1182
+
1010
1183
  storage_->ownerToken = acquireOwnerToken();
1011
1184
  if (storage_->ownerToken == 0) {
1012
1185
  constructionResult_ = result(WorldStatus2D::OwnerTokenExhausted);
@@ -1039,25 +1212,34 @@ WorldIdentity2D World2D::identity() const {
1039
1212
 
1040
1213
  std::size_t World2D::retainedBytes() const {
1041
1214
  if (!ready()) return 0;
1042
- const std::size_t bodyBytes = static_cast<std::size_t>(config_.bodyCapacity)
1043
- * (2 * sizeof(Body) + 2 * sizeof(PolygonGeometry));
1044
- const std::size_t jointBytes = static_cast<std::size_t>(config_.jointCapacity)
1045
- * (2 * sizeof(JointRecord2D) + 2 * sizeof(JointState2D)
1046
- + 2 * sizeof(JointTelemetry2D) + 2 * sizeof(JointBreakEvent2D)
1047
- + 8 * sizeof(GearReactionEntry2D));
1048
- const std::size_t fluidBytes = static_cast<std::size_t>(config_.fluidCapacity)
1049
- * 2 * sizeof(FluidRegion2D);
1050
- std::size_t checkpointBytes = 0;
1051
- if (storage_->checkpoints != nullptr) {
1052
- checkpointBytes = sizeof(CheckpointRing2D);
1053
- for (const RetainedCheckpoint2D& checkpoint : *storage_->checkpoints) {
1054
- checkpointBytes += checkpoint.byteCapacity;
1055
- }
1056
- }
1057
- return sizeof(Storage) + bodyBytes + jointBytes + fluidBytes
1058
- + sizeof(PhysicsContext2D) * 2 + storage_->physics->retainedBytes()
1059
- + storage_->stagedPhysics->retainedBytes() + sizeof(SolverContext2D)
1060
- + storage_->solver->retainedBytes() + sizeof(QueryContext2D) + checkpointBytes;
1215
+ const auto charged = [](const void* pointer) { return memory_private::chargedBytes(pointer); };
1216
+ std::size_t total = charged(storage_)
1217
+ + charged(storage_->bodies) + charged(storage_->stagedBodies)
1218
+ + charged(storage_->geometries) + charged(storage_->stagedGeometries)
1219
+ + charged(storage_->joints) + charged(storage_->stagedJoints)
1220
+ + charged(storage_->jointStates) + charged(storage_->stagedJointStates)
1221
+ + charged(storage_->fluids) + charged(storage_->stagedFluids)
1222
+ + charged(storage_->telemetry) + charged(storage_->stagedTelemetry)
1223
+ + charged(storage_->breakEvents) + charged(storage_->stagedBreakEvents)
1224
+ + charged(storage_->gearReactions) + charged(storage_->stagedGearReactions)
1225
+ + charged(storage_->activePairs) + charged(storage_->stagedActivePairs)
1226
+ + charged(storage_->priorPairs) + charged(storage_->stagedPriorPairs)
1227
+ + charged(storage_->disabledPairs) + charged(storage_->contourEdges)
1228
+ + charged(storage_->stagedContourEdges) + charged(storage_->slots)
1229
+ + charged(storage_->query) + charged(storage_->legacyIds) + storage_->physics->retainedBytes()
1230
+ + storage_->stagedPhysics->retainedBytes() + storage_->solver->retainedBytes();
1231
+ for (std::uint32_t index = 0; index < storage_->slotCapacity; ++index) {
1232
+ total += charged(storage_->slots[index].bytes);
1233
+ }
1234
+ return total;
1235
+ }
1236
+
1237
+ std::size_t World2D::checkpointPayloadBytes() const {
1238
+ if (!ready()) return 0;
1239
+ return retainedCheckpointBytes(
1240
+ storage_->bodyCount, storage_->jointCount, storage_->fluidCount,
1241
+ storage_->telemetryCount, storage_->breakEventCount, storage_->gearReactionCount,
1242
+ storage_->activePairCount, storage_->priorPairCount, storage_->contourEdgeCount);
1061
1243
  }
1062
1244
 
1063
1245
  bool World2D::storageOverlaps(const void* pointer, std::size_t bytes) const {
@@ -1083,6 +1265,12 @@ WorldState2DView World2D::state() const {
1083
1265
  storage_->breakEventCount,
1084
1266
  storage_->gearReactions,
1085
1267
  storage_->gearReactionCount,
1268
+ storage_->activePairs,
1269
+ storage_->activePairCount,
1270
+ storage_->priorPairs,
1271
+ storage_->priorPairCount,
1272
+ storage_->contourEdges,
1273
+ storage_->contourEdgeCount,
1086
1274
  storage_->frame,
1087
1275
  storage_->nextBodyId,
1088
1276
  storage_->nextJointId,
@@ -1094,10 +1282,16 @@ WorldState2DView World2D::state() const {
1094
1282
 
1095
1283
  WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1096
1284
  if (!ready()) return result(WorldStatus2D::NotReady);
1285
+ if (storage_->mutationRevision == std::numeric_limits<std::uint64_t>::max()) {
1286
+ return result(WorldStatus2D::EpochExhausted);
1287
+ }
1097
1288
  if (state.bodyCount > config_.bodyCapacity || state.jointCount > config_.jointCapacity
1098
1289
  || state.fluidCount > config_.fluidCapacity || state.telemetryCount > config_.jointCapacity
1099
1290
  || state.breakEventCount > config_.jointCapacity
1100
- || state.gearReactionCount > static_cast<std::uint64_t>(config_.jointCapacity) * 4) {
1291
+ || state.gearReactionCount > static_cast<std::uint64_t>(config_.jointCapacity) * 4
1292
+ || state.activePairCount > config_.contactCapacity
1293
+ || state.priorPairCount > config_.contactCapacity
1294
+ || state.contourEdgeCount > config_.contourEdgeCapacity) {
1101
1295
  return result(WorldStatus2D::CapacityExceeded);
1102
1296
  }
1103
1297
  if ((state.bodyCount > 0 && (state.bodies == nullptr || state.geometries == nullptr))
@@ -1106,6 +1300,9 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1106
1300
  || (state.telemetryCount > 0 && state.telemetry == nullptr)
1107
1301
  || (state.breakEventCount > 0 && state.breakEvents == nullptr)
1108
1302
  || (state.gearReactionCount > 0 && state.gearReactions == nullptr)
1303
+ || (state.contourEdgeCount > 0 && state.contourEdges == nullptr)
1304
+ || !validContactPairs(state.activePairs, state.activePairCount)
1305
+ || !validContactPairs(state.priorPairs, state.priorPairCount)
1109
1306
  || !validOptions(state.latestStepOptions)
1110
1307
  || !validGravity(state.currentGravity)) {
1111
1308
  return result(WorldStatus2D::InvalidArguments);
@@ -1120,6 +1317,12 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1120
1317
  {state.breakEvents, sizeof(JointBreakEvent2D) * state.breakEventCount, alignof(JointBreakEvent2D)},
1121
1318
  {state.gearReactions, sizeof(GearReactionEntry2D) * state.gearReactionCount,
1122
1319
  alignof(GearReactionEntry2D)},
1320
+ {state.activePairs, sizeof(ContactEvent2D) * state.activePairCount,
1321
+ alignof(ContactEvent2D)},
1322
+ {state.priorPairs, sizeof(ContactEvent2D) * state.priorPairCount,
1323
+ alignof(ContactEvent2D)},
1324
+ {state.contourEdges, sizeof(ContourEdge2D) * state.contourEdgeCount,
1325
+ alignof(ContourEdge2D)},
1123
1326
  };
1124
1327
  for (const InputRange& input : inputs) {
1125
1328
  if (!rangeIsValid(input.data, input.bytes, input.alignment)) {
@@ -1177,9 +1380,29 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1177
1380
  sizeof(GearReactionEntry2D) * state.gearReactionCount);
1178
1381
  }
1179
1382
  }
1383
+ if (state.activePairCount > 0 && storage_->stagedActivePairs != state.activePairs) {
1384
+ std::memmove(storage_->stagedActivePairs, state.activePairs,
1385
+ sizeof(ContactEvent2D) * state.activePairCount);
1386
+ }
1387
+ if (state.priorPairCount > 0 && storage_->stagedPriorPairs != state.priorPairs) {
1388
+ std::memmove(storage_->stagedPriorPairs, state.priorPairs,
1389
+ sizeof(ContactEvent2D) * state.priorPairCount);
1390
+ }
1391
+ if (state.contourEdgeCount > 0 && storage_->stagedContourEdges != state.contourEdges) {
1392
+ std::memmove(storage_->stagedContourEdges, state.contourEdges,
1393
+ sizeof(ContourEdge2D) * state.contourEdgeCount);
1394
+ }
1395
+ storage_->stagedContourEdgeCount = state.contourEdgeCount;
1180
1396
  for (std::uint32_t index = 0; index < state.bodyCount; index += 1) {
1181
1397
  normalizeBody(storage_->stagedBodies[index]);
1182
- normalizeGeometry(storage_->stagedGeometries[index]);
1398
+ if (storage_->stagedBodies[index].shape == ShapeType::Contour) {
1399
+ ContourHeader2D header{};
1400
+ std::memcpy(&header, &storage_->stagedGeometries[index], sizeof(header));
1401
+ header.skin = cleanZero(header.skin);
1402
+ std::memcpy(&storage_->stagedGeometries[index], &header, sizeof(header));
1403
+ } else {
1404
+ normalizeGeometry(storage_->stagedGeometries[index]);
1405
+ }
1183
1406
  }
1184
1407
  for (std::uint32_t index = 0; index < state.jointCount; index += 1) {
1185
1408
  normalizeJoint(storage_->stagedJoints[index]);
@@ -1200,6 +1423,8 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1200
1423
  storage_->stagedTelemetryCount = state.telemetryCount;
1201
1424
  storage_->stagedBreakEventCount = state.breakEventCount;
1202
1425
  storage_->stagedGearReactionCount = state.gearReactionCount;
1426
+ storage_->stagedActivePairCount = state.activePairCount;
1427
+ storage_->stagedPriorPairCount = state.priorPairCount;
1203
1428
  storage_->stagedFrame = state.frame;
1204
1429
  storage_->stagedNextBodyId = state.nextBodyId;
1205
1430
  storage_->stagedNextJointId = state.nextJointId;
@@ -1213,7 +1438,7 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1213
1438
  for (std::uint32_t index = 0; index < state.bodyCount; index += 1) {
1214
1439
  const Body& body = storage_->stagedBodies[index];
1215
1440
  const PolygonGeometry& geometry = storage_->stagedGeometries[index];
1216
- const bool isIndexedGeom = (body.shape == ShapeType::Polygon || body.shape == ShapeType::Chain || body.shape == ShapeType::Segment);
1441
+ const bool isIndexedGeom = (body.shape == ShapeType::Polygon || body.shape == ShapeType::Chain || body.shape == ShapeType::Segment || body.shape == ShapeType::Contour);
1217
1442
  const bool validGeomReserved = isIndexedGeom
1218
1443
  ? (body.shape == ShapeType::Segment
1219
1444
  ? (body.reserved == index || (body.reserved == 0 && emptyGeometryIsCanonical(geometry)))
@@ -1226,8 +1451,15 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1226
1451
  }
1227
1452
  maximumBodyId = body.id;
1228
1453
  }
1454
+ for (std::uint32_t index = 0; index < state.activePairCount; index += 1) {
1455
+ maximumBodyId = std::max(maximumBodyId, state.activePairs[index].bodyB);
1456
+ }
1457
+ for (std::uint32_t index = 0; index < state.priorPairCount; index += 1) {
1458
+ maximumBodyId = std::max(maximumBodyId, state.priorPairs[index].bodyB);
1459
+ }
1229
1460
  const std::int32_t geometryStatus = setPolygonGeometry(
1230
1461
  *storage_->stagedPhysics, storage_->stagedGeometries, state.bodyCount);
1462
+ setContourEdges(*storage_->stagedPhysics, storage_->stagedContourEdges, state.contourEdgeCount);
1231
1463
  if (geometryStatus != kStepOk) {
1232
1464
  return result(geometryStatus == kStepWorkspaceAllocation
1233
1465
  ? WorldStatus2D::AllocationFailure : WorldStatus2D::InvalidState, geometryStatus);
@@ -1313,19 +1545,31 @@ WorldResult2D World2D::stageAndValidate(const WorldState2DView& state) {
1313
1545
  return result(WorldStatus2D::Success);
1314
1546
  }
1315
1547
 
1316
- void World2D::commitStagedTopology() noexcept {
1548
+ WorldResult2D World2D::commitStagedTopology() noexcept {
1549
+ if (storage_->mutationRevision == std::numeric_limits<std::uint64_t>::max()) {
1550
+ return result(WorldStatus2D::EpochExhausted);
1551
+ }
1552
+ const auto checked = clock_private::Access::invalidatePair(
1553
+ *storage_->physics, *storage_->stagedPhysics, true);
1554
+ if (const auto* failure = std::get_if<clock_private::Failure>(&checked))
1555
+ return result(failure->code == clock_private::Error::GenerationOverflow
1556
+ ? WorldStatus2D::EpochExhausted : WorldStatus2D::InvalidState, kStepJointInvalidArguments);
1317
1557
  std::swap(storage_->bodies, storage_->stagedBodies);
1318
1558
  std::swap(storage_->geometries, storage_->stagedGeometries);
1319
1559
  std::swap(storage_->joints, storage_->stagedJoints);
1320
1560
  std::swap(storage_->jointStates, storage_->stagedJointStates);
1321
1561
  std::swap(storage_->fluids, storage_->stagedFluids);
1322
1562
  std::swap(storage_->physics, storage_->stagedPhysics);
1563
+ std::swap(storage_->contourEdges, storage_->stagedContourEdges);
1323
1564
  storage_->bodyCount = storage_->stagedBodyCount;
1565
+ storage_->contourEdgeCount = storage_->stagedContourEdgeCount;
1324
1566
  storage_->jointCount = storage_->stagedJointCount;
1325
1567
  storage_->fluidCount = storage_->stagedFluidCount;
1326
1568
  storage_->nextBodyId = storage_->stagedNextBodyId;
1327
1569
  storage_->nextJointId = storage_->stagedNextJointId;
1328
1570
  storage_->nextFluidId = storage_->stagedNextFluidId;
1571
+ storage_->mutationRevision += 1;
1572
+ return result(WorldStatus2D::Success);
1329
1573
  }
1330
1574
 
1331
1575
  bool World2D::topologyEditAliases(
@@ -1361,32 +1605,97 @@ bool World2D::topologyEditAliases(
1361
1605
  sizeof(GearReactionEntry2D) * config_.jointCapacity * 4},
1362
1606
  {storage_->stagedGearReactions,
1363
1607
  sizeof(GearReactionEntry2D) * config_.jointCapacity * 4},
1608
+ {storage_->activePairs, sizeof(ContactEvent2D) * config_.contactCapacity},
1609
+ {storage_->stagedActivePairs, sizeof(ContactEvent2D) * config_.contactCapacity},
1610
+ {storage_->priorPairs, sizeof(ContactEvent2D) * config_.contactCapacity},
1611
+ {storage_->stagedPriorPairs, sizeof(ContactEvent2D) * config_.contactCapacity},
1612
+ {storage_->disabledPairs, sizeof(DisabledContactPair2D) * config_.jointCapacity},
1364
1613
  {storage_->physics, sizeof(PhysicsContext2D)},
1365
1614
  {storage_->stagedPhysics, sizeof(PhysicsContext2D)},
1366
1615
  {storage_->solver, sizeof(SolverContext2D)},
1367
1616
  {storage_->query, sizeof(QueryContext2D)},
1617
+ {storage_->slots, sizeof(RetainedCheckpointSlot2D) * storage_->slotCapacity},
1618
+ {storage_->legacyIds, sizeof(checkpoint_private::LegacyIdEntry) * storage_->legacyIdCapacity},
1619
+ {storage_->contourEdges, sizeof(ContourEdge2D) * config_.contourEdgeCapacity},
1620
+ {storage_->stagedContourEdges, sizeof(ContourEdge2D) * config_.contourEdgeCapacity},
1368
1621
  };
1369
1622
  for (std::uint32_t external = 0; external < count; external += 1) {
1370
1623
  for (const Range& internal : authoritative) {
1371
1624
  if (rangesOverlap(pointers[external], sizes[external],
1372
1625
  internal.data, internal.bytes)) return true;
1373
1626
  }
1627
+ if (storage_->slots != nullptr) {
1628
+ for (std::uint32_t slotIndex = 0; slotIndex < storage_->slotCapacity; slotIndex += 1) {
1629
+ const RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
1630
+ if (slot.bytes == nullptr || slot.byteCapacity == 0) continue;
1631
+ if (rangesOverlap(pointers[external], sizes[external], slot.bytes, slot.byteCapacity)) {
1632
+ return true;
1633
+ }
1634
+ }
1635
+ }
1374
1636
  }
1375
1637
  return false;
1376
1638
  }
1377
1639
 
1640
+ bool World2D::acceptOutput(
1641
+ const void* pointer,
1642
+ std::size_t bytes,
1643
+ std::size_t alignment) const {
1644
+ if (!rangeIsValid(pointer, bytes, alignment)) return false;
1645
+ const void* pointers[] = {pointer};
1646
+ const std::size_t sizes[] = {bytes};
1647
+ return !topologyEditAliases(pointers, sizes, 1);
1648
+ }
1649
+
1650
+ bool World2D::acceptOutputs(
1651
+ const void* const* pointers,
1652
+ const std::size_t* sizes,
1653
+ const std::size_t* alignments,
1654
+ std::uint32_t count) const {
1655
+ for (std::uint32_t index = 0; index < count; index += 1) {
1656
+ if (!rangeIsValid(pointers[index], sizes[index], alignments[index])) return false;
1657
+ }
1658
+ return !topologyEditAliases(pointers, sizes, count);
1659
+ }
1660
+
1661
+ bool World2D::resolveLegacyCheckpoint(
1662
+ std::uint32_t handle,
1663
+ std::uint32_t& slotIndex,
1664
+ std::uint32_t& generation) const {
1665
+ if (!ready() || handle == 0 || storage_->slots == nullptr) return false;
1666
+ const std::uint32_t index = checkpoint_private::legacySlot(
1667
+ {storage_->legacyIds, storage_->legacyIdCapacity}, handle);
1668
+ if (index >= storage_->slotCapacity) return false;
1669
+ const RetainedCheckpointSlot2D& slot = storage_->slots[index];
1670
+ if (!slot.live || slot.credentialKind != CheckpointCredentialKind2D::Legacy
1671
+ || slot.token == 0 || slot.token != handle
1672
+ || slot.ownerToken != storage_->ownerToken) {
1673
+ return false;
1674
+ }
1675
+ slotIndex = index;
1676
+ generation = slot.generation;
1677
+ return true;
1678
+ }
1679
+
1378
1680
  void World2D::normalizeTopologyJoint(JointRecord2D& joint) const {
1379
1681
  normalizeJoint(joint);
1380
1682
  }
1381
1683
 
1382
1684
  WorldResult2D World2D::commitStaged() {
1383
- commitStagedTopology();
1685
+ if (storage_->restoreEpoch == std::numeric_limits<std::uint64_t>::max())
1686
+ return result(WorldStatus2D::EpochExhausted);
1687
+ const auto topology = commitStagedTopology();
1688
+ if (!topology.ok()) return topology;
1384
1689
  std::swap(storage_->telemetry, storage_->stagedTelemetry);
1385
1690
  std::swap(storage_->breakEvents, storage_->stagedBreakEvents);
1386
1691
  std::swap(storage_->gearReactions, storage_->stagedGearReactions);
1692
+ std::swap(storage_->activePairs, storage_->stagedActivePairs);
1693
+ std::swap(storage_->priorPairs, storage_->stagedPriorPairs);
1387
1694
  storage_->telemetryCount = storage_->stagedTelemetryCount;
1388
1695
  storage_->breakEventCount = storage_->stagedBreakEventCount;
1389
1696
  storage_->gearReactionCount = storage_->stagedGearReactionCount;
1697
+ storage_->activePairCount = storage_->stagedActivePairCount;
1698
+ storage_->priorPairCount = storage_->stagedPriorPairCount;
1390
1699
  storage_->frame = storage_->stagedFrame;
1391
1700
  storage_->latestStepOptions = storage_->stagedLatestStepOptions;
1392
1701
  storage_->currentGravity = storage_->stagedCurrentGravity;
@@ -1412,7 +1721,19 @@ WorldResult2D World2D::setGravity(double x, double y) {
1412
1721
  Gravity2D candidate{x, y};
1413
1722
  if (!validGravity(candidate)) return result(WorldStatus2D::InvalidArguments);
1414
1723
  normalizeGravity(candidate);
1724
+ if (candidate.x == storage_->currentGravity.x && candidate.y == storage_->currentGravity.y) {
1725
+ return result(WorldStatus2D::Success);
1726
+ }
1727
+ if (storage_->mutationRevision == std::numeric_limits<std::uint64_t>::max()) {
1728
+ return result(WorldStatus2D::EpochExhausted);
1729
+ }
1730
+ const auto checked = clock_private::Access::invalidatePair(
1731
+ *storage_->physics, *storage_->stagedPhysics, false);
1732
+ if (const auto* failure = std::get_if<clock_private::Failure>(&checked))
1733
+ return result(failure->code == clock_private::Error::GenerationOverflow
1734
+ ? WorldStatus2D::EpochExhausted : WorldStatus2D::InvalidState, kStepJointInvalidArguments);
1415
1735
  storage_->currentGravity = candidate;
1736
+ storage_->mutationRevision += 1;
1416
1737
  return result(WorldStatus2D::Success);
1417
1738
  }
1418
1739
 
@@ -1433,246 +1754,517 @@ WorldResult2D World2D::step(const StepOptions& options) {
1433
1754
  if (storage_->frame == std::numeric_limits<std::uint64_t>::max()) {
1434
1755
  return result(WorldStatus2D::FrameOverflow);
1435
1756
  }
1757
+ if (storage_->mutationRevision == std::numeric_limits<std::uint64_t>::max()) {
1758
+ return result(WorldStatus2D::EpochExhausted);
1759
+ }
1436
1760
  FluidState2D fluidState{};
1437
1761
  fluidState.regionCount = storage_->fluidCount;
1438
1762
  for (std::uint32_t index = 0; index < storage_->fluidCount; index += 1) {
1439
1763
  fluidState.regions[index] = storage_->fluids[index];
1440
1764
  }
1441
- std::uint32_t eventCount = storage_->breakEventCount;
1442
- std::uint32_t gearReactionCount = storage_->gearReactionCount;
1765
+ if (storage_->bodyCount > 0) {
1766
+ std::memcpy(storage_->stagedBodies, storage_->bodies,
1767
+ sizeof(Body) * storage_->bodyCount);
1768
+ }
1769
+ if (storage_->jointCount > 0) {
1770
+ std::memcpy(storage_->stagedJointStates, storage_->jointStates,
1771
+ sizeof(JointState2D) * storage_->jointCount);
1772
+ }
1773
+ const std::int32_t geometryStatus = setPolygonGeometry(
1774
+ *storage_->stagedPhysics, storage_->geometries, storage_->bodyCount);
1775
+ setContourEdges(*storage_->stagedPhysics, storage_->contourEdges, storage_->contourEdgeCount);
1776
+ if (geometryStatus != kStepOk) {
1777
+ return result(geometryStatus == kStepWorkspaceAllocation
1778
+ ? WorldStatus2D::AllocationFailure : WorldStatus2D::InvalidState,
1779
+ geometryStatus);
1780
+ }
1781
+ std::uint32_t eventCount = 0;
1782
+ std::uint32_t gearReactionCount = 0;
1443
1783
  const std::int32_t status = stepWorld2D(
1444
1784
  *storage_->solver,
1445
- *storage_->physics,
1446
- storage_->bodies,
1785
+ *storage_->stagedPhysics,
1786
+ storage_->stagedBodies,
1447
1787
  storage_->bodyCount,
1448
1788
  storage_->joints,
1449
1789
  storage_->jointCount,
1450
- storage_->jointStates,
1790
+ storage_->stagedJointStates,
1451
1791
  storage_->jointCount,
1452
- storage_->telemetry,
1792
+ storage_->stagedTelemetry,
1453
1793
  config_.jointCapacity,
1454
- storage_->breakEvents,
1794
+ storage_->stagedBreakEvents,
1455
1795
  config_.jointCapacity,
1456
1796
  &eventCount,
1457
- storage_->gearReactions,
1797
+ storage_->stagedGearReactions,
1458
1798
  config_.jointCapacity * 4,
1459
1799
  &gearReactionCount,
1460
1800
  storage_->fluidCount == 0 ? nullptr : &fluidState,
1461
1801
  options);
1462
1802
  if (status != kStepOk) return result(WorldStatus2D::NativeStepFailure, status);
1803
+ const std::uint32_t disabledPairCount = buildWorldDisabledPairs(
1804
+ storage_->joints, storage_->stagedJointStates, storage_->jointCount,
1805
+ storage_->disabledPairs);
1806
+ std::uint32_t activePairCount = 0;
1807
+ const std::int32_t contactStatus = collectContactPairs2D(
1808
+ *storage_->stagedPhysics, storage_->stagedBodies, storage_->bodyCount,
1809
+ storage_->disabledPairs, disabledPairCount, storage_->stagedActivePairs,
1810
+ config_.contactCapacity, &activePairCount);
1811
+ if (contactStatus != kStepOk) {
1812
+ return result(WorldStatus2D::NativeStepFailure, contactStatus);
1813
+ }
1463
1814
  for (std::uint32_t index = 0; index < storage_->bodyCount; index += 1) {
1464
- normalizeBody(storage_->bodies[index]);
1815
+ normalizeBody(storage_->stagedBodies[index]);
1465
1816
  }
1466
1817
  for (std::uint32_t index = 0; index < storage_->jointCount; index += 1) {
1467
- normalizeJointState(storage_->jointStates[index]);
1468
- normalizeTelemetry(storage_->telemetry[index]);
1818
+ normalizeJointState(storage_->stagedJointStates[index]);
1819
+ normalizeTelemetry(storage_->stagedTelemetry[index]);
1469
1820
  }
1470
1821
  for (std::uint32_t index = 0; index < gearReactionCount; index += 1) {
1471
- normalizeGearReaction(storage_->gearReactions[index]);
1822
+ normalizeGearReaction(storage_->stagedGearReactions[index]);
1472
1823
  }
1824
+ std::swap(storage_->bodies, storage_->stagedBodies);
1825
+ std::swap(storage_->jointStates, storage_->stagedJointStates);
1826
+ std::swap(storage_->telemetry, storage_->stagedTelemetry);
1827
+ std::swap(storage_->breakEvents, storage_->stagedBreakEvents);
1828
+ std::swap(storage_->gearReactions, storage_->stagedGearReactions);
1829
+ std::swap(storage_->physics, storage_->stagedPhysics);
1830
+ ContactEvent2D* obsoletePriorPairs = storage_->priorPairs;
1831
+ storage_->priorPairs = storage_->activePairs;
1832
+ storage_->activePairs = storage_->stagedActivePairs;
1833
+ storage_->stagedActivePairs = obsoletePriorPairs;
1834
+ storage_->priorPairCount = storage_->activePairCount;
1835
+ storage_->activePairCount = activePairCount;
1473
1836
  storage_->telemetryCount = storage_->jointCount;
1474
1837
  storage_->breakEventCount = eventCount;
1475
1838
  storage_->gearReactionCount = gearReactionCount;
1476
1839
  storage_->frame += 1;
1840
+ storage_->mutationRevision += 1;
1477
1841
  storage_->latestStepOptions = options;
1478
1842
  normalizeOptions(storage_->latestStepOptions);
1479
1843
  return result(WorldStatus2D::Success);
1480
1844
  }
1481
1845
 
1846
+ std::uint32_t World2D::contactEventCount() const {
1847
+ if (!ready()) return 0;
1848
+ std::uint32_t count = 0;
1849
+ std::uint32_t active = 0;
1850
+ std::uint32_t prior = 0;
1851
+ while (active < storage_->activePairCount || prior < storage_->priorPairCount) {
1852
+ count += 1;
1853
+ if (active == storage_->activePairCount) {
1854
+ prior += 1;
1855
+ } else if (prior == storage_->priorPairCount) {
1856
+ active += 1;
1857
+ } else if (contactPairLess(storage_->activePairs[active], storage_->priorPairs[prior])) {
1858
+ active += 1;
1859
+ } else if (contactPairLess(storage_->priorPairs[prior], storage_->activePairs[active])) {
1860
+ prior += 1;
1861
+ } else {
1862
+ active += 1;
1863
+ prior += 1;
1864
+ }
1865
+ }
1866
+ return count;
1867
+ }
1868
+
1869
+ WorldResult2D World2D::copyContactEvents(
1870
+ ContactEvent2D* output,
1871
+ std::uint32_t outputCapacity,
1872
+ std::uint32_t* outputCount) const {
1873
+ if (!ready()) return result(WorldStatus2D::NotReady);
1874
+ if (outputCount == nullptr || (outputCapacity > 0 && output == nullptr)) {
1875
+ return result(WorldStatus2D::InvalidArguments);
1876
+ }
1877
+ const std::uint32_t required = contactEventCount();
1878
+ if (outputCapacity < required) return result(WorldStatus2D::CapacityExceeded);
1879
+ std::uint32_t count = 0;
1880
+ std::uint32_t active = 0;
1881
+ std::uint32_t prior = 0;
1882
+ while (active < storage_->activePairCount || prior < storage_->priorPairCount) {
1883
+ ContactEvent2D event{};
1884
+ if (active == storage_->activePairCount) {
1885
+ event = storage_->priorPairs[prior++];
1886
+ event.type = ContactEventType2D::Exit;
1887
+ } else if (prior == storage_->priorPairCount
1888
+ || contactPairLess(storage_->activePairs[active], storage_->priorPairs[prior])) {
1889
+ event = storage_->activePairs[active++];
1890
+ event.type = ContactEventType2D::Enter;
1891
+ } else if (contactPairLess(storage_->priorPairs[prior], storage_->activePairs[active])) {
1892
+ event = storage_->priorPairs[prior++];
1893
+ event.type = ContactEventType2D::Exit;
1894
+ } else {
1895
+ event = storage_->activePairs[active++];
1896
+ prior += 1;
1897
+ event.type = ContactEventType2D::Stay;
1898
+ }
1899
+ output[count++] = event;
1900
+ }
1901
+ *outputCount = count;
1902
+ return result(WorldStatus2D::Success);
1903
+ }
1904
+
1482
1905
  std::size_t World2D::captureSize() const {
1483
1906
  if (!ready()) return 0;
1484
1907
  return snapshotSize(storage_->bodyCount, storage_->jointCount, storage_->fluidCount,
1485
- storage_->telemetryCount, storage_->breakEventCount, storage_->gearReactionCount);
1908
+ storage_->telemetryCount, storage_->breakEventCount, storage_->gearReactionCount,
1909
+ storage_->activePairCount, storage_->priorPairCount, storage_->contourEdgeCount);
1486
1910
  }
1487
1911
 
1488
- WorldResult2D World2D::captureCheckpoint(std::uint32_t* checkpointHandle) {
1912
+ WorldResult2D World2D::captureCheckpointToken(
1913
+ std::uint32_t attachmentToken,
1914
+ CheckpointToken2D* outputToken) {
1489
1915
  if (!ready()) return result(WorldStatus2D::NotReady);
1490
- if (checkpointHandle == nullptr) return result(WorldStatus2D::InvalidArguments);
1491
- if (storage_->checkpoints == nullptr) {
1492
- storage_->checkpoints = new (std::nothrow) CheckpointRing2D();
1493
- if (storage_->checkpoints == nullptr) return result(WorldStatus2D::AllocationFailure);
1494
- }
1495
- const auto available = std::find_if(
1496
- storage_->checkpoints->begin(), storage_->checkpoints->end(),
1497
- [](const RetainedCheckpoint2D& checkpoint) { return !checkpoint.live; });
1498
- if (available == storage_->checkpoints->end()) {
1916
+ if (!storage_->credentialValid(attachmentToken)) return result(WorldStatus2D::WorldAttached);
1917
+ if (!acceptOutput(outputToken, sizeof(*outputToken), alignof(CheckpointToken2D))) {
1918
+ return result(WorldStatus2D::InvalidArguments);
1919
+ }
1920
+ return captureCheckpointCredential(CheckpointCredentialKind2D::Token, nullptr, outputToken);
1921
+ }
1922
+
1923
+ WorldResult2D World2D::captureCheckpointCredential(
1924
+ CheckpointCredentialKind2D kind,
1925
+ std::uint32_t* legacyHandle,
1926
+ CheckpointToken2D* tokenOut) {
1927
+ const bool legacy = kind == CheckpointCredentialKind2D::Legacy;
1928
+ if (kind != CheckpointCredentialKind2D::Token && !legacy) {
1929
+ return result(WorldStatus2D::InvalidState);
1930
+ }
1931
+ if (legacy && legacyHandle == nullptr) return result(WorldStatus2D::InvalidArguments);
1932
+ if (!legacy && tokenOut == nullptr) return result(WorldStatus2D::InvalidArguments);
1933
+ if (storage_->firstFreeSlot == kCheckpointFreeListEnd
1934
+ || storage_->liveCheckpointCount >= storage_->slotCapacity) {
1499
1935
  return result(WorldStatus2D::CheckpointCapacity);
1500
1936
  }
1501
- const std::uint32_t token = acquireCheckpointToken();
1502
- if (token == 0) return result(WorldStatus2D::CheckpointCapacity);
1503
- const std::size_t required = retainedCheckpointBytes(
1504
- storage_->bodyCount, storage_->jointCount, storage_->fluidCount,
1505
- storage_->telemetryCount, storage_->breakEventCount, storage_->gearReactionCount);
1506
- if (available->byteCapacity < required) {
1507
- std::uint8_t* replacement = allocatePod<std::uint8_t>(required);
1937
+
1938
+ // Refuse before any allocation. Each kind reads only its own counter.
1939
+ if (legacy) {
1940
+ if (!legacyCheckpointGenerationAvailable()) {
1941
+ return result(WorldStatus2D::CheckpointTokenExhausted);
1942
+ }
1943
+ } else if (!checkpointGenerationAvailable()) {
1944
+ return result(WorldStatus2D::CheckpointTokenExhausted);
1945
+ }
1946
+
1947
+ const std::size_t required = checkpointPayloadBytes();
1948
+ std::uint8_t* replacement = nullptr;
1949
+ if (required > 0) {
1950
+ replacement = memory_private::allocateArray<std::uint8_t>(
1951
+ LedgerClass::Checkpoint, required, false);
1508
1952
  if (replacement == nullptr) return result(WorldStatus2D::AllocationFailure);
1509
- freePod(available->bytes);
1510
- available->bytes = replacement;
1511
- available->byteCapacity = required;
1512
1953
  }
1513
- std::uint8_t* output = available->bytes;
1514
- const auto copy = [&output](const void* source, std::size_t bytes) {
1515
- if (bytes != 0) {
1954
+ if (!InstanceCheckpointLedger2D::instance().claimSlot()) {
1955
+ discardCheckpointCandidate(replacement, false);
1956
+ return result(WorldStatus2D::AllocationFailure);
1957
+ }
1958
+
1959
+ if (required > 0) {
1960
+ std::uint8_t* output = replacement;
1961
+ const auto copy = [&output](const void* source, std::size_t bytes) {
1962
+ if (bytes == 0) return;
1516
1963
  std::memcpy(output, source, bytes);
1517
1964
  output += bytes;
1965
+ };
1966
+ copy(storage_->bodies, sizeof(Body) * storage_->bodyCount);
1967
+ copy(storage_->geometries, sizeof(PolygonGeometry) * storage_->bodyCount);
1968
+ copy(storage_->joints, sizeof(JointRecord2D) * storage_->jointCount);
1969
+ copy(storage_->jointStates, sizeof(JointState2D) * storage_->jointCount);
1970
+ copy(storage_->fluids, sizeof(FluidRegion2D) * storage_->fluidCount);
1971
+ copy(storage_->telemetry, sizeof(JointTelemetry2D) * storage_->telemetryCount);
1972
+ copy(storage_->breakEvents, sizeof(JointBreakEvent2D) * storage_->breakEventCount);
1973
+ copy(storage_->gearReactions, sizeof(GearReactionEntry2D) * storage_->gearReactionCount);
1974
+ copy(storage_->activePairs, sizeof(ContactEvent2D) * storage_->activePairCount);
1975
+ copy(storage_->priorPairs, sizeof(ContactEvent2D) * storage_->priorPairCount);
1976
+ copy(storage_->contourEdges, sizeof(ContourEdge2D) * storage_->contourEdgeCount);
1977
+ }
1978
+
1979
+ // The candidate is complete. Reserve only the counter for this kind.
1980
+ std::uint32_t insertion = checkpoint_private::kMissingEntry;
1981
+ std::uint32_t credential = 0;
1982
+ if (legacy) {
1983
+ const auto reservation = checkpoint_private::reserveLegacyId(legacyCheckpointGenerationCounter(),
1984
+ {storage_->legacyIds, storage_->legacyIdCapacity});
1985
+ if (const auto* reserved = std::get_if<checkpoint_private::ReservedLegacyId>(&reservation)) {
1986
+ credential = reserved->id;
1987
+ insertion = reserved->insertion;
1988
+ } else {
1989
+ switch (std::get<checkpoint_private::LegacyIdReservationError>(reservation)) {
1990
+ case checkpoint_private::LegacyIdReservationError::Exhausted:
1991
+ break;
1992
+ case checkpoint_private::LegacyIdReservationError::TableInvariantViolation:
1993
+ discardCheckpointCandidate(replacement, true);
1994
+ memory_private::InstanceLedger::instance().noteImbalance();
1995
+ return result(WorldStatus2D::InvalidState);
1996
+ }
1518
1997
  }
1519
- };
1520
- copy(storage_->bodies, sizeof(Body) * storage_->bodyCount);
1521
- copy(storage_->geometries, sizeof(PolygonGeometry) * storage_->bodyCount);
1522
- copy(storage_->joints, sizeof(JointRecord2D) * storage_->jointCount);
1523
- copy(storage_->jointStates, sizeof(JointState2D) * storage_->jointCount);
1524
- copy(storage_->fluids, sizeof(FluidRegion2D) * storage_->fluidCount);
1525
- copy(storage_->telemetry, sizeof(JointTelemetry2D) * storage_->telemetryCount);
1526
- copy(storage_->breakEvents, sizeof(JointBreakEvent2D) * storage_->breakEventCount);
1527
- copy(storage_->gearReactions, sizeof(GearReactionEntry2D) * storage_->gearReactionCount);
1528
- available->byteCount = required;
1529
- available->ownerToken = storage_->ownerToken;
1530
- available->frame = storage_->frame;
1531
- available->nextBodyId = storage_->nextBodyId;
1532
- available->nextJointId = storage_->nextJointId;
1533
- available->nextFluidId = storage_->nextFluidId;
1534
- available->bodyCount = storage_->bodyCount;
1535
- available->jointCount = storage_->jointCount;
1536
- available->fluidCount = storage_->fluidCount;
1537
- available->telemetryCount = storage_->telemetryCount;
1538
- available->breakEventCount = storage_->breakEventCount;
1539
- available->gearReactionCount = storage_->gearReactionCount;
1540
- available->latestStepOptions = storage_->latestStepOptions;
1541
- available->currentGravity = storage_->currentGravity;
1542
- available->token = token;
1543
- available->live = true;
1544
- *checkpointHandle = token;
1998
+ } else {
1999
+ credential = reserveCheckpointGeneration();
2000
+ }
2001
+ if (credential == 0) {
2002
+ discardCheckpointCandidate(replacement, true);
2003
+ return result(WorldStatus2D::CheckpointTokenExhausted);
2004
+ }
2005
+
2006
+ const std::uint32_t slotIndex = storage_->firstFreeSlot;
2007
+ RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
2008
+ storage_->firstFreeSlot = slot.nextFree;
2009
+ slot.nextFree = kCheckpointFreeListEnd;
2010
+ freeInstalledPayload(slot);
2011
+
2012
+ slot.bytes = replacement;
2013
+ slot.byteCapacity = required;
2014
+ slot.byteCount = required;
2015
+ slot.generation = credential;
2016
+ slot.slotIndex = slotIndex;
2017
+ slot.ownerToken = storage_->ownerToken;
2018
+ slot.token = legacy ? credential : 0;
2019
+ slot.credentialKind = kind;
2020
+
2021
+ slot.frame = storage_->frame;
2022
+ slot.nextBodyId = storage_->nextBodyId;
2023
+ slot.nextJointId = storage_->nextJointId;
2024
+ slot.nextFluidId = storage_->nextFluidId;
2025
+ slot.bodyCount = storage_->bodyCount;
2026
+ slot.jointCount = storage_->jointCount;
2027
+ slot.fluidCount = storage_->fluidCount;
2028
+ slot.telemetryCount = storage_->telemetryCount;
2029
+ slot.breakEventCount = storage_->breakEventCount;
2030
+ slot.gearReactionCount = storage_->gearReactionCount;
2031
+ slot.activePairCount = storage_->activePairCount;
2032
+ slot.priorPairCount = storage_->priorPairCount;
2033
+ slot.contourEdgeCount = storage_->contourEdgeCount;
2034
+ slot.latestStepOptions = storage_->latestStepOptions;
2035
+ slot.currentGravity = storage_->currentGravity;
2036
+ slot.live = true;
2037
+ storage_->liveCheckpointCount += 1;
2038
+
2039
+ if (legacy) {
2040
+ storage_->legacyIds[insertion] = {credential, slotIndex};
2041
+ *legacyHandle = credential;
2042
+ } else {
2043
+ tokenOut->slotIndex = slotIndex;
2044
+ tokenOut->generation = credential;
2045
+ }
1545
2046
  return result(WorldStatus2D::Success);
1546
2047
  }
1547
2048
 
1548
- WorldResult2D World2D::restoreCheckpoint(std::uint32_t checkpointHandle) {
2049
+ WorldResult2D World2D::restoreCheckpointToken(
2050
+ std::uint32_t attachmentToken,
2051
+ std::uint32_t slotIndex,
2052
+ std::uint32_t generation) {
1549
2053
  if (!ready()) return result(WorldStatus2D::NotReady);
1550
- if (storage_->checkpoints == nullptr || checkpointHandle == 0) {
1551
- return result(WorldStatus2D::InvalidCheckpoint);
2054
+ if (!storage_->credentialValid(attachmentToken)) return result(WorldStatus2D::WorldAttached);
2055
+ if (storage_->restoreEpoch == std::numeric_limits<std::uint64_t>::max()) {
2056
+ return result(WorldStatus2D::EpochExhausted);
1552
2057
  }
1553
- const auto found = std::find_if(
1554
- storage_->checkpoints->begin(), storage_->checkpoints->end(),
1555
- [checkpointHandle](const RetainedCheckpoint2D& checkpoint) {
1556
- return checkpoint.live && checkpoint.token == checkpointHandle;
1557
- });
1558
- if (found == storage_->checkpoints->end() || found->ownerToken != storage_->ownerToken) {
2058
+
2059
+ if (!tokenCredentialMatches(slotIndex, generation)) {
1559
2060
  return result(WorldStatus2D::InvalidCheckpoint);
1560
2061
  }
2062
+ return restoreResolvedCheckpoint(slotIndex);
2063
+ }
2064
+
2065
+ bool World2D::tokenCredentialMatches(
2066
+ std::uint32_t slotIndex,
2067
+ std::uint32_t generation) const noexcept {
2068
+ if (!ready() || storage_->slots == nullptr || slotIndex >= storage_->slotCapacity) return false;
2069
+ const RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
2070
+ return slot.live
2071
+ && slot.credentialKind == CheckpointCredentialKind2D::Token
2072
+ && generation != 0
2073
+ && slot.generation == generation
2074
+ && slot.ownerToken == storage_->ownerToken;
2075
+ }
2076
+
2077
+ WorldResult2D World2D::restoreResolvedCheckpoint(std::uint32_t slotIndex) {
1561
2078
  if (storage_->restoreEpoch == std::numeric_limits<std::uint64_t>::max()) {
1562
2079
  return result(WorldStatus2D::EpochExhausted);
1563
2080
  }
1564
- const std::uint8_t* input = found->bytes;
1565
- const auto copy = [&input](void* output, std::size_t bytes) {
1566
- if (bytes != 0) {
1567
- std::memcpy(output, input, bytes);
1568
- input += bytes;
2081
+ if (storage_->mutationRevision == std::numeric_limits<std::uint64_t>::max()) {
2082
+ return result(WorldStatus2D::EpochExhausted);
2083
+ }
2084
+ const RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
2085
+ const bool emptyPayload = slot.byteCount == 0;
2086
+ if (emptyPayload) {
2087
+ if (slot.bodyCount != 0 || slot.jointCount != 0 || slot.fluidCount != 0
2088
+ || slot.telemetryCount != 0 || slot.breakEventCount != 0
2089
+ || slot.gearReactionCount != 0 || slot.activePairCount != 0
2090
+ || slot.priorPairCount != 0 || slot.contourEdgeCount != 0) {
2091
+ return result(WorldStatus2D::InvalidState);
1569
2092
  }
2093
+ } else if (slot.bytes == nullptr) {
2094
+ return result(WorldStatus2D::InvalidState);
2095
+ }
2096
+
2097
+ const std::uint8_t* input = slot.bytes;
2098
+ const auto copy = [&input](void* output, std::size_t bytes) {
2099
+ if (bytes == 0) return;
2100
+ std::memcpy(output, input, bytes);
2101
+ input += bytes;
1570
2102
  };
1571
- copy(storage_->stagedBodies, sizeof(Body) * found->bodyCount);
1572
- copy(storage_->stagedGeometries, sizeof(PolygonGeometry) * found->bodyCount);
1573
- copy(storage_->stagedJoints, sizeof(JointRecord2D) * found->jointCount);
1574
- copy(storage_->stagedJointStates, sizeof(JointState2D) * found->jointCount);
1575
- copy(storage_->stagedFluids, sizeof(FluidRegion2D) * found->fluidCount);
1576
- copy(storage_->stagedTelemetry, sizeof(JointTelemetry2D) * found->telemetryCount);
1577
- copy(storage_->stagedBreakEvents, sizeof(JointBreakEvent2D) * found->breakEventCount);
1578
- copy(storage_->stagedGearReactions, sizeof(GearReactionEntry2D) * found->gearReactionCount);
2103
+ copy(storage_->stagedBodies, sizeof(Body) * slot.bodyCount);
2104
+ copy(storage_->stagedGeometries, sizeof(PolygonGeometry) * slot.bodyCount);
2105
+ copy(storage_->stagedJoints, sizeof(JointRecord2D) * slot.jointCount);
2106
+ copy(storage_->stagedJointStates, sizeof(JointState2D) * slot.jointCount);
2107
+ copy(storage_->stagedFluids, sizeof(FluidRegion2D) * slot.fluidCount);
2108
+ copy(storage_->stagedTelemetry, sizeof(JointTelemetry2D) * slot.telemetryCount);
2109
+ copy(storage_->stagedBreakEvents, sizeof(JointBreakEvent2D) * slot.breakEventCount);
2110
+ copy(storage_->stagedGearReactions, sizeof(GearReactionEntry2D) * slot.gearReactionCount);
2111
+ copy(storage_->stagedActivePairs, sizeof(ContactEvent2D) * slot.activePairCount);
2112
+ copy(storage_->stagedPriorPairs, sizeof(ContactEvent2D) * slot.priorPairCount);
2113
+ copy(storage_->stagedContourEdges, sizeof(ContourEdge2D) * slot.contourEdgeCount);
2114
+
1579
2115
  const std::int32_t geometryStatus = setPolygonGeometry(
1580
- *storage_->stagedPhysics, storage_->stagedGeometries, found->bodyCount);
2116
+ *storage_->stagedPhysics, storage_->stagedGeometries, slot.bodyCount);
2117
+ setContourEdges(*storage_->stagedPhysics, storage_->stagedContourEdges, slot.contourEdgeCount);
1581
2118
  if (geometryStatus != kStepOk) {
1582
2119
  return result(geometryStatus == kStepWorkspaceAllocation
1583
2120
  ? WorldStatus2D::AllocationFailure : WorldStatus2D::InvalidState, geometryStatus);
1584
2121
  }
1585
- storage_->stagedBodyCount = found->bodyCount;
1586
- storage_->stagedJointCount = found->jointCount;
1587
- storage_->stagedFluidCount = found->fluidCount;
1588
- storage_->stagedTelemetryCount = found->telemetryCount;
1589
- storage_->stagedBreakEventCount = found->breakEventCount;
1590
- storage_->stagedGearReactionCount = found->gearReactionCount;
1591
- storage_->stagedFrame = found->frame;
1592
- storage_->stagedNextBodyId = found->nextBodyId;
1593
- storage_->stagedNextJointId = found->nextJointId;
1594
- storage_->stagedNextFluidId = found->nextFluidId;
1595
- storage_->stagedLatestStepOptions = found->latestStepOptions;
1596
- storage_->stagedCurrentGravity = found->currentGravity;
2122
+
2123
+ storage_->stagedBodyCount = slot.bodyCount;
2124
+ storage_->stagedJointCount = slot.jointCount;
2125
+ storage_->stagedFluidCount = slot.fluidCount;
2126
+ storage_->stagedTelemetryCount = slot.telemetryCount;
2127
+ storage_->stagedBreakEventCount = slot.breakEventCount;
2128
+ storage_->stagedGearReactionCount = slot.gearReactionCount;
2129
+ storage_->stagedActivePairCount = slot.activePairCount;
2130
+ storage_->stagedPriorPairCount = slot.priorPairCount;
2131
+ storage_->stagedContourEdgeCount = slot.contourEdgeCount;
2132
+ storage_->stagedFrame = slot.frame;
2133
+ storage_->stagedNextBodyId = slot.nextBodyId;
2134
+ storage_->stagedNextJointId = slot.nextJointId;
2135
+ storage_->stagedNextFluidId = slot.nextFluidId;
2136
+ storage_->stagedLatestStepOptions = slot.latestStepOptions;
2137
+ storage_->stagedCurrentGravity = slot.currentGravity;
1597
2138
  return commitStaged();
1598
2139
  }
1599
2140
 
1600
- WorldResult2D World2D::releaseCheckpoint(std::uint32_t checkpointHandle) {
2141
+ WorldResult2D World2D::releaseCheckpointToken(
2142
+ std::uint32_t attachmentToken,
2143
+ std::uint32_t slotIndex,
2144
+ std::uint32_t generation) {
1601
2145
  if (!ready()) return result(WorldStatus2D::NotReady);
1602
- if (storage_->checkpoints == nullptr || checkpointHandle == 0) {
2146
+ if (!storage_->credentialValid(attachmentToken)) return result(WorldStatus2D::WorldAttached);
2147
+
2148
+ if (!tokenCredentialMatches(slotIndex, generation)) {
1603
2149
  return result(WorldStatus2D::InvalidCheckpoint);
1604
2150
  }
1605
- const auto found = std::find_if(
1606
- storage_->checkpoints->begin(), storage_->checkpoints->end(),
1607
- [checkpointHandle](const RetainedCheckpoint2D& checkpoint) {
1608
- return checkpoint.live && checkpoint.token == checkpointHandle;
1609
- });
1610
- if (found == storage_->checkpoints->end() || found->ownerToken != storage_->ownerToken) {
1611
- return result(WorldStatus2D::InvalidCheckpoint);
2151
+ return releaseResolvedCheckpoint(slotIndex);
2152
+ }
2153
+
2154
+ WorldResult2D World2D::releaseResolvedCheckpoint(std::uint32_t slotIndex) {
2155
+ RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
2156
+ if (slot.credentialKind == CheckpointCredentialKind2D::Legacy) {
2157
+ if (!checkpoint_private::eraseLegacyId({storage_->legacyIds, storage_->legacyIdCapacity}, slot.token)) {
2158
+ memory_private::InstanceLedger::instance().noteImbalance();
2159
+ return result(WorldStatus2D::InvalidState);
2160
+ }
1612
2161
  }
1613
- found->live = false;
2162
+ freeInstalledPayload(slot);
2163
+ clearPublishedCredential(slot);
2164
+ slot.nextFree = storage_->firstFreeSlot;
2165
+ storage_->firstFreeSlot = slotIndex;
2166
+ if (storage_->liveCheckpointCount > 0) {
2167
+ storage_->liveCheckpointCount -= 1;
2168
+ }
2169
+ InstanceCheckpointLedger2D::instance().releaseSlot();
1614
2170
  return result(WorldStatus2D::Success);
1615
2171
  }
1616
2172
 
1617
- WorldResult2D World2D::checkpointCaptureSize(
1618
- std::uint32_t checkpointHandle,
2173
+ WorldResult2D World2D::checkpointCaptureSizeToken(
2174
+ std::uint32_t attachmentToken,
2175
+ std::uint32_t slotIndex,
2176
+ std::uint32_t generation,
1619
2177
  std::size_t* outputSize) const {
1620
2178
  if (!ready()) return result(WorldStatus2D::NotReady);
1621
- if (outputSize == nullptr || storage_->checkpoints == nullptr || checkpointHandle == 0) {
1622
- return result(WorldStatus2D::InvalidCheckpoint);
2179
+ if (!storage_->credentialValid(attachmentToken)) return result(WorldStatus2D::WorldAttached);
2180
+ if (!acceptOutput(outputSize, sizeof(*outputSize), alignof(std::size_t))) {
2181
+ return result(WorldStatus2D::InvalidArguments);
1623
2182
  }
1624
- const auto found = std::find_if(
1625
- storage_->checkpoints->begin(), storage_->checkpoints->end(),
1626
- [checkpointHandle](const RetainedCheckpoint2D& checkpoint) {
1627
- return checkpoint.live && checkpoint.token == checkpointHandle;
1628
- });
1629
- if (found == storage_->checkpoints->end() || found->ownerToken != storage_->ownerToken) {
2183
+
2184
+ if (!tokenCredentialMatches(slotIndex, generation)) {
1630
2185
  return result(WorldStatus2D::InvalidCheckpoint);
1631
2186
  }
1632
- *outputSize = snapshotSize(found->bodyCount, found->jointCount, found->fluidCount,
1633
- found->telemetryCount, found->breakEventCount, found->gearReactionCount);
2187
+ return checkpointSizeResolved(slotIndex, outputSize);
2188
+ }
2189
+
2190
+ WorldResult2D World2D::checkpointSizeResolved(
2191
+ std::uint32_t slotIndex,
2192
+ std::size_t* outputSize) const {
2193
+ const RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
2194
+ *outputSize = snapshotSize(slot.bodyCount, slot.jointCount, slot.fluidCount,
2195
+ slot.telemetryCount, slot.breakEventCount, slot.gearReactionCount,
2196
+ slot.activePairCount, slot.priorPairCount, slot.contourEdgeCount);
1634
2197
  return result(WorldStatus2D::Success);
1635
2198
  }
1636
2199
 
1637
- WorldResult2D World2D::captureCheckpointSnapshot(
1638
- std::uint32_t checkpointHandle,
2200
+ WorldResult2D World2D::captureCheckpointSnapshotToken(
2201
+ std::uint32_t attachmentToken,
2202
+ std::uint32_t slotIndex,
2203
+ std::uint32_t generation,
1639
2204
  std::uint8_t* output,
1640
2205
  std::size_t outputCapacity,
1641
2206
  std::size_t* outputSize) const {
2207
+ if (!ready()) return result(WorldStatus2D::NotReady);
2208
+ if (!storage_->credentialValid(attachmentToken)) return result(WorldStatus2D::WorldAttached);
2209
+
1642
2210
  std::size_t required = 0;
1643
- const WorldResult2D sizeResult = checkpointCaptureSize(checkpointHandle, &required);
2211
+ const WorldResult2D sizeResult = checkpointCaptureSizeToken(attachmentToken, slotIndex, generation, &required);
1644
2212
  if (!sizeResult.ok()) return sizeResult;
1645
2213
  if (outputCapacity < required) return result(WorldStatus2D::SnapshotCapacity);
1646
- if (!rangeIsValid(output, required, alignof(std::uint8_t))
1647
- || !rangeIsValid(outputSize, sizeof(*outputSize), alignof(std::size_t))) {
2214
+ const void* outputs[] = {output, outputSize};
2215
+ const std::size_t outputBytes[] = {required, sizeof(*outputSize)};
2216
+ const std::size_t outputAlign[] = {alignof(std::uint8_t), alignof(std::size_t)};
2217
+ if (!acceptOutputs(outputs, outputBytes, outputAlign, 2)) {
1648
2218
  return result(WorldStatus2D::InvalidArguments);
1649
2219
  }
1650
- const auto found = std::find_if(
1651
- storage_->checkpoints->begin(), storage_->checkpoints->end(),
1652
- [checkpointHandle](const RetainedCheckpoint2D& checkpoint) {
1653
- return checkpoint.live && checkpoint.token == checkpointHandle;
1654
- });
1655
- if (rangesOverlap(output, required, found->bytes, found->byteCount)
1656
- || rangesOverlap(outputSize, sizeof(*outputSize), found->bytes, found->byteCount)
1657
- || rangesOverlap(output, required, outputSize, sizeof(*outputSize))) {
1658
- return result(WorldStatus2D::InvalidArguments);
2220
+ return captureSnapshotResolved(slotIndex, output, required, outputSize);
2221
+ }
2222
+
2223
+ WorldResult2D World2D::captureSnapshotResolved(
2224
+ std::uint32_t slotIndex,
2225
+ std::uint8_t* output,
2226
+ std::size_t required,
2227
+ std::size_t* outputSize) const {
2228
+ const RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
2229
+ if (slot.byteCount == 0) {
2230
+ if (slot.bodyCount != 0 || slot.jointCount != 0 || slot.fluidCount != 0
2231
+ || slot.telemetryCount != 0 || slot.breakEventCount != 0
2232
+ || slot.gearReactionCount != 0 || slot.activePairCount != 0
2233
+ || slot.priorPairCount != 0 || slot.contourEdgeCount != 0) {
2234
+ return result(WorldStatus2D::InvalidState);
2235
+ }
2236
+ } else if (slot.bytes == nullptr) {
2237
+ return result(WorldStatus2D::InvalidState);
1659
2238
  }
1660
- const std::uint8_t* input = found->bytes;
1661
- const Body* bodies = reinterpret_cast<const Body*>(input);
1662
- input += sizeof(Body) * found->bodyCount;
1663
- const PolygonGeometry* geometries = reinterpret_cast<const PolygonGeometry*>(input);
1664
- input += sizeof(PolygonGeometry) * found->bodyCount;
1665
- const JointRecord2D* joints = reinterpret_cast<const JointRecord2D*>(input);
1666
- input += sizeof(JointRecord2D) * found->jointCount;
1667
- const JointState2D* jointStates = reinterpret_cast<const JointState2D*>(input);
1668
- input += sizeof(JointState2D) * found->jointCount;
1669
- const FluidRegion2D* fluids = reinterpret_cast<const FluidRegion2D*>(input);
1670
- input += sizeof(FluidRegion2D) * found->fluidCount;
1671
- const JointTelemetry2D* telemetry = reinterpret_cast<const JointTelemetry2D*>(input);
1672
- input += sizeof(JointTelemetry2D) * found->telemetryCount;
1673
- const JointBreakEvent2D* breakEvents = reinterpret_cast<const JointBreakEvent2D*>(input);
1674
- input += sizeof(JointBreakEvent2D) * found->breakEventCount;
1675
- const GearReactionEntry2D* gearReactions = reinterpret_cast<const GearReactionEntry2D*>(input);
2239
+
2240
+ const std::uint8_t* input = slot.bytes;
2241
+ const auto take = [&input](std::uint32_t count, std::size_t itemBytes) -> const void* {
2242
+ if (count == 0 || itemBytes == 0) return nullptr;
2243
+ const void* value = input;
2244
+ input += itemBytes * static_cast<std::size_t>(count);
2245
+ return value;
2246
+ };
2247
+ const auto* bodies = static_cast<const Body*>(take(slot.bodyCount, sizeof(Body)));
2248
+ const auto* geometries = static_cast<const PolygonGeometry*>(
2249
+ take(slot.bodyCount, sizeof(PolygonGeometry)));
2250
+ const auto* joints = static_cast<const JointRecord2D*>(
2251
+ take(slot.jointCount, sizeof(JointRecord2D)));
2252
+ const auto* jointStates = static_cast<const JointState2D*>(
2253
+ take(slot.jointCount, sizeof(JointState2D)));
2254
+ const auto* fluids = static_cast<const FluidRegion2D*>(
2255
+ take(slot.fluidCount, sizeof(FluidRegion2D)));
2256
+ const auto* telemetry = static_cast<const JointTelemetry2D*>(
2257
+ take(slot.telemetryCount, sizeof(JointTelemetry2D)));
2258
+ const auto* breakEvents = static_cast<const JointBreakEvent2D*>(
2259
+ take(slot.breakEventCount, sizeof(JointBreakEvent2D)));
2260
+ const auto* gearReactions = static_cast<const GearReactionEntry2D*>(
2261
+ take(slot.gearReactionCount, sizeof(GearReactionEntry2D)));
2262
+ const auto* activePairs = static_cast<const ContactEvent2D*>(
2263
+ take(slot.activePairCount, sizeof(ContactEvent2D)));
2264
+ const auto* priorPairs = static_cast<const ContactEvent2D*>(
2265
+ take(slot.priorPairCount, sizeof(ContactEvent2D)));
2266
+ const auto* contourEdges = static_cast<const ContourEdge2D*>(
2267
+ take(slot.contourEdgeCount, sizeof(ContourEdge2D)));
1676
2268
 
1677
2269
  Writer writer(output, required);
1678
2270
  bool ok = writer.u32(kOwnedWorld2DSnapshotMagic)
@@ -1682,84 +2274,223 @@ WorldResult2D World2D::captureCheckpointSnapshot(
1682
2274
  && writer.u32(config_.bodyCapacity)
1683
2275
  && writer.u32(config_.jointCapacity)
1684
2276
  && writer.u32(config_.fluidCapacity)
2277
+ && writer.u32(config_.contactCapacity)
2278
+ && writer.u32(config_.contourEdgeCapacity)
2279
+ && writer.u64(slot.frame)
2280
+ && writer.u32(slot.nextBodyId)
2281
+ && writer.u32(slot.nextJointId)
2282
+ && writer.u32(slot.nextFluidId)
2283
+ && writer.u32(slot.bodyCount)
2284
+ && writer.u32(slot.jointCount)
2285
+ && writer.u32(slot.fluidCount)
2286
+ && writer.u32(slot.telemetryCount)
2287
+ && writer.u32(slot.breakEventCount)
2288
+ && writer.u32(slot.gearReactionCount)
2289
+ && writer.u32(slot.activePairCount) && writer.u32(slot.priorPairCount)
1685
2290
  && writer.u32(0)
1686
- && writer.u64(found->frame)
1687
- && writer.u32(found->nextBodyId)
1688
- && writer.u32(found->nextJointId)
1689
- && writer.u32(found->nextFluidId)
1690
- && writer.u32(found->bodyCount)
1691
- && writer.u32(found->jointCount)
1692
- && writer.u32(found->fluidCount)
1693
- && writer.u32(found->telemetryCount)
1694
- && writer.u32(found->breakEventCount)
1695
- && writer.u32(found->gearReactionCount)
1696
- && writer.u32(0) && writer.u32(0) && writer.u32(0)
1697
- && writer.f64(found->latestStepOptions.dt)
1698
- && writer.f64(found->latestStepOptions.gravityX)
1699
- && writer.f64(found->latestStepOptions.gravityY)
1700
- && writer.u32(found->latestStepOptions.substeps)
1701
- && writer.u32(found->latestStepOptions.velocityIterations)
2291
+ && writer.f64(slot.latestStepOptions.dt)
2292
+ && writer.f64(slot.latestStepOptions.gravityX)
2293
+ && writer.f64(slot.latestStepOptions.gravityY)
2294
+ && writer.u32(slot.latestStepOptions.substeps)
2295
+ && writer.u32(slot.latestStepOptions.velocityIterations)
1702
2296
  && writer.f64(config_.fixedTiming.dt)
1703
2297
  && writer.u32(config_.fixedTiming.substeps)
1704
2298
  && writer.u32(config_.fixedTiming.velocityIterations)
1705
- && writer.f64(found->currentGravity.x)
1706
- && writer.f64(found->currentGravity.y);
1707
- for (std::uint32_t index = 0; ok && index < found->bodyCount; index += 1) {
2299
+ && writer.f64(slot.currentGravity.x)
2300
+ && writer.f64(slot.currentGravity.y);
2301
+ for (std::uint32_t index = 0; ok && index < slot.bodyCount; index += 1) {
1708
2302
  ok = writeBodyAndGeometry(writer, bodies[index], geometries[index]);
1709
2303
  }
1710
- for (std::uint32_t index = 0; ok && index < found->jointCount; index += 1) {
2304
+ for (std::uint32_t index = 0; ok && index < slot.jointCount; index += 1) {
1711
2305
  ok = writeJointRecord(writer, joints[index]);
1712
2306
  }
1713
- for (std::uint32_t index = 0; ok && index < found->jointCount; index += 1) {
2307
+ for (std::uint32_t index = 0; ok && index < slot.jointCount; index += 1) {
1714
2308
  ok = writeJointState(writer, jointStates[index]);
1715
2309
  }
1716
- for (std::uint32_t index = 0; ok && index < found->fluidCount; index += 1) {
2310
+ for (std::uint32_t index = 0; ok && index < slot.fluidCount; index += 1) {
1717
2311
  ok = writeFluid(writer, fluids[index]);
1718
2312
  }
1719
- for (std::uint32_t index = 0; ok && index < found->telemetryCount; index += 1) {
2313
+ for (std::uint32_t index = 0; ok && index < slot.telemetryCount; index += 1) {
1720
2314
  ok = writeTelemetry(writer, telemetry[index]);
1721
2315
  }
1722
- for (std::uint32_t index = 0; ok && index < found->breakEventCount; index += 1) {
2316
+ for (std::uint32_t index = 0; ok && index < slot.breakEventCount; index += 1) {
1723
2317
  ok = writeBreakEvent(writer, breakEvents[index]);
1724
2318
  }
1725
- for (std::uint32_t index = 0; ok && index < found->gearReactionCount; index += 1) {
2319
+ for (std::uint32_t index = 0; ok && index < slot.gearReactionCount; index += 1) {
1726
2320
  ok = writeGearReaction(writer, gearReactions[index]);
1727
2321
  }
2322
+ for (std::uint32_t index = 0; ok && index < slot.activePairCount; index += 1) {
2323
+ ok = writeContactPair(writer, activePairs[index]);
2324
+ }
2325
+ for (std::uint32_t index = 0; ok && index < slot.priorPairCount; index += 1) {
2326
+ ok = writeContactPair(writer, priorPairs[index]);
2327
+ }
2328
+ ok = ok && writer.u32(slot.contourEdgeCount) && writer.u32(0);
2329
+ for (std::uint32_t index = 0; ok && index < slot.contourEdgeCount; index += 1) {
2330
+ ok = writeContourEdge(writer, contourEdges[index]);
2331
+ }
1728
2332
  if (!ok || writer.position() != required) return result(WorldStatus2D::InvalidState);
1729
2333
  *outputSize = required;
1730
2334
  return result(WorldStatus2D::Success);
1731
2335
  }
1732
2336
 
2337
+ WorldResult2D World2D::captureCheckpoint(std::uint32_t* checkpointHandle) {
2338
+ if (!ready()) return result(WorldStatus2D::NotReady);
2339
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
2340
+ if (!acceptOutput(checkpointHandle, sizeof(*checkpointHandle), alignof(std::uint32_t))) {
2341
+ return result(WorldStatus2D::InvalidArguments);
2342
+ }
2343
+ return captureCheckpointCredential(
2344
+ CheckpointCredentialKind2D::Legacy, checkpointHandle, nullptr);
2345
+ }
2346
+
2347
+ WorldResult2D World2D::restoreCheckpoint(std::uint32_t checkpointHandle) {
2348
+ if (!ready()) return result(WorldStatus2D::NotReady);
2349
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
2350
+ std::uint32_t slotIndex = 0;
2351
+ std::uint32_t generation = 0;
2352
+ if (!resolveLegacyCheckpoint(checkpointHandle, slotIndex, generation) || generation == 0) {
2353
+ return result(WorldStatus2D::InvalidCheckpoint);
2354
+ }
2355
+ return restoreResolvedCheckpoint(slotIndex);
2356
+ }
2357
+
2358
+ WorldResult2D World2D::releaseCheckpoint(std::uint32_t checkpointHandle) {
2359
+ if (!ready()) return result(WorldStatus2D::NotReady);
2360
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
2361
+ std::uint32_t slotIndex = 0;
2362
+ std::uint32_t generation = 0;
2363
+ if (!resolveLegacyCheckpoint(checkpointHandle, slotIndex, generation) || generation == 0) {
2364
+ return result(WorldStatus2D::InvalidCheckpoint);
2365
+ }
2366
+ return releaseResolvedCheckpoint(slotIndex);
2367
+ }
2368
+
2369
+ WorldResult2D World2D::checkpointCaptureSize(
2370
+ std::uint32_t checkpointHandle,
2371
+ std::size_t* outputSize) const {
2372
+ if (!ready()) return result(WorldStatus2D::NotReady);
2373
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
2374
+ std::uint32_t slotIndex = 0;
2375
+ std::uint32_t generation = 0;
2376
+ if (!resolveLegacyCheckpoint(checkpointHandle, slotIndex, generation) || generation == 0) {
2377
+ return result(WorldStatus2D::InvalidCheckpoint);
2378
+ }
2379
+ if (!acceptOutput(outputSize, sizeof(*outputSize), alignof(std::size_t))) {
2380
+ return result(WorldStatus2D::InvalidArguments);
2381
+ }
2382
+ return checkpointSizeResolved(slotIndex, outputSize);
2383
+ }
2384
+
2385
+ WorldResult2D World2D::captureCheckpointSnapshot(
2386
+ std::uint32_t checkpointHandle,
2387
+ std::uint8_t* output,
2388
+ std::size_t outputCapacity,
2389
+ std::size_t* outputSize) const {
2390
+ if (!ready()) return result(WorldStatus2D::NotReady);
2391
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
2392
+ std::uint32_t slotIndex = 0;
2393
+ std::uint32_t generation = 0;
2394
+ if (!resolveLegacyCheckpoint(checkpointHandle, slotIndex, generation) || generation == 0) {
2395
+ return result(WorldStatus2D::InvalidCheckpoint);
2396
+ }
2397
+ std::size_t required = 0;
2398
+ if (!acceptOutput(outputSize, sizeof(*outputSize), alignof(std::size_t))) {
2399
+ return result(WorldStatus2D::InvalidArguments);
2400
+ }
2401
+ const WorldResult2D sized = checkpointSizeResolved(slotIndex, &required);
2402
+ if (!sized.ok()) return sized;
2403
+ if (outputCapacity < required) return result(WorldStatus2D::SnapshotCapacity);
2404
+ const void* outputs[] = {output, outputSize};
2405
+ const std::size_t outputBytes[] = {required, sizeof(*outputSize)};
2406
+ const std::size_t outputAlign[] = {alignof(std::uint8_t), alignof(std::size_t)};
2407
+ if (!acceptOutputs(outputs, outputBytes, outputAlign, 2)) {
2408
+ return result(WorldStatus2D::InvalidArguments);
2409
+ }
2410
+ return captureSnapshotResolved(slotIndex, output, required, outputSize);
2411
+ }
2412
+
2413
+ std::uint64_t World2D::mutationRevision() const noexcept {
2414
+ return ready() ? storage_->mutationRevision : 0;
2415
+ }
2416
+
2417
+ bool World2D::isAttached() const noexcept {
2418
+ return ready() ? storage_->isAttached : false;
2419
+ }
2420
+
2421
+ std::uint32_t World2D::attachmentToken() const noexcept {
2422
+ return ready() ? storage_->attachmentToken : 0;
2423
+ }
2424
+
2425
+ WorldResult2D World2D::attach(std::uint64_t expectedInitialDigest, std::uint32_t* outputToken) {
2426
+ if (!ready()) return result(WorldStatus2D::NotReady);
2427
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
2428
+ if (!acceptOutput(outputToken, sizeof(*outputToken), alignof(std::uint32_t))) {
2429
+ return result(WorldStatus2D::InvalidArguments);
2430
+ }
2431
+ if (storage_->liveCheckpointCount != 0) return result(WorldStatus2D::WorldAttached);
2432
+ if (storage_->frame != 0) return result(WorldStatus2D::InitialStateMismatch);
2433
+ std::uint64_t currentDigest = 0;
2434
+ const auto dResult = digest(&currentDigest);
2435
+ if (!dResult.ok()) return dResult;
2436
+ if (currentDigest != expectedInitialDigest) {
2437
+ return result(WorldStatus2D::InitialStateMismatch);
2438
+ }
2439
+ const std::uint32_t token = acquireAttachmentToken();
2440
+ if (token == 0) return result(WorldStatus2D::AttachmentTokenExhausted);
2441
+ storage_->isAttached = true;
2442
+ storage_->attachmentToken = token;
2443
+ *outputToken = token;
2444
+ return result(WorldStatus2D::Success);
2445
+ }
2446
+
2447
+ WorldResult2D World2D::detach(std::uint32_t token) {
2448
+ if (!ready()) return result(WorldStatus2D::NotReady);
2449
+ if (!storage_->isAttached) return result(WorldStatus2D::InvalidState);
2450
+ if (token == 0 || token != storage_->attachmentToken) {
2451
+ return result(WorldStatus2D::WorldAttached);
2452
+ }
2453
+ if (storage_->liveCheckpointCount > 0) {
2454
+ return result(WorldStatus2D::WorldAttached);
2455
+ }
2456
+ storage_->isAttached = false;
2457
+ storage_->attachmentToken = 0;
2458
+ return result(WorldStatus2D::Success);
2459
+ }
2460
+
2461
+ std::uint32_t World2D::checkpointCapacity() const noexcept {
2462
+ return ready() ? storage_->slotCapacity : 0;
2463
+ }
2464
+
2465
+ std::uint32_t World2D::checkpointLiveCount() const noexcept {
2466
+ return ready() ? storage_->liveCheckpointCount : 0;
2467
+ }
2468
+
2469
+ bool World2D::checkpointPreflight(std::uint32_t requiredSlots) const noexcept {
2470
+ if (!ready() || requiredSlots == 0) return false;
2471
+ const std::uint32_t live = storage_->liveCheckpointCount;
2472
+ const std::uint32_t cap = storage_->slotCapacity;
2473
+ if (requiredSlots > cap || live > cap - requiredSlots) return false;
2474
+ const std::uint32_t currentGen = checkpointGenerationCounter().load(std::memory_order_relaxed);
2475
+ if (currentGen == std::numeric_limits<std::uint32_t>::max()) return false;
2476
+ if (requiredSlots > std::numeric_limits<std::uint32_t>::max() - currentGen) return false;
2477
+ return true;
2478
+ }
2479
+
1733
2480
  WorldResult2D World2D::capture(
1734
2481
  std::uint8_t* output,
1735
2482
  std::size_t outputCapacity,
1736
2483
  std::size_t* outputSize) const {
1737
2484
  if (!ready()) return result(WorldStatus2D::NotReady);
2485
+ if (storage_->isAttached) return result(WorldStatus2D::WorldAttached);
1738
2486
  const std::size_t required = captureSize();
1739
2487
  if (outputCapacity < required) return result(WorldStatus2D::SnapshotCapacity);
1740
- if (!rangeIsValid(output, required, alignof(std::uint8_t))
1741
- || !rangeIsValid(outputSize, sizeof(*outputSize), alignof(std::size_t))) {
2488
+ const void* outputs[] = {output, outputSize};
2489
+ const std::size_t outputBytes[] = {required, sizeof(*outputSize)};
2490
+ const std::size_t outputAlign[] = {alignof(std::uint8_t), alignof(std::size_t)};
2491
+ if (!acceptOutputs(outputs, outputBytes, outputAlign, 2)) {
1742
2492
  return result(WorldStatus2D::InvalidArguments);
1743
2493
  }
1744
- if (rangesOverlap(output, required, outputSize, sizeof(*outputSize))) {
1745
- return result(WorldStatus2D::InvalidArguments);
1746
- }
1747
- const struct Range { const void* data; std::size_t bytes; } ranges[] = {
1748
- {storage_->bodies, sizeof(Body) * config_.bodyCapacity},
1749
- {storage_->geometries, sizeof(PolygonGeometry) * config_.bodyCapacity},
1750
- {storage_->joints, sizeof(JointRecord2D) * config_.jointCapacity},
1751
- {storage_->jointStates, sizeof(JointState2D) * config_.jointCapacity},
1752
- {storage_->fluids, sizeof(FluidRegion2D) * config_.fluidCapacity},
1753
- {storage_->telemetry, sizeof(JointTelemetry2D) * config_.jointCapacity},
1754
- {storage_->breakEvents, sizeof(JointBreakEvent2D) * config_.jointCapacity},
1755
- {storage_->gearReactions, sizeof(GearReactionEntry2D) * config_.jointCapacity * 4},
1756
- };
1757
- for (const Range& range : ranges) {
1758
- if (rangesOverlap(output, required, range.data, range.bytes)
1759
- || rangesOverlap(outputSize, sizeof(*outputSize), range.data, range.bytes)) {
1760
- return result(WorldStatus2D::InvalidArguments);
1761
- }
1762
- }
1763
2494
 
1764
2495
  Writer writer(output, required);
1765
2496
  bool ok = writer.u32(kOwnedWorld2DSnapshotMagic)
@@ -1769,7 +2500,8 @@ WorldResult2D World2D::capture(
1769
2500
  && writer.u32(config_.bodyCapacity)
1770
2501
  && writer.u32(config_.jointCapacity)
1771
2502
  && writer.u32(config_.fluidCapacity)
1772
- && writer.u32(0)
2503
+ && writer.u32(config_.contactCapacity)
2504
+ && writer.u32(config_.contourEdgeCapacity)
1773
2505
  && writer.u64(storage_->frame)
1774
2506
  && writer.u32(storage_->nextBodyId)
1775
2507
  && writer.u32(storage_->nextJointId)
@@ -1780,7 +2512,8 @@ WorldResult2D World2D::capture(
1780
2512
  && writer.u32(storage_->telemetryCount)
1781
2513
  && writer.u32(storage_->breakEventCount)
1782
2514
  && writer.u32(storage_->gearReactionCount)
1783
- && writer.u32(0) && writer.u32(0) && writer.u32(0)
2515
+ && writer.u32(storage_->activePairCount) && writer.u32(storage_->priorPairCount)
2516
+ && writer.u32(0)
1784
2517
  && writer.f64(storage_->latestStepOptions.dt)
1785
2518
  && writer.f64(storage_->latestStepOptions.gravityX)
1786
2519
  && writer.f64(storage_->latestStepOptions.gravityY)
@@ -1812,6 +2545,16 @@ WorldResult2D World2D::capture(
1812
2545
  for (std::uint32_t index = 0; ok && index < storage_->gearReactionCount; index += 1) {
1813
2546
  ok = writeGearReaction(writer, storage_->gearReactions[index]);
1814
2547
  }
2548
+ for (std::uint32_t index = 0; ok && index < storage_->activePairCount; index += 1) {
2549
+ ok = writeContactPair(writer, storage_->activePairs[index]);
2550
+ }
2551
+ for (std::uint32_t index = 0; ok && index < storage_->priorPairCount; index += 1) {
2552
+ ok = writeContactPair(writer, storage_->priorPairs[index]);
2553
+ }
2554
+ ok = ok && writer.u32(storage_->contourEdgeCount) && writer.u32(0);
2555
+ for (std::uint32_t index = 0; ok && index < storage_->contourEdgeCount; index += 1) {
2556
+ ok = writeContourEdge(writer, storage_->contourEdges[index]);
2557
+ }
1815
2558
  if (!ok || writer.position() != required) return result(WorldStatus2D::InvalidState);
1816
2559
  *outputSize = required;
1817
2560
  return result(WorldStatus2D::Success);
@@ -1819,12 +2562,16 @@ WorldResult2D World2D::capture(
1819
2562
 
1820
2563
  WorldResult2D World2D::digest(std::uint64_t* output) const {
1821
2564
  if (!ready()) return result(WorldStatus2D::NotReady);
1822
- if (output == nullptr) return result(WorldStatus2D::InvalidArguments);
2565
+ if (!acceptOutput(output, sizeof(*output), alignof(std::uint64_t))) {
2566
+ return result(WorldStatus2D::InvalidArguments);
2567
+ }
1823
2568
  std::uint64_t value = kDigestOffset;
1824
2569
  digestValue(value, config_.physicsProfile);
1825
2570
  digestValue(value, config_.bodyCapacity);
1826
2571
  digestValue(value, config_.jointCapacity);
1827
2572
  digestValue(value, config_.fluidCapacity);
2573
+ digestValue(value, config_.contactCapacity);
2574
+ digestValue(value, config_.contourEdgeCapacity);
1828
2575
  digestValue(value, config_.fixedTiming);
1829
2576
  digestValue(value, storage_->frame);
1830
2577
  digestValue(value, storage_->nextBodyId);
@@ -1836,6 +2583,8 @@ WorldResult2D World2D::digest(std::uint64_t* output) const {
1836
2583
  digestValue(value, storage_->telemetryCount);
1837
2584
  digestValue(value, storage_->breakEventCount);
1838
2585
  digestValue(value, storage_->gearReactionCount);
2586
+ digestValue(value, storage_->activePairCount);
2587
+ digestValue(value, storage_->priorPairCount);
1839
2588
  digestValue(value, storage_->latestStepOptions);
1840
2589
  digestValue(value, storage_->currentGravity);
1841
2590
  digestBytes(value, storage_->bodies, sizeof(Body) * storage_->bodyCount);
@@ -1847,32 +2596,38 @@ WorldResult2D World2D::digest(std::uint64_t* output) const {
1847
2596
  digestBytes(value, storage_->breakEvents, sizeof(JointBreakEvent2D) * storage_->breakEventCount);
1848
2597
  digestBytes(value, storage_->gearReactions,
1849
2598
  sizeof(GearReactionEntry2D) * storage_->gearReactionCount);
2599
+ digestBytes(value, storage_->activePairs,
2600
+ sizeof(ContactEvent2D) * storage_->activePairCount);
2601
+ digestBytes(value, storage_->priorPairs,
2602
+ sizeof(ContactEvent2D) * storage_->priorPairCount);
2603
+ digestValue(value, storage_->contourEdgeCount);
2604
+ digestBytes(value, storage_->contourEdges,
2605
+ sizeof(ContourEdge2D) * storage_->contourEdgeCount);
1850
2606
  *output = value == 0 ? kDigestOffset : value;
1851
2607
  return result(WorldStatus2D::Success);
1852
2608
  }
1853
2609
 
1854
2610
  WorldResult2D World2D::restore(const std::uint8_t* bytes, std::size_t byteCount) {
2611
+ return restoreAuthorized(bytes, byteCount, 0);
2612
+ }
2613
+
2614
+ WorldResult2D World2D::restoreAuthorized(
2615
+ const std::uint8_t* bytes,
2616
+ std::size_t byteCount,
2617
+ std::uint32_t attachmentToken) {
1855
2618
  if (!ready()) return result(WorldStatus2D::NotReady);
2619
+ if (!storage_->credentialValid(attachmentToken)) return result(WorldStatus2D::WorldAttached);
1856
2620
  if (byteCount < kOwnedWorld2DSnapshotHeaderBytes) {
2621
+ if (rangeIsValid(bytes, byteCount, alignof(std::uint8_t)) && storageOverlaps(bytes, byteCount)) {
2622
+ return result(WorldStatus2D::InvalidArguments);
2623
+ }
1857
2624
  return result(WorldStatus2D::SnapshotTruncated);
1858
2625
  }
1859
2626
  if (!rangeIsValid(bytes, byteCount, alignof(std::uint8_t))) {
1860
2627
  return result(WorldStatus2D::InvalidArguments);
1861
2628
  }
1862
- const struct Range { const void* data; std::size_t bytes; } ranges[] = {
1863
- {storage_->bodies, sizeof(Body) * config_.bodyCapacity},
1864
- {storage_->geometries, sizeof(PolygonGeometry) * config_.bodyCapacity},
1865
- {storage_->joints, sizeof(JointRecord2D) * config_.jointCapacity},
1866
- {storage_->jointStates, sizeof(JointState2D) * config_.jointCapacity},
1867
- {storage_->fluids, sizeof(FluidRegion2D) * config_.fluidCapacity},
1868
- {storage_->telemetry, sizeof(JointTelemetry2D) * config_.jointCapacity},
1869
- {storage_->breakEvents, sizeof(JointBreakEvent2D) * config_.jointCapacity},
1870
- {storage_->gearReactions, sizeof(GearReactionEntry2D) * config_.jointCapacity * 4},
1871
- };
1872
- for (const Range& range : ranges) {
1873
- if (rangesOverlap(bytes, byteCount, range.data, range.bytes)) {
1874
- return result(WorldStatus2D::InvalidArguments);
1875
- }
2629
+ if (storageOverlaps(bytes, byteCount)) {
2630
+ return result(WorldStatus2D::InvalidArguments);
1876
2631
  }
1877
2632
 
1878
2633
  Reader reader(bytes, byteCount);
@@ -1883,21 +2638,22 @@ WorldResult2D World2D::restore(const std::uint8_t* bytes, std::size_t byteCount)
1883
2638
  std::uint32_t bodyCapacity = 0;
1884
2639
  std::uint32_t jointCapacity = 0;
1885
2640
  std::uint32_t fluidCapacity = 0;
1886
- std::uint32_t reserved0 = 0;
2641
+ std::uint32_t contactCapacity = 0;
2642
+ std::uint32_t contourEdgeCapacity = 0;
1887
2643
  WorldState2DView candidate{};
1888
2644
  FixedStepTiming2D capturedTiming{};
1889
- std::uint32_t reserved1 = 0;
1890
- std::uint32_t reserved2 = 0;
2645
+ std::uint32_t activePairCount = 0;
2646
+ std::uint32_t priorPairCount = 0;
1891
2647
  std::uint32_t reserved3 = 0;
1892
2648
  if (!reader.u32(magic) || !reader.u32(snapshotVersion) || !reader.u32(worldAbi)
1893
2649
  || !reader.u32(profile) || !reader.u32(bodyCapacity) || !reader.u32(jointCapacity)
1894
- || !reader.u32(fluidCapacity) || !reader.u32(reserved0) || !reader.u64(candidate.frame)
2650
+ || !reader.u32(fluidCapacity) || !reader.u32(contactCapacity) || !reader.u32(contourEdgeCapacity) || !reader.u64(candidate.frame)
1895
2651
  || !reader.u32(candidate.nextBodyId) || !reader.u32(candidate.nextJointId)
1896
2652
  || !reader.u32(candidate.nextFluidId) || !reader.u32(candidate.bodyCount)
1897
2653
  || !reader.u32(candidate.jointCount) || !reader.u32(candidate.fluidCount)
1898
2654
  || !reader.u32(candidate.telemetryCount) || !reader.u32(candidate.breakEventCount)
1899
- || !reader.u32(candidate.gearReactionCount) || !reader.u32(reserved1)
1900
- || !reader.u32(reserved2) || !reader.u32(reserved3)
2655
+ || !reader.u32(candidate.gearReactionCount) || !reader.u32(activePairCount)
2656
+ || !reader.u32(priorPairCount) || !reader.u32(reserved3)
1901
2657
  || !reader.f64(candidate.latestStepOptions.dt)
1902
2658
  || !reader.f64(candidate.latestStepOptions.gravityX)
1903
2659
  || !reader.f64(candidate.latestStepOptions.gravityY)
@@ -1916,10 +2672,11 @@ WorldResult2D World2D::restore(const std::uint8_t* bytes, std::size_t byteCount)
1916
2672
  }
1917
2673
  if (profile != config_.physicsProfile) return result(WorldStatus2D::SnapshotProfileMismatch);
1918
2674
  if (bodyCapacity != config_.bodyCapacity || jointCapacity != config_.jointCapacity
1919
- || fluidCapacity != config_.fluidCapacity) {
2675
+ || fluidCapacity != config_.fluidCapacity || contactCapacity != config_.contactCapacity
2676
+ || contourEdgeCapacity != config_.contourEdgeCapacity) {
1920
2677
  return result(WorldStatus2D::SnapshotCapacityMismatch);
1921
2678
  }
1922
- if (reserved0 != 0 || reserved1 != 0 || reserved2 != 0 || reserved3 != 0) {
2679
+ if (reserved3 != 0) {
1923
2680
  return result(WorldStatus2D::SnapshotMalformed);
1924
2681
  }
1925
2682
  if (!validOptions(candidate.latestStepOptions)
@@ -1934,14 +2691,17 @@ WorldResult2D World2D::restore(const std::uint8_t* bytes, std::size_t byteCount)
1934
2691
  || candidate.fluidCount > config_.fluidCapacity
1935
2692
  || candidate.telemetryCount > config_.jointCapacity
1936
2693
  || candidate.breakEventCount > config_.jointCapacity
1937
- || candidate.gearReactionCount > static_cast<std::uint64_t>(config_.jointCapacity) * 4) {
2694
+ || candidate.gearReactionCount > static_cast<std::uint64_t>(config_.jointCapacity) * 4
2695
+ || activePairCount > config_.contactCapacity || priorPairCount > config_.contactCapacity) {
1938
2696
  return result(WorldStatus2D::SnapshotMalformed);
1939
2697
  }
1940
- const std::size_t expected = snapshotSize(candidate.bodyCount, candidate.jointCount,
2698
+ const std::size_t minExpected = snapshotSize(candidate.bodyCount, candidate.jointCount,
1941
2699
  candidate.fluidCount, candidate.telemetryCount, candidate.breakEventCount,
1942
- candidate.gearReactionCount);
1943
- if (byteCount < expected) return result(WorldStatus2D::SnapshotTruncated);
1944
- if (byteCount != expected) return result(WorldStatus2D::SnapshotMalformed);
2700
+ candidate.gearReactionCount, activePairCount, priorPairCount, 0);
2701
+ if (byteCount < minExpected) return result(WorldStatus2D::SnapshotTruncated);
2702
+ if (storage_->mutationRevision == std::numeric_limits<std::uint64_t>::max()) {
2703
+ return result(WorldStatus2D::EpochExhausted);
2704
+ }
1945
2705
 
1946
2706
  for (std::uint32_t index = 0; index < candidate.bodyCount; index += 1) {
1947
2707
  if (!readBodyAndGeometry(reader, storage_->stagedBodies[index],
@@ -1977,6 +2737,37 @@ WorldResult2D World2D::restore(const std::uint8_t* bytes, std::size_t byteCount)
1977
2737
  return result(WorldStatus2D::SnapshotMalformed);
1978
2738
  }
1979
2739
  }
2740
+ for (std::uint32_t index = 0; index < activePairCount; index += 1) {
2741
+ if (!readContactPair(reader, storage_->stagedActivePairs[index])) {
2742
+ return result(WorldStatus2D::SnapshotMalformed);
2743
+ }
2744
+ }
2745
+ for (std::uint32_t index = 0; index < priorPairCount; index += 1) {
2746
+ if (!readContactPair(reader, storage_->stagedPriorPairs[index])) {
2747
+ return result(WorldStatus2D::SnapshotMalformed);
2748
+ }
2749
+ }
2750
+
2751
+ std::uint32_t contourEdgeCount = 0;
2752
+ std::uint32_t contourReserved = 0;
2753
+ if (!reader.u32(contourEdgeCount) || !reader.u32(contourReserved)) {
2754
+ return result(byteCount < reader.position() ? WorldStatus2D::SnapshotTruncated : WorldStatus2D::SnapshotMalformed);
2755
+ }
2756
+ if (contourReserved != 0 || contourEdgeCount > config_.contourEdgeCapacity) {
2757
+ return result(WorldStatus2D::SnapshotMalformed);
2758
+ }
2759
+ const std::size_t expected = snapshotSize(candidate.bodyCount, candidate.jointCount,
2760
+ candidate.fluidCount, candidate.telemetryCount, candidate.breakEventCount,
2761
+ candidate.gearReactionCount, activePairCount, priorPairCount, contourEdgeCount);
2762
+ if (byteCount < expected) return result(WorldStatus2D::SnapshotTruncated);
2763
+ if (byteCount != expected) return result(WorldStatus2D::SnapshotMalformed);
2764
+
2765
+ for (std::uint32_t index = 0; index < contourEdgeCount; index += 1) {
2766
+ if (!readContourEdge(reader, storage_->stagedContourEdges[index])) {
2767
+ return result(WorldStatus2D::SnapshotMalformed);
2768
+ }
2769
+ }
2770
+ storage_->stagedContourEdgeCount = contourEdgeCount;
1980
2771
  if (reader.remaining() != 0) return result(WorldStatus2D::SnapshotMalformed);
1981
2772
 
1982
2773
  candidate.bodies = storage_->stagedBodies;
@@ -1987,6 +2778,12 @@ WorldResult2D World2D::restore(const std::uint8_t* bytes, std::size_t byteCount)
1987
2778
  candidate.telemetry = storage_->stagedTelemetry;
1988
2779
  candidate.breakEvents = storage_->stagedBreakEvents;
1989
2780
  candidate.gearReactions = storage_->stagedGearReactions;
2781
+ candidate.activePairs = storage_->stagedActivePairs;
2782
+ candidate.activePairCount = activePairCount;
2783
+ candidate.priorPairs = storage_->stagedPriorPairs;
2784
+ candidate.priorPairCount = priorPairCount;
2785
+ candidate.contourEdges = storage_->stagedContourEdges;
2786
+ candidate.contourEdgeCount = contourEdgeCount;
1990
2787
  return replaceState(candidate);
1991
2788
  }
1992
2789
 
@@ -1999,6 +2796,8 @@ bool queryAliasesAuthoritative(
1999
2796
  const JointTelemetry2D* telemetry,
2000
2797
  const JointBreakEvent2D* breakEvents,
2001
2798
  const GearReactionEntry2D* gearReactions,
2799
+ const ContactEvent2D* activePairs,
2800
+ const ContactEvent2D* priorPairs,
2002
2801
  const Request* request,
2003
2802
  const QueryFilter2D* filter,
2004
2803
  const std::uint32_t* excludedIds,
@@ -2030,6 +2829,8 @@ bool queryAliasesAuthoritative(
2030
2829
  {telemetry, sizeof(JointTelemetry2D) * config.jointCapacity},
2031
2830
  {breakEvents, sizeof(JointBreakEvent2D) * config.jointCapacity},
2032
2831
  {gearReactions, sizeof(GearReactionEntry2D) * config.jointCapacity * 4},
2832
+ {activePairs, sizeof(ContactEvent2D) * config.contactCapacity},
2833
+ {priorPairs, sizeof(ContactEvent2D) * config.contactCapacity},
2033
2834
  };
2034
2835
  for (const Range& first : external) {
2035
2836
  for (const Range& second : authoritative) {
@@ -2049,10 +2850,13 @@ std::int32_t World2D::raycast(
2049
2850
  if (!ready()) return static_cast<std::int32_t>(QueryStatus2D::InvalidArguments);
2050
2851
  if (queryAliasesAuthoritative(config_, storage_->joints, storage_->jointStates,
2051
2852
  storage_->fluids, storage_->telemetry, storage_->breakEvents,
2052
- storage_->gearReactions, request, filter, excludedIds, output,
2853
+ storage_->gearReactions, storage_->activePairs, storage_->priorPairs,
2854
+ request, filter, excludedIds, output,
2053
2855
  outputCapacity, outputCount)) {
2054
2856
  return static_cast<std::int32_t>(QueryStatus2D::AliasedBuffers);
2055
2857
  }
2858
+ storage_->query->contourEdges = storage_->contourEdges;
2859
+ storage_->query->contourEdgeCount = storage_->contourEdgeCount;
2056
2860
  return rundot_physics2d_raycast(storage_->query, storage_->bodies, storage_->bodyCount,
2057
2861
  storage_->geometries, storage_->bodyCount, request, filter, excludedIds,
2058
2862
  output, outputCapacity, outputCount);
@@ -2068,15 +2872,43 @@ std::int32_t World2D::overlap(
2068
2872
  if (!ready()) return static_cast<std::int32_t>(QueryStatus2D::InvalidArguments);
2069
2873
  if (queryAliasesAuthoritative(config_, storage_->joints, storage_->jointStates,
2070
2874
  storage_->fluids, storage_->telemetry, storage_->breakEvents,
2071
- storage_->gearReactions, request, filter, excludedIds, output,
2875
+ storage_->gearReactions, storage_->activePairs, storage_->priorPairs,
2876
+ request, filter, excludedIds, output,
2072
2877
  outputCapacity, outputCount)) {
2073
2878
  return static_cast<std::int32_t>(QueryStatus2D::AliasedBuffers);
2074
2879
  }
2880
+ storage_->query->contourEdges = storage_->contourEdges;
2881
+ storage_->query->contourEdgeCount = storage_->contourEdgeCount;
2075
2882
  return rundot_physics2d_overlap(storage_->query, storage_->bodies, storage_->bodyCount,
2076
2883
  storage_->geometries, storage_->bodyCount, request, filter, excludedIds,
2077
2884
  output, outputCapacity, outputCount);
2078
2885
  }
2079
2886
 
2887
+ std::int32_t World2D::overlapContacts(
2888
+ const OverlapQuery2D* request,
2889
+ const QueryFilter2D* filter,
2890
+ const std::uint32_t* excludedIds,
2891
+ OverlapContactHit2D* output,
2892
+ std::uint32_t outputCapacity,
2893
+ std::uint32_t* outputCount) {
2894
+ if (!ready()) return static_cast<std::int32_t>(QueryStatus2D::InvalidArguments);
2895
+ if (queryAliasesAuthoritative(config_, storage_->joints, storage_->jointStates,
2896
+ storage_->fluids, storage_->telemetry, storage_->breakEvents,
2897
+ storage_->gearReactions, storage_->activePairs, storage_->priorPairs,
2898
+ request, filter, excludedIds, output,
2899
+ outputCapacity, outputCount)) {
2900
+ return static_cast<std::int32_t>(QueryStatus2D::AliasedBuffers);
2901
+ }
2902
+ storage_->query->contourEdges = storage_->contourEdges;
2903
+ storage_->query->contourEdgeCount = storage_->contourEdgeCount;
2904
+ setContourGeometry(nullptr, 0, storage_->contourEdges, storage_->contourEdgeCount);
2905
+ const auto status = rundot_physics2d_overlap_contacts(storage_->query, storage_->bodies, storage_->bodyCount,
2906
+ storage_->geometries, storage_->bodyCount, request, filter, excludedIds,
2907
+ output, outputCapacity, outputCount);
2908
+ setContourGeometry(nullptr, 0, nullptr, 0);
2909
+ return status;
2910
+ }
2911
+
2080
2912
  std::int32_t World2D::shapeCast(
2081
2913
  const ShapeCastQuery2D* request,
2082
2914
  const QueryFilter2D* filter,
@@ -2087,10 +2919,13 @@ std::int32_t World2D::shapeCast(
2087
2919
  if (!ready()) return static_cast<std::int32_t>(QueryStatus2D::InvalidArguments);
2088
2920
  if (queryAliasesAuthoritative(config_, storage_->joints, storage_->jointStates,
2089
2921
  storage_->fluids, storage_->telemetry, storage_->breakEvents,
2090
- storage_->gearReactions, request, filter, excludedIds, output,
2922
+ storage_->gearReactions, storage_->activePairs, storage_->priorPairs,
2923
+ request, filter, excludedIds, output,
2091
2924
  outputCapacity, outputCount)) {
2092
2925
  return static_cast<std::int32_t>(QueryStatus2D::AliasedBuffers);
2093
2926
  }
2927
+ storage_->query->contourEdges = storage_->contourEdges;
2928
+ storage_->query->contourEdgeCount = storage_->contourEdgeCount;
2094
2929
  return rundot_physics2d_shape_cast(storage_->query, storage_->bodies, storage_->bodyCount,
2095
2930
  storage_->geometries, storage_->bodyCount, request, filter, excludedIds,
2096
2931
  output, outputCapacity, outputCount);
@@ -2106,10 +2941,13 @@ std::int32_t World2D::closestPoints(
2106
2941
  if (!ready()) return static_cast<std::int32_t>(QueryStatus2D::InvalidArguments);
2107
2942
  if (queryAliasesAuthoritative(config_, storage_->joints, storage_->jointStates,
2108
2943
  storage_->fluids, storage_->telemetry, storage_->breakEvents,
2109
- storage_->gearReactions, request, filter, excludedIds, output,
2944
+ storage_->gearReactions, storage_->activePairs, storage_->priorPairs,
2945
+ request, filter, excludedIds, output,
2110
2946
  outputCapacity, outputCount)) {
2111
2947
  return static_cast<std::int32_t>(QueryStatus2D::AliasedBuffers);
2112
2948
  }
2949
+ storage_->query->contourEdges = storage_->contourEdges;
2950
+ storage_->query->contourEdgeCount = storage_->contourEdgeCount;
2113
2951
  return rundot_physics2d_closest_points(storage_->query, storage_->bodies, storage_->bodyCount,
2114
2952
  storage_->geometries, storage_->bodyCount, request, filter, excludedIds,
2115
2953
  output, outputCapacity, outputCount);
@@ -2117,12 +2955,31 @@ std::int32_t World2D::closestPoints(
2117
2955
 
2118
2956
  void World2D::release() {
2119
2957
  if (storage_ == nullptr) return;
2120
- if (storage_->checkpoints != nullptr) {
2121
- for (RetainedCheckpoint2D& checkpoint : *storage_->checkpoints) {
2122
- freePod(checkpoint.bytes);
2958
+ storage_->isAttached = false;
2959
+ storage_->attachmentToken = 0;
2960
+ if (storage_->physics != nullptr) clock_private::Access::expireOwner(*storage_->physics);
2961
+ if (storage_->stagedPhysics != nullptr) clock_private::Access::expireOwner(*storage_->stagedPhysics);
2962
+ if (storage_->slots != nullptr) {
2963
+ for (std::uint32_t i = 0; i < storage_->slotCapacity; ++i) {
2964
+ if (storage_->slots[i].bytes != nullptr) {
2965
+ freeInstalledPayload(storage_->slots[i]);
2966
+ }
2967
+ if (storage_->slots[i].live) {
2968
+ InstanceCheckpointLedger2D::instance().releaseSlot();
2969
+ storage_->slots[i].live = false;
2970
+ }
2123
2971
  }
2124
- delete storage_->checkpoints;
2972
+ freePod(storage_->slots);
2973
+ storage_->slots = nullptr;
2974
+ storage_->slotCapacity = 0;
2975
+ }
2976
+ if (storage_->registered) {
2977
+ storage_->registered = false;
2978
+ InstanceCheckpointLedger2D::instance().unregisterWorld();
2125
2979
  }
2980
+ freePod(storage_->legacyIds);
2981
+ storage_->legacyIds = nullptr;
2982
+ storage_->legacyIdCapacity = 0;
2126
2983
  freePod(storage_->bodies);
2127
2984
  freePod(storage_->stagedBodies);
2128
2985
  freePod(storage_->geometries);
@@ -2139,12 +2996,115 @@ void World2D::release() {
2139
2996
  freePod(storage_->stagedBreakEvents);
2140
2997
  freePod(storage_->gearReactions);
2141
2998
  freePod(storage_->stagedGearReactions);
2142
- delete storage_->physics;
2143
- delete storage_->stagedPhysics;
2144
- delete storage_->solver;
2999
+ freePod(storage_->activePairs);
3000
+ freePod(storage_->stagedActivePairs);
3001
+ freePod(storage_->priorPairs);
3002
+ freePod(storage_->stagedPriorPairs);
3003
+ freePod(storage_->disabledPairs);
3004
+ freePod(storage_->contourEdges);
3005
+ freePod(storage_->stagedContourEdges);
3006
+ memory_private::deallocateObject(storage_->physics);
3007
+ memory_private::deallocateObject(storage_->stagedPhysics);
3008
+ memory_private::deallocateObject(storage_->solver);
2145
3009
  freePod(storage_->query);
2146
- delete storage_;
3010
+ memory_private::deallocateObject(storage_);
2147
3011
  storage_ = nullptr;
2148
3012
  }
2149
3013
 
3014
+
3015
+ std::size_t World2D::contourEdgeCount() const noexcept {
3016
+ return ready() ? storage_->contourEdgeCount : 0;
3017
+ }
3018
+
3019
+ WorldResult2D World2D::readContourEdges(
3020
+ std::uint32_t bodyId,
3021
+ ContourEdge2D* output,
3022
+ std::uint32_t capacity,
3023
+ std::uint32_t* outputCount) const noexcept {
3024
+ if (!ready()) return result(WorldStatus2D::NotReady);
3025
+ if (output == nullptr || outputCount == nullptr) {
3026
+ return result(WorldStatus2D::InvalidArguments);
3027
+ }
3028
+ const auto it = std::find_if(storage_->bodies, storage_->bodies + storage_->bodyCount,
3029
+ [bodyId](const Body& b) { return b.id == bodyId; });
3030
+ if (it == storage_->bodies + storage_->bodyCount) {
3031
+ return result(WorldStatus2D::InvalidArguments);
3032
+ }
3033
+ const std::size_t bodyIndex = it - storage_->bodies;
3034
+ if (it->shape != ShapeType::Contour) {
3035
+ *outputCount = 0;
3036
+ return result(WorldStatus2D::Success);
3037
+ }
3038
+ ContourHeader2D header{};
3039
+ std::memcpy(&header, &storage_->geometries[bodyIndex], sizeof(header));
3040
+ if (header.tag != kContourHeaderTag) {
3041
+ return result(WorldStatus2D::InvalidState);
3042
+ }
3043
+ const std::uint32_t totalRecords = header.reserved != 0 ? header.reserved : header.edgeCount;
3044
+ if (capacity < totalRecords) {
3045
+ return result(WorldStatus2D::CapacityExceeded);
3046
+ }
3047
+ if (header.firstEdge + totalRecords > storage_->contourEdgeCount) {
3048
+ return result(WorldStatus2D::InvalidState);
3049
+ }
3050
+ std::memcpy(output, &storage_->contourEdges[header.firstEdge], totalRecords * sizeof(ContourEdge2D));
3051
+ *outputCount = totalRecords;
3052
+ return result(WorldStatus2D::Success);
3053
+ }
3054
+
3055
+ #ifdef RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS
3056
+ bool World2D::debugAdvanceMutationRevisionForTest(std::uint64_t value) noexcept {
3057
+ if (!ready()) return false;
3058
+ if (value < storage_->mutationRevision) return false;
3059
+ storage_->mutationRevision = value;
3060
+ return true;
3061
+ }
3062
+
3063
+ const std::uint8_t* World2D::debugSlotPayloadForTest(
3064
+ std::uint32_t slotIndex,
3065
+ std::size_t* bytes) const noexcept {
3066
+ if (!ready() || bytes == nullptr || storage_->slots == nullptr
3067
+ || slotIndex >= storage_->slotCapacity) {
3068
+ return nullptr;
3069
+ }
3070
+ *bytes = storage_->slots[slotIndex].byteCapacity;
3071
+ return storage_->slots[slotIndex].bytes;
3072
+ }
3073
+
3074
+ bool World2D::debugSlotCredentialForTest(
3075
+ std::uint32_t slotIndex,
3076
+ std::uint32_t* generation,
3077
+ std::uint32_t* legacyCredential,
3078
+ std::uint8_t* kind) const noexcept {
3079
+ if (!ready() || storage_->slots == nullptr || slotIndex >= storage_->slotCapacity) return false;
3080
+ if (generation == nullptr || legacyCredential == nullptr || kind == nullptr) return false;
3081
+ const RetainedCheckpointSlot2D& slot = storage_->slots[slotIndex];
3082
+ *generation = slot.generation;
3083
+ *legacyCredential = slot.token;
3084
+ *kind = static_cast<std::uint8_t>(slot.credentialKind);
3085
+ return true;
3086
+ }
3087
+
3088
+ const void* World2D::debugStagedRangeForTest(std::uint32_t index, std::size_t* bytes) const noexcept {
3089
+ if (!ready() || bytes == nullptr) return nullptr;
3090
+ const struct Range { const void* data; std::size_t bytes; } ranges[] = {
3091
+ {storage_->stagedBodies, sizeof(Body) * config_.bodyCapacity},
3092
+ {storage_->stagedGeometries, sizeof(PolygonGeometry) * config_.bodyCapacity},
3093
+ {storage_->stagedJoints, sizeof(JointRecord2D) * config_.jointCapacity},
3094
+ {storage_->stagedJointStates, sizeof(JointState2D) * config_.jointCapacity},
3095
+ {storage_->stagedFluids, sizeof(FluidRegion2D) * config_.fluidCapacity},
3096
+ {storage_->stagedTelemetry, sizeof(JointTelemetry2D) * config_.jointCapacity},
3097
+ {storage_->stagedBreakEvents, sizeof(JointBreakEvent2D) * config_.jointCapacity},
3098
+ {storage_->stagedGearReactions, sizeof(GearReactionEntry2D) * config_.jointCapacity * 4},
3099
+ {storage_->stagedActivePairs, sizeof(ContactEvent2D) * config_.contactCapacity},
3100
+ {storage_->stagedPriorPairs, sizeof(ContactEvent2D) * config_.contactCapacity},
3101
+ {storage_->stagedContourEdges, sizeof(ContourEdge2D) * config_.contourEdgeCapacity},
3102
+ {storage_->stagedPhysics, sizeof(PhysicsContext2D)},
3103
+ };
3104
+ if (index >= std::size(ranges)) return nullptr;
3105
+ *bytes = ranges[index].bytes;
3106
+ return ranges[index].data;
3107
+ }
3108
+ #endif
3109
+
2150
3110
  } // namespace rundot::kinetix::physics2d