@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
@@ -0,0 +1,1302 @@
1
+ #include "ccd.hpp"
2
+ #include "contour.hpp"
3
+ #include <algorithm>
4
+ #include <cmath>
5
+ #include <cstdint>
6
+ #include <cstring>
7
+ #include <limits>
8
+
9
+ namespace rundot::kinetix::physics2d {
10
+
11
+ namespace {
12
+
13
+ constexpr double kEpsilon = 1e-12;
14
+
15
+ inline Vec2 add(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
16
+ inline Vec2 sub(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
17
+ inline Vec2 scale(Vec2 a, double s) { return {a.x * s, a.y * s}; }
18
+ inline double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
19
+ inline double cross(Vec2 a, Vec2 b) { return a.x * b.y - a.y * b.x; }
20
+ inline double lengthSq(Vec2 a) { return a.x * a.x + a.y * a.y; }
21
+ inline double length(Vec2 a) { return std::sqrt(std::max(0.0, lengthSq(a))); }
22
+
23
+ inline Vec2 normalize(Vec2 a, Vec2 fallback = {1.0, 0.0}) {
24
+ if (std::abs(a.y) <= kEpsilon * std::abs(a.x) && a.x != 0.0) {
25
+ return {a.x < 0.0 ? -1.0 : 1.0, 0.0};
26
+ }
27
+ if (std::abs(a.x) <= kEpsilon * std::abs(a.y) && a.y != 0.0) {
28
+ return {0.0, a.y < 0.0 ? -1.0 : 1.0};
29
+ }
30
+ const double len = length(a);
31
+ return len > kEpsilon ? scale(a, 1.0 / len) : fallback;
32
+ }
33
+
34
+ inline double clamp(double value, double low, double high) {
35
+ return std::max(low, std::min(high, value));
36
+ }
37
+
38
+ // Distance from point p to line segment [a, b], with closest point on segment.
39
+ double pointToSegmentDistance(Vec2 p, Vec2 a, Vec2 b, Vec2& closest) {
40
+ const Vec2 ab = sub(b, a);
41
+ const double l2 = lengthSq(ab);
42
+ if (l2 <= 1e-14) {
43
+ closest = a;
44
+ return length(sub(p, a));
45
+ }
46
+ const double t = clamp(dot(sub(p, a), ab) / l2, 0.0, 1.0);
47
+ closest = add(a, scale(ab, t));
48
+ return length(sub(p, closest));
49
+ }
50
+
51
+ // Distance between two line segments [a1, b1] and [a2, b2].
52
+ double segmentToSegmentDistance(Vec2 a1, Vec2 b1, Vec2 a2, Vec2 b2, Vec2& closest1, Vec2& closest2) {
53
+ // Check if segments strictly intersect
54
+ const double cp1 = cross(sub(b1, a1), sub(a2, a1));
55
+ const double cp2 = cross(sub(b1, a1), sub(b2, a1));
56
+ const double cp3 = cross(sub(b2, a2), sub(a1, a2));
57
+ const double cp4 = cross(sub(b2, a2), sub(b1, a2));
58
+
59
+ if (((cp1 > 1e-9 && cp2 < -1e-9) || (cp1 < -1e-9 && cp2 > 1e-9)) &&
60
+ ((cp3 > 1e-9 && cp4 < -1e-9) || (cp3 < -1e-9 && cp4 > 1e-9))) {
61
+ // Intersecting: find intersection point
62
+ const double num = cross(sub(a2, a1), sub(b2, a2));
63
+ const double den = cross(sub(b1, a1), sub(b2, a2));
64
+ const double t = den != 0.0 ? num / den : 0.0;
65
+ closest1 = add(a1, scale(sub(b1, a1), clamp(t, 0.0, 1.0)));
66
+ closest2 = closest1;
67
+ return 0.0;
68
+ }
69
+
70
+ // Non-intersecting: minimum of endpoint-to-segment distances
71
+ Vec2 cCandidate;
72
+ double minD = std::numeric_limits<double>::infinity();
73
+
74
+ // a1 to [a2, b2]
75
+ double d = pointToSegmentDistance(a1, a2, b2, cCandidate);
76
+ if (d < minD) { minD = d; closest1 = a1; closest2 = cCandidate; }
77
+
78
+ // b1 to [a2, b2]
79
+ d = pointToSegmentDistance(b1, a2, b2, cCandidate);
80
+ if (d < minD) { minD = d; closest1 = b1; closest2 = cCandidate; }
81
+
82
+ // a2 to [a1, b1]
83
+ d = pointToSegmentDistance(a2, a1, b1, cCandidate);
84
+ if (d < minD) { minD = d; closest1 = cCandidate; closest2 = a2; }
85
+
86
+ // b2 to [a1, b1]
87
+ d = pointToSegmentDistance(b2, a1, b1, cCandidate);
88
+ if (d < minD) { minD = d; closest1 = cCandidate; closest2 = b2; }
89
+
90
+ return minD;
91
+ }
92
+
93
+ // Distance from point p to convex polygon vertices in CCW order.
94
+ double pointToPolygonDistance(Vec2 p, const Vec2* verts, std::uint32_t count, Vec2& closest) {
95
+ if (count == 0) { closest = p; return 0.0; }
96
+ if (count == 1) { closest = verts[0]; return length(sub(p, verts[0])); }
97
+ if (count == 2) { return pointToSegmentDistance(p, verts[0], verts[1], closest); }
98
+
99
+ bool inside = true;
100
+ double minEdgeDist = std::numeric_limits<double>::infinity();
101
+ Vec2 bestPoint = verts[0];
102
+
103
+ for (std::uint32_t i = 0; i < count; ++i) {
104
+ const Vec2 v0 = verts[i];
105
+ const Vec2 v1 = verts[(i + 1) % count];
106
+ const Vec2 edge = sub(v1, v0);
107
+ // In CCW polygon, interior is on the left of edge: cross(edge, p - v0) >= 0
108
+ const double cp = cross(edge, sub(p, v0));
109
+ if (cp < -1e-9) {
110
+ inside = false;
111
+ }
112
+ Vec2 ptOnEdge;
113
+ const double d = pointToSegmentDistance(p, v0, v1, ptOnEdge);
114
+ if (d < minEdgeDist) {
115
+ minEdgeDist = d;
116
+ bestPoint = ptOnEdge;
117
+ }
118
+ }
119
+
120
+ if (inside) {
121
+ closest = p;
122
+ return 0.0;
123
+ }
124
+ closest = bestPoint;
125
+ return minEdgeDist;
126
+ }
127
+
128
+ // Check polygon-polygon overlap using Separating Axis Theorem.
129
+ bool polygonsOverlap(const Vec2* vertsA, std::uint32_t countA,
130
+ const Vec2* vertsB, std::uint32_t countB) {
131
+ if (countA < 3 || countB < 3) return false;
132
+
133
+ // Test axes of A
134
+ for (std::uint32_t i = 0; i < countA; ++i) {
135
+ const Vec2 edge = sub(vertsA[(i + 1) % countA], vertsA[i]);
136
+ const Vec2 normal{-edge.y, edge.x};
137
+ double minA = dot(vertsA[0], normal), maxA = minA;
138
+ for (std::uint32_t j = 1; j < countA; ++j) {
139
+ const double p = dot(vertsA[j], normal);
140
+ minA = std::min(minA, p);
141
+ maxA = std::max(maxA, p);
142
+ }
143
+ double minB = dot(vertsB[0], normal), maxB = minB;
144
+ for (std::uint32_t j = 1; j < countB; ++j) {
145
+ const double p = dot(vertsB[j], normal);
146
+ minB = std::min(minB, p);
147
+ maxB = std::max(maxB, p);
148
+ }
149
+ if (minA > maxB + 1e-9 || minB > maxA + 1e-9) return false;
150
+ }
151
+
152
+ // Test axes of B
153
+ for (std::uint32_t i = 0; i < countB; ++i) {
154
+ const Vec2 edge = sub(vertsB[(i + 1) % countB], vertsB[i]);
155
+ const Vec2 normal{-edge.y, edge.x};
156
+ double minA = dot(vertsA[0], normal), maxA = minA;
157
+ for (std::uint32_t j = 1; j < countA; ++j) {
158
+ const double p = dot(vertsA[j], normal);
159
+ minA = std::min(minA, p);
160
+ maxA = std::max(maxA, p);
161
+ }
162
+ double minB = dot(vertsB[0], normal), maxB = minB;
163
+ for (std::uint32_t j = 1; j < countB; ++j) {
164
+ const double p = dot(vertsB[j], normal);
165
+ minB = std::min(minB, p);
166
+ maxB = std::max(maxB, p);
167
+ }
168
+ if (minA > maxB + 1e-9 || minB > maxA + 1e-9) return false;
169
+ }
170
+
171
+ return true;
172
+ }
173
+
174
+ // Distance between two convex polygon cores.
175
+ double polygonToPolygonDistance(const Vec2* vertsA, std::uint32_t countA,
176
+ const Vec2* vertsB, std::uint32_t countB,
177
+ Vec2& closestA, Vec2& closestB) {
178
+ if (polygonsOverlap(vertsA, countA, vertsB, countB)) {
179
+ closestA = vertsA[0];
180
+ closestB = vertsA[0];
181
+ return 0.0;
182
+ }
183
+
184
+ double minD = std::numeric_limits<double>::infinity();
185
+
186
+ // Test all vertices of A against polygon B
187
+ for (std::uint32_t i = 0; i < countA; ++i) {
188
+ Vec2 cB;
189
+ const double d = pointToPolygonDistance(vertsA[i], vertsB, countB, cB);
190
+ if (d < minD) {
191
+ minD = d;
192
+ closestA = vertsA[i];
193
+ closestB = cB;
194
+ }
195
+ }
196
+
197
+ // Test all vertices of B against polygon A
198
+ for (std::uint32_t j = 0; j < countB; ++j) {
199
+ Vec2 cA;
200
+ const double d = pointToPolygonDistance(vertsB[j], vertsA, countA, cA);
201
+ if (d < minD) {
202
+ minD = d;
203
+ closestA = cA;
204
+ closestB = vertsB[j];
205
+ }
206
+ }
207
+
208
+ return minD;
209
+ }
210
+
211
+ // Distance between two ConvexGeometry2D cores.
212
+ double coreDistance(const ConvexGeometry2D& a, const ConvexGeometry2D& b,
213
+ Vec2& closestA, Vec2& closestB) {
214
+ const std::uint32_t nA = a.coreCount;
215
+ const std::uint32_t nB = b.coreCount;
216
+
217
+ if (nA == 1 && nB == 1) {
218
+ closestA = a.coreVertices[0];
219
+ closestB = b.coreVertices[0];
220
+ return length(sub(closestB, closestA));
221
+ }
222
+ if (nA == 1 && nB == 2) {
223
+ closestA = a.coreVertices[0];
224
+ return pointToSegmentDistance(closestA, b.coreVertices[0], b.coreVertices[1], closestB);
225
+ }
226
+ if (nA == 2 && nB == 1) {
227
+ closestB = b.coreVertices[0];
228
+ return pointToSegmentDistance(closestB, a.coreVertices[0], a.coreVertices[1], closestA);
229
+ }
230
+ if (nA == 2 && nB == 2) {
231
+ return segmentToSegmentDistance(a.coreVertices[0], a.coreVertices[1],
232
+ b.coreVertices[0], b.coreVertices[1],
233
+ closestA, closestB);
234
+ }
235
+ if (nA == 1 && nB >= 3) {
236
+ closestA = a.coreVertices[0];
237
+ return pointToPolygonDistance(closestA, b.coreVertices, nB, closestB);
238
+ }
239
+ if (nA >= 3 && nB == 1) {
240
+ closestB = b.coreVertices[0];
241
+ return pointToPolygonDistance(closestB, a.coreVertices, nA, closestA);
242
+ }
243
+ if (nA == 2 && nB >= 3) {
244
+ // Segment to polygon
245
+ Vec2 c1, c2;
246
+ const double d1 = pointToPolygonDistance(a.coreVertices[0], b.coreVertices, nB, c1);
247
+ const double d2 = pointToPolygonDistance(a.coreVertices[1], b.coreVertices, nB, c2);
248
+ double minD = d1 < d2 ? d1 : d2;
249
+ closestA = d1 < d2 ? a.coreVertices[0] : a.coreVertices[1];
250
+ closestB = d1 < d2 ? c1 : c2;
251
+
252
+ for (std::uint32_t j = 0; j < nB; ++j) {
253
+ Vec2 cSeg;
254
+ const double d = pointToSegmentDistance(b.coreVertices[j], a.coreVertices[0], a.coreVertices[1], cSeg);
255
+ if (d < minD) {
256
+ minD = d;
257
+ closestA = cSeg;
258
+ closestB = b.coreVertices[j];
259
+ }
260
+ }
261
+ return minD;
262
+ }
263
+ if (nA >= 3 && nB == 2) {
264
+ Vec2 c1, c2;
265
+ const double d1 = pointToPolygonDistance(b.coreVertices[0], a.coreVertices, nA, c1);
266
+ const double d2 = pointToPolygonDistance(b.coreVertices[1], a.coreVertices, nA, c2);
267
+ double minD = d1 < d2 ? d1 : d2;
268
+ closestB = d1 < d2 ? b.coreVertices[0] : b.coreVertices[1];
269
+ closestA = d1 < d2 ? c1 : c2;
270
+
271
+ for (std::uint32_t i = 0; i < nA; ++i) {
272
+ Vec2 cSeg;
273
+ const double d = pointToSegmentDistance(a.coreVertices[i], b.coreVertices[0], b.coreVertices[1], cSeg);
274
+ if (d < minD) {
275
+ minD = d;
276
+ closestA = a.coreVertices[i];
277
+ closestB = cSeg;
278
+ }
279
+ }
280
+ return minD;
281
+ }
282
+
283
+ // Polygon to Polygon (including Box-Box, Box-Polygon, Polygon-Polygon)
284
+ return polygonToPolygonDistance(a.coreVertices, nA, b.coreVertices, nB, closestA, closestB);
285
+ }
286
+
287
+ struct GeometrySource2D {
288
+ const PhysicsContext2D* context = nullptr;
289
+ const PolygonGeometry* geometries = nullptr;
290
+ std::uint32_t geometryCount = 0;
291
+ };
292
+
293
+ bool prepareCcdGeometry(
294
+ const GeometrySource2D& source,
295
+ const Body& body,
296
+ ConvexGeometry2D& geometry) {
297
+ if (source.context != nullptr) {
298
+ return prepareBodyConvexGeometry(*source.context, body, geometry);
299
+ }
300
+ return prepareBodyConvexGeometry(body, source.geometries, source.geometryCount, geometry);
301
+ }
302
+
303
+ ChainSegmentList ccdChainSegments(const GeometrySource2D& source, const Body& body) {
304
+ if (source.context != nullptr) return getChainSegmentsForBody(*source.context, body);
305
+ return getChainSegmentsForBody(body, source.geometries, source.geometryCount);
306
+ }
307
+
308
+ double computeMaxRadius(const GeometrySource2D& source, const Body& body) {
309
+ if (body.shape == ShapeType::Circle) return body.radius;
310
+ if (body.shape == ShapeType::Box) return std::sqrt(body.halfX * body.halfX + body.halfY * body.halfY);
311
+ if (body.shape == ShapeType::Capsule) return body.halfX + body.radius;
312
+ if (body.shape == ShapeType::Polygon) {
313
+ ConvexGeometry2D geometry;
314
+ if (prepareCcdGeometry(source, body, geometry)) {
315
+ double maxR = 0.0;
316
+ for (std::uint32_t i = 0; i < geometry.coreCount; ++i) {
317
+ maxR = std::max(maxR, length(sub(geometry.coreVertices[i], {body.x, body.y})));
318
+ }
319
+ return maxR;
320
+ }
321
+ }
322
+ if (body.shape == ShapeType::Segment || body.shape == ShapeType::Chain) {
323
+ const ChainSegmentList list = ccdChainSegments(source, body);
324
+ if (list.count != 0) {
325
+ double maxR = 0.0;
326
+ for (std::uint32_t i = 0; i < list.count; ++i) {
327
+ maxR = std::max(maxR, length(sub(list.segments[i].point1, {body.x, body.y})));
328
+ maxR = std::max(maxR, length(sub(list.segments[i].point2, {body.x, body.y})));
329
+ }
330
+ return maxR + body.radius;
331
+ }
332
+ }
333
+ return std::max(body.radius, std::max(body.halfX, body.halfY));
334
+ }
335
+
336
+ // Build pose of body at time t (interpolating position and orientation).
337
+ Body bodyAtTime(const Body& b, double t) {
338
+ Body res = b;
339
+ res.x = b.x + b.vx * t;
340
+ res.y = b.y + b.vy * t;
341
+ res.angle = b.angle + b.angularVelocity * t;
342
+ return res;
343
+ }
344
+
345
+ // Compute distance and closest points between two bodies at a given pose.
346
+ double bodySeparation(const GeometrySource2D& source, const Body& bodyA, const Body& bodyB,
347
+ Vec2& closestA, Vec2& closestB, Vec2& normalFromBToA) {
348
+ const bool aChain = (bodyA.shape == ShapeType::Segment || bodyA.shape == ShapeType::Chain);
349
+ const bool bChain = (bodyB.shape == ShapeType::Segment || bodyB.shape == ShapeType::Chain);
350
+ const bool aContour = (bodyA.shape == ShapeType::Contour);
351
+ const bool bContour = (bodyB.shape == ShapeType::Contour);
352
+
353
+ if (!aChain && !bChain && !aContour && !bContour) {
354
+ ConvexGeometry2D geomA{}, geomB{};
355
+ if (!prepareCcdGeometry(source, bodyA, geomA) ||
356
+ !prepareCcdGeometry(source, bodyB, geomB)) {
357
+ normalFromBToA = {1.0, 0.0};
358
+ closestA = {bodyA.x, bodyA.y};
359
+ closestB = {bodyB.x, bodyB.y};
360
+ return 0.0;
361
+ }
362
+
363
+ const double dCore = coreDistance(geomA, geomB, closestA, closestB);
364
+ const double sep = dCore - geomA.radius - geomB.radius;
365
+
366
+ if (dCore > 1e-12) {
367
+ // Normal pointing from B toward A
368
+ normalFromBToA = normalize(sub(closestA, closestB));
369
+ } else {
370
+ const Vec2 diff = sub({bodyA.x, bodyA.y}, {bodyB.x, bodyB.y});
371
+ normalFromBToA = normalize(diff, {1.0, 0.0});
372
+ }
373
+ return sep;
374
+ }
375
+
376
+ // If one body is a segment or chain
377
+ if (bChain && !aChain) {
378
+ ConvexGeometry2D geomA{};
379
+ if (!prepareCcdGeometry(source, bodyA, geomA)) return 0.0;
380
+ const ChainSegmentList list = ccdChainSegments(source, bodyB);
381
+
382
+ double minSep = std::numeric_limits<double>::infinity();
383
+ Vec2 bestA = {bodyA.x, bodyA.y};
384
+ Vec2 bestB = {bodyB.x, bodyB.y};
385
+ Vec2 bestNorm = {1.0, 0.0};
386
+
387
+ for (std::uint32_t i = 0; i < list.count; ++i) {
388
+ const Vec2 p1 = list.segments[i].point1;
389
+ const Vec2 p2 = list.segments[i].point2;
390
+ const Vec2 e = sub(p2, p1);
391
+ const double L2 = dot(e, e);
392
+ if (L2 <= 1e-12) continue;
393
+ const double invL = 1.0 / std::sqrt(L2);
394
+ const Vec2 t = scale(e, invL);
395
+ const Vec2 n = {t.y, -t.x};
396
+
397
+ const bool freeSide = source.context != nullptr
398
+ ? onFreeSide(*source.context, bodyA, p1, n)
399
+ : onFreeSide(bodyA, p1, n);
400
+ if (!freeSide) continue;
401
+
402
+ ConvexGeometry2D activeGeomA = geomA;
403
+ if (bodyA.shape == ShapeType::Capsule && geomA.coreCount == 2) {
404
+ const double distN0 = dot(sub(geomA.coreVertices[0], p1), n);
405
+ const double distN1 = dot(sub(geomA.coreVertices[1], p1), n);
406
+ if (distN0 < -1e-4 && distN1 >= -1e-4) {
407
+ activeGeomA.coreCount = 1;
408
+ activeGeomA.coreVertices[0] = geomA.coreVertices[1];
409
+ } else if (distN1 < -1e-4 && distN0 >= -1e-4) {
410
+ activeGeomA.coreCount = 1;
411
+ }
412
+ }
413
+
414
+ ConvexGeometry2D segGeom{};
415
+ segGeom.sourceShape = ShapeType::Segment;
416
+ segGeom.coreCount = 2;
417
+ segGeom.coreVertices[0] = p1;
418
+ segGeom.coreVertices[1] = p2;
419
+ segGeom.radius = list.segments[i].radius;
420
+
421
+ Vec2 cA, cB;
422
+ const double dCore = coreDistance(activeGeomA, segGeom, cA, cB);
423
+ const double sep = dCore - activeGeomA.radius - segGeom.radius;
424
+ if (sep < minSep) {
425
+ minSep = sep;
426
+ const Vec2 norm = dCore > 1e-12 ? scale(sub(cA, cB), 1.0 / dCore) : n;
427
+ bestA = sub(cA, scale(norm, activeGeomA.radius));
428
+ bestB = add(cB, scale(norm, segGeom.radius));
429
+ bestNorm = norm;
430
+ }
431
+ }
432
+ closestA = bestA;
433
+ closestB = bestB;
434
+ normalFromBToA = bestNorm;
435
+ return minSep;
436
+ }
437
+
438
+ if (aChain && !bChain) {
439
+ Vec2 cB, cA, normAtoB;
440
+ const double sep = bodySeparation(source, bodyB, bodyA, cB, cA, normAtoB);
441
+ closestA = cA;
442
+ closestB = cB;
443
+ normalFromBToA = scale(normAtoB, -1.0);
444
+ return sep;
445
+ }
446
+
447
+ if (bContour && !aContour) {
448
+ const PhysicsContext2D* ctx = source.context != nullptr ? source.context : &detail::legacyPhysicsContext();
449
+ const ContourHeader2D* header = contourHeaderFor(*ctx, bodyB);
450
+ if (header == nullptr || header->edgeCount == 0) return 0.0;
451
+ const ContourEdge2D* edges = contourEdgesFor(*ctx, *header);
452
+ if (edges == nullptr) return 0.0;
453
+
454
+ ConvexGeometry2D geomA{};
455
+ if (!prepareCcdGeometry(source, bodyA, geomA)) return 0.0;
456
+
457
+ double minSep = std::numeric_limits<double>::infinity();
458
+ Vec2 bestA = {bodyA.x, bodyA.y};
459
+ Vec2 bestB = {bodyB.x, bodyB.y};
460
+ Vec2 bestNorm = {1.0, 0.0};
461
+
462
+ for (std::uint32_t i = 0; i < header->edgeCount; ++i) {
463
+ const auto& edge = edges[i];
464
+ if (edge.kind == 2) continue;
465
+ if (!onFreeSideContour(*ctx, bodyA, edge)) continue;
466
+
467
+ if (edge.kind == 0) {
468
+ ConvexGeometry2D segGeom{};
469
+ segGeom.sourceShape = ShapeType::Segment;
470
+ segGeom.coreCount = 2;
471
+ segGeom.coreVertices[0] = edge.from;
472
+ segGeom.coreVertices[1] = edge.to;
473
+ segGeom.radius = header->skin;
474
+
475
+ Vec2 cA, cB;
476
+ const double dCore = coreDistance(geomA, segGeom, cA, cB);
477
+ const double sep = dCore - geomA.radius - segGeom.radius;
478
+ if (sep < minSep) {
479
+ minSep = sep;
480
+ const Vec2 norm = dCore > 1e-12 ? scale(sub(cA, cB), 1.0 / dCore) : Vec2{0.0, 1.0};
481
+ bestA = sub(cA, scale(norm, geomA.radius));
482
+ bestB = add(cB, scale(norm, segGeom.radius));
483
+ bestNorm = norm;
484
+ }
485
+ } else if (edge.kind == 1) {
486
+ const Vec2 centerA = {bodyA.x, bodyA.y};
487
+ const Vec2 cp = closestPointOnArc(centerA, edge.center, edge.arcRadius, edge.quadrant, edge.from, edge.to);
488
+
489
+ ConvexGeometry2D ptGeom{};
490
+ ptGeom.sourceShape = ShapeType::Circle;
491
+ ptGeom.coreCount = 1;
492
+ ptGeom.coreVertices[0] = cp;
493
+ ptGeom.radius = header->skin;
494
+
495
+ Vec2 cA, cB;
496
+ const double dCore = coreDistance(geomA, ptGeom, cA, cB);
497
+ const double sep = dCore - geomA.radius - ptGeom.radius;
498
+ if (sep < minSep) {
499
+ minSep = sep;
500
+ const Vec2 norm = dCore > 1e-12 ? scale(sub(cA, cB), 1.0 / dCore) : Vec2{0.0, 1.0};
501
+ bestA = sub(cA, scale(norm, geomA.radius));
502
+ bestB = add(cB, scale(norm, ptGeom.radius));
503
+ bestNorm = norm;
504
+ }
505
+ }
506
+ }
507
+ closestA = bestA;
508
+ closestB = bestB;
509
+ normalFromBToA = bestNorm;
510
+ return minSep;
511
+ }
512
+
513
+ if (aContour && !bContour) {
514
+ Vec2 cB, cA, normAtoB;
515
+ const double sep = bodySeparation(source, bodyB, bodyA, cB, cA, normAtoB);
516
+ closestA = cA;
517
+ closestB = cB;
518
+ normalFromBToA = scale(normAtoB, -1.0);
519
+ return sep;
520
+ }
521
+
522
+ // Chain to chain
523
+ closestA = {bodyA.x, bodyA.y};
524
+ closestB = {bodyB.x, bodyB.y};
525
+ normalFromBToA = normalize(sub(closestA, closestB), {1.0, 0.0});
526
+ return 0.0;
527
+ }
528
+
529
+ // Compute swept bounding box of a body over time interval dt.
530
+ BodyAabb2D computeSweptAabb(const GeometrySource2D& source, const Body& body, double dt) {
531
+ const double rMax = computeMaxRadius(source, body);
532
+ const double startX = body.x;
533
+ const double startY = body.y;
534
+ const double endX = body.x + body.vx * dt;
535
+ const double endY = body.y + body.vy * dt;
536
+
537
+ BodyAabb2D aabb;
538
+ aabb.minX = std::min(startX, endX) - rMax;
539
+ aabb.maxX = std::max(startX, endX) + rMax;
540
+ aabb.minY = std::min(startY, endY) - rMax;
541
+ aabb.maxY = std::max(startY, endY) + rMax;
542
+ return aabb;
543
+ }
544
+
545
+ bool aabbsOverlap(const BodyAabb2D& a, const BodyAabb2D& b) {
546
+ return !(a.maxX < b.minX || a.minX > b.maxX || a.maxY < b.minY || a.minY > b.maxY);
547
+ }
548
+
549
+ } // namespace
550
+
551
+ namespace {
552
+
553
+ ToiResult2D computeTimeOfImpact(
554
+ const GeometrySource2D& source,
555
+ const Body& bodyA,
556
+ const Body& bodyB,
557
+ double dt,
558
+ double targetSeparation,
559
+ std::uint32_t maxIterations) {
560
+ ToiResult2D result;
561
+ result.hit = false;
562
+ result.toi = 1.0;
563
+ result.time = dt;
564
+ result.iterations = 0;
565
+
566
+ if (dt <= 0.0) return result;
567
+
568
+ const PhysicsContext2D* ctx = source.context;
569
+ if (ctx == nullptr) {
570
+ PhysicsContext2D& legacy = detail::legacyPhysicsContext();
571
+ if (source.geometries != nullptr && source.geometryCount > 0) {
572
+ (void)setPolygonGeometry(legacy, source.geometries, source.geometryCount);
573
+ }
574
+ ctx = &legacy;
575
+ }
576
+ Manifold initialManifold{};
577
+ if (collideChecked(*ctx, bodyA, bodyB, initialManifold) == kStepOk && initialManifold.hit) {
578
+ result.hit = true;
579
+ result.toi = 0.0;
580
+ result.time = 0.0;
581
+ result.normal = scale(initialManifold.normal, -1.0);
582
+ result.point = initialManifold.pointCount > 0 ? initialManifold.points[0].position : Vec2{bodyA.x, bodyA.y};
583
+ result.separation = -initialManifold.penetration;
584
+ result.iterations = 1;
585
+ return result;
586
+ }
587
+
588
+ // Upper bound on closing velocity including linear and rotational surface motion
589
+ const double rMaxA = computeMaxRadius(source, bodyA);
590
+ const double rMaxB = computeMaxRadius(source, bodyB);
591
+ const double relVx = bodyA.vx - bodyB.vx;
592
+ const double relVy = bodyA.vy - bodyB.vy;
593
+ const double linearClosingSpeed = std::sqrt(relVx * relVx + relVy * relVy);
594
+ const double vMax = linearClosingSpeed
595
+ + std::abs(bodyA.angularVelocity) * rMaxA
596
+ + std::abs(bodyB.angularVelocity) * rMaxB;
597
+
598
+ // Initial separation check at t = 0
599
+ Vec2 closestA, closestB, normalFromBToA;
600
+ double sep0 = bodySeparation(source, bodyA, bodyB, closestA, closestB, normalFromBToA);
601
+ if (sep0 <= targetSeparation) {
602
+ result.hit = true;
603
+ result.toi = 0.0;
604
+ result.time = 0.0;
605
+ result.normal = normalFromBToA;
606
+ result.point = scale(add(closestA, closestB), 0.5);
607
+ result.separation = sep0;
608
+ result.iterations = 1;
609
+ return result;
610
+ }
611
+
612
+ if (vMax <= kEpsilon) {
613
+ // Bodies are not moving relative to each other and do not touch initially
614
+ return result;
615
+ }
616
+
617
+ double t = 0.0;
618
+ double prevT = 0.0;
619
+ std::uint32_t iter = 0;
620
+
621
+ for (; iter < maxIterations; ++iter) {
622
+ const Body poseA = bodyAtTime(bodyA, t);
623
+ const Body poseB = bodyAtTime(bodyB, t);
624
+ const double sep = bodySeparation(source, poseA, poseB, closestA, closestB, normalFromBToA);
625
+
626
+ if (std::isinf(sep)) {
627
+ break;
628
+ }
629
+
630
+ if (sep <= targetSeparation && sep >= -targetSeparation) {
631
+ // Reached impact within tolerance
632
+ result.hit = true;
633
+ result.toi = clamp(t / dt, 0.0, 1.0);
634
+ result.time = t;
635
+ result.normal = normalFromBToA;
636
+ result.point = scale(add(closestA, closestB), 0.5);
637
+ result.separation = sep;
638
+ result.iterations = iter + 1;
639
+ return result;
640
+ }
641
+
642
+ if (sep < -targetSeparation) {
643
+ // Overshot into penetration: perform bisection between prevT and t
644
+ double tLow = prevT;
645
+ double tHigh = t;
646
+ for (std::uint32_t bisect = 0; bisect < 16; ++bisect) {
647
+ const double tMid = 0.5 * (tLow + tHigh);
648
+ const Body midA = bodyAtTime(bodyA, tMid);
649
+ const Body midB = bodyAtTime(bodyB, tMid);
650
+ const double midSep = bodySeparation(source, midA, midB, closestA, closestB, normalFromBToA);
651
+ if (midSep > targetSeparation) {
652
+ tLow = tMid;
653
+ } else {
654
+ tHigh = tMid;
655
+ }
656
+ }
657
+ result.hit = true;
658
+ result.toi = clamp(tHigh / dt, 0.0, 1.0);
659
+ result.time = tHigh;
660
+ result.normal = normalFromBToA;
661
+ result.point = scale(add(closestA, closestB), 0.5);
662
+ result.separation = 0.0;
663
+ result.iterations = iter + 1;
664
+ return result;
665
+ }
666
+
667
+ // Conservative advancement step: dtStep = (sep - targetSeparation) / vMax
668
+ const double dtStep = (sep - targetSeparation) / vMax;
669
+ prevT = t;
670
+ t += std::max(1e-9, dtStep);
671
+
672
+ if (t > dt) {
673
+ // No collision occurs within the step duration
674
+ break;
675
+ }
676
+ }
677
+
678
+ result.iterations = iter;
679
+ return result;
680
+ }
681
+
682
+ } // namespace
683
+
684
+ ToiResult2D computeTimeOfImpact2D(
685
+ const Body& bodyA,
686
+ const Body& bodyB,
687
+ const PolygonGeometry* geometries,
688
+ std::uint32_t geometryCount,
689
+ double dt,
690
+ double targetSeparation,
691
+ std::uint32_t maxIterations) {
692
+ return computeTimeOfImpact(
693
+ {nullptr, geometries, geometryCount}, bodyA, bodyB, dt, targetSeparation, maxIterations);
694
+ }
695
+
696
+ ToiResult2D computeTimeOfImpact2D(
697
+ const PhysicsContext2D& context,
698
+ const Body& bodyA,
699
+ const Body& bodyB,
700
+ double dt,
701
+ double targetSeparation,
702
+ std::uint32_t maxIterations) {
703
+ return computeTimeOfImpact(
704
+ {&context, nullptr, 0}, bodyA, bodyB, dt, targetSeparation, maxIterations);
705
+ }
706
+
707
+ // Check if a body qualifies as a continuous collision bullet.
708
+ inline bool isBulletBody(const Body& body, const bool* bulletFlags, std::uint32_t index, double dt) {
709
+ (void)dt;
710
+ if (body.type != BodyType::Dynamic) return false;
711
+ if (bulletFlags != nullptr && bulletFlags[index]) return true;
712
+ return body.ccd != 0;
713
+ }
714
+
715
+ bool disabledContactPair(
716
+ const DisabledContactPair2D* pairs,
717
+ std::uint32_t count,
718
+ std::uint32_t firstBodyId,
719
+ std::uint32_t secondBodyId) {
720
+ if (pairs == nullptr || count == 0) return false;
721
+ const DisabledContactPair2D key{
722
+ std::min(firstBodyId, secondBodyId), std::max(firstBodyId, secondBodyId)};
723
+ const auto* found = std::lower_bound(pairs, pairs + count, key,
724
+ [](const DisabledContactPair2D& left, const DisabledContactPair2D& right) {
725
+ return left.firstBodyId < right.firstBodyId
726
+ || (left.firstBodyId == right.firstBodyId && left.secondBodyId < right.secondBodyId);
727
+ });
728
+ return found != pairs + count
729
+ && found->firstBodyId == key.firstBodyId
730
+ && found->secondBodyId == key.secondBodyId;
731
+ }
732
+
733
+ std::int32_t resolveContinuousContacts2D(
734
+ PhysicsContext2D& context,
735
+ Body* bodies,
736
+ std::uint32_t bodyCount,
737
+ const StepOptions& options,
738
+ const DisabledContactPair2D* disabledPairs,
739
+ std::uint32_t disabledPairCount,
740
+ const bool* bulletFlags,
741
+ CcdStepStats2D* stats) {
742
+ if (bodies == nullptr || bodyCount == 0 || options.dt <= 0.0) return kStepOk;
743
+ if (bodyCount > context.bodyCapacity()) return kStepWorkspaceAllocation;
744
+ if (stats != nullptr) {
745
+ stats->pairsChecked = 0;
746
+ stats->impactsResolved = 0;
747
+ stats->earliestToi = 1.0;
748
+ }
749
+
750
+ const GeometrySource2D geometrySource{&context, nullptr, 0};
751
+ double remaining = options.dt;
752
+ const std::uint64_t eventLimit = static_cast<std::uint64_t>(bodyCount) * 4u + 8u;
753
+ for (std::uint64_t event = 0; event < eventLimit && remaining > 0.0; ++event) {
754
+ ToiResult2D earliest{};
755
+ earliest.toi = 1.0;
756
+ std::uint32_t firstIndex = bodyCount;
757
+ std::uint32_t secondIndex = bodyCount;
758
+ for (std::uint32_t first = 0; first < bodyCount; ++first) {
759
+ for (std::uint32_t second = first + 1; second < bodyCount; ++second) {
760
+ const Body& a = bodies[first];
761
+ const Body& b = bodies[second];
762
+ if (!isBulletBody(a, bulletFlags, first, remaining)
763
+ && !isBulletBody(b, bulletFlags, second, remaining)) continue;
764
+ if (a.type == BodyType::Static && b.type == BodyType::Static) continue;
765
+ if ((a.layer & b.mask) == 0 || (b.layer & a.mask) == 0) continue;
766
+ if (((a.filterFlags | b.filterFlags) & kFilterFlagsMask) != 0) continue;
767
+ if (disabledContactPair(disabledPairs, disabledPairCount, a.id, b.id)) continue;
768
+ const BodyAabb2D firstSweep = computeSweptAabb(geometrySource, a, remaining);
769
+ const BodyAabb2D secondSweep = computeSweptAabb(geometrySource, b, remaining);
770
+ if (!aabbsOverlap(firstSweep, secondSweep)) continue;
771
+ if (stats != nullptr) stats->pairsChecked += 1;
772
+ const ToiResult2D candidate = computeTimeOfImpact2D(
773
+ context, a, b, remaining);
774
+ if (!candidate.hit) continue;
775
+ const Vec2 normal = scale(candidate.normal, -1.0);
776
+ const Body impactA = bodyAtTime(a, candidate.time);
777
+ const Body impactB = bodyAtTime(b, candidate.time);
778
+ const Vec2 offsetA = sub(candidate.point, Vec2{impactA.x, impactA.y});
779
+ const Vec2 offsetB = sub(candidate.point, Vec2{impactB.x, impactB.y});
780
+ const Vec2 velocityA = add({impactA.vx, impactA.vy},
781
+ {-impactA.angularVelocity * offsetA.y, impactA.angularVelocity * offsetA.x});
782
+ const Vec2 velocityB = add({impactB.vx, impactB.vy},
783
+ {-impactB.angularVelocity * offsetB.y, impactB.angularVelocity * offsetB.x});
784
+ if (dot(sub(velocityB, velocityA), normal) >= -kEpsilon) continue;
785
+ const bool earlier = firstIndex == bodyCount || candidate.toi < earliest.toi;
786
+ const bool tied = firstIndex != bodyCount && candidate.toi == earliest.toi;
787
+ const bool canonical = tied && (a.id < bodies[firstIndex].id
788
+ || (a.id == bodies[firstIndex].id && b.id < bodies[secondIndex].id));
789
+ if (earlier || canonical) {
790
+ earliest = candidate;
791
+ firstIndex = first;
792
+ secondIndex = second;
793
+ }
794
+ }
795
+ }
796
+ if (firstIndex == bodyCount) {
797
+ for (std::uint32_t index = 0; index < bodyCount; ++index) {
798
+ Body& body = bodies[index];
799
+ if (body.type == BodyType::Static) continue;
800
+ body.x += body.vx * remaining;
801
+ body.y += body.vy * remaining;
802
+ body.angle += body.angularVelocity * remaining;
803
+ }
804
+ remaining = 0.0;
805
+ break;
806
+ }
807
+
808
+ const double elapsed = earliest.time;
809
+ for (std::uint32_t index = 0; index < bodyCount; ++index) {
810
+ Body& body = bodies[index];
811
+ if (body.type == BodyType::Static) continue;
812
+ body.x += body.vx * elapsed;
813
+ body.y += body.vy * elapsed;
814
+ body.angle += body.angularVelocity * elapsed;
815
+ }
816
+ remaining -= elapsed;
817
+
818
+ Body& a = bodies[firstIndex];
819
+ Body& b = bodies[secondIndex];
820
+ const Vec2 normal = scale(earliest.normal, -1.0);
821
+ const Vec2 offsetA = sub(earliest.point, Vec2{a.x, a.y});
822
+ const Vec2 offsetB = sub(earliest.point, Vec2{b.x, b.y});
823
+ const Vec2 velocityA = add({a.vx, a.vy},
824
+ {-a.angularVelocity * offsetA.y, a.angularVelocity * offsetA.x});
825
+ const Vec2 velocityB = add({b.vx, b.vy},
826
+ {-b.angularVelocity * offsetB.y, b.angularVelocity * offsetB.x});
827
+ const Vec2 relativeVelocity = sub(velocityB, velocityA);
828
+ const double normalVelocity = dot(relativeVelocity, normal);
829
+ const double inverseMassA = a.type == BodyType::Dynamic && a.mass > 0.0 ? 1.0 / a.mass : 0.0;
830
+ const double inverseMassB = b.type == BodyType::Dynamic && b.mass > 0.0 ? 1.0 / b.mass : 0.0;
831
+ const double inverseInertiaA = a.type == BodyType::Dynamic && a.inertia > 0.0 ? 1.0 / a.inertia : 0.0;
832
+ const double inverseInertiaB = b.type == BodyType::Dynamic && b.inertia > 0.0 ? 1.0 / b.inertia : 0.0;
833
+ const double crossAN = cross(offsetA, normal);
834
+ const double crossBN = cross(offsetB, normal);
835
+ const double normalMass = inverseMassA + inverseMassB
836
+ + crossAN * crossAN * inverseInertiaA + crossBN * crossBN * inverseInertiaB;
837
+ if (normalVelocity < 0.0 && normalMass > kEpsilon) {
838
+ const double restitution = std::min(a.restitution, b.restitution);
839
+ const double impulseMagnitude = -(1.0 + restitution) * normalVelocity / normalMass;
840
+ const Vec2 impulse = scale(normal, impulseMagnitude);
841
+ if (a.type == BodyType::Dynamic) {
842
+ a.vx -= impulse.x * inverseMassA;
843
+ a.vy -= impulse.y * inverseMassA;
844
+ a.angularVelocity -= cross(offsetA, impulse) * inverseInertiaA;
845
+ }
846
+ if (b.type == BodyType::Dynamic) {
847
+ b.vx += impulse.x * inverseMassB;
848
+ b.vy += impulse.y * inverseMassB;
849
+ b.angularVelocity += cross(offsetB, impulse) * inverseInertiaB;
850
+ }
851
+ }
852
+ if (stats != nullptr) {
853
+ stats->impactsResolved += 1;
854
+ stats->earliestToi = std::min(stats->earliestToi,
855
+ options.dt > 0.0 ? (options.dt - remaining) / options.dt : 1.0);
856
+ }
857
+ }
858
+ if (remaining > 0.0) return kStepCandidateCapacity;
859
+ return kStepOk;
860
+ }
861
+
862
+ std::int32_t resolveContinuousContacts2D(
863
+ PhysicsContext2D& context,
864
+ Body* bodies,
865
+ std::uint32_t bodyCount,
866
+ const StepOptions& options,
867
+ const bool* bulletFlags,
868
+ CcdStepStats2D* stats) {
869
+ return resolveContinuousContacts2D(
870
+ context, bodies, bodyCount, options, nullptr, 0, bulletFlags, stats);
871
+ }
872
+
873
+ std::int32_t resolveContinuousContacts2D(
874
+ Body* bodies,
875
+ std::uint32_t bodyCount,
876
+ const StepOptions& options,
877
+ const bool* bulletFlags,
878
+ CcdStepStats2D* stats) {
879
+ if (bodies == nullptr || bodyCount == 0 || options.dt <= 0.0) return kStepOk;
880
+
881
+ const double dt = options.dt;
882
+ if (stats != nullptr) {
883
+ stats->pairsChecked = 0;
884
+ stats->impactsResolved = 0;
885
+ stats->earliestToi = 1.0;
886
+ }
887
+
888
+ // Identify bullets and compute swept AABBs
889
+ for (std::uint32_t i = 0; i < bodyCount; ++i) {
890
+ Body& bullet = bodies[i];
891
+ if (!isBulletBody(bullet, bulletFlags, i, dt)) continue;
892
+
893
+ const BodyAabb2D bulletSwept = computeSweptAabb({}, bullet, dt);
894
+
895
+ // Find earliest impact against all other bodies
896
+ ToiResult2D earliestImpact;
897
+ earliestImpact.hit = false;
898
+ earliestImpact.toi = 1.0;
899
+ std::uint32_t targetIndex = kMaxBodies;
900
+
901
+ for (std::uint32_t j = 0; j < bodyCount; ++j) {
902
+ if (i == j) continue;
903
+ Body& target = bodies[j];
904
+
905
+ // Broadphase swept AABB overlap test
906
+ const BodyAabb2D targetSwept = computeSweptAabb({}, target, dt);
907
+ if (!aabbsOverlap(bulletSwept, targetSwept)) continue;
908
+
909
+ if (stats != nullptr) stats->pairsChecked += 1;
910
+
911
+ const ToiResult2D toi = computeTimeOfImpact2D(bullet, target, nullptr, 0, dt);
912
+ if (toi.hit && toi.toi < earliestImpact.toi) {
913
+ earliestImpact = toi;
914
+ targetIndex = j;
915
+ }
916
+ }
917
+
918
+ if (!earliestImpact.hit || targetIndex >= bodyCount) continue;
919
+
920
+ // Found impact!
921
+ Body& target = bodies[targetIndex];
922
+ const double tHit = earliestImpact.time;
923
+ const double tResidual = dt - tHit;
924
+
925
+ if (stats != nullptr) {
926
+ stats->impactsResolved += 1;
927
+ stats->earliestToi = std::min(stats->earliestToi, earliestImpact.toi);
928
+ }
929
+
930
+ // 1. Advance both bodies to the exact time of impact
931
+ bullet.x += bullet.vx * tHit;
932
+ bullet.y += bullet.vy * tHit;
933
+ bullet.angle += bullet.angularVelocity * tHit;
934
+
935
+ if (target.type != BodyType::Static) {
936
+ target.x += target.vx * tHit;
937
+ target.y += target.vy * tHit;
938
+ target.angle += target.angularVelocity * tHit;
939
+ }
940
+
941
+ // 2. Resolve impact impulse at contact point
942
+ const Vec2 normal = earliestImpact.normal; // Normal pointing from target to bullet
943
+ const Vec2 contactPoint = earliestImpact.point;
944
+ const Vec2 rA = sub(contactPoint, {bullet.x, bullet.y});
945
+ const Vec2 rB = sub(contactPoint, {target.x, target.y});
946
+
947
+ // Linear + angular velocity at contact point
948
+ const Vec2 vA = add({bullet.vx, bullet.vy}, {-bullet.angularVelocity * rA.y, bullet.angularVelocity * rA.x});
949
+ const Vec2 vB = (target.type == BodyType::Static) ? Vec2{0.0, 0.0} :
950
+ add({target.vx, target.vy}, {-target.angularVelocity * rB.y, target.angularVelocity * rB.x});
951
+ const Vec2 vRel = sub(vA, vB);
952
+ const double vn = dot(vRel, normal);
953
+
954
+ if (vn < 0.0) {
955
+ // Approaching along contact normal
956
+ const double invMassA = bullet.mass > 0.0 ? 1.0 / bullet.mass : 0.0;
957
+ const double invMassB = (target.type == BodyType::Dynamic && target.mass > 0.0) ? 1.0 / target.mass : 0.0;
958
+ const double invInertiaA = bullet.inertia > 0.0 ? 1.0 / bullet.inertia : 0.0;
959
+ const double invInertiaB = (target.type == BodyType::Dynamic && target.inertia > 0.0) ? 1.0 / target.inertia : 0.0;
960
+
961
+ const double crossAN = cross(rA, normal);
962
+ const double crossBN = cross(rB, normal);
963
+ const double kn = invMassA + invMassB + crossAN * crossAN * invInertiaA + crossBN * crossBN * invInertiaB;
964
+
965
+ if (kn > kEpsilon) {
966
+ const double restitution = std::max(bullet.restitution, target.restitution);
967
+ const double jn = -(1.0 + restitution) * vn / kn;
968
+ const Vec2 impulseN = scale(normal, jn);
969
+
970
+ bullet.vx += impulseN.x * invMassA;
971
+ bullet.vy += impulseN.y * invMassA;
972
+ bullet.angularVelocity += cross(rA, impulseN) * invInertiaA;
973
+
974
+ if (target.type == BodyType::Dynamic) {
975
+ target.vx -= impulseN.x * invMassB;
976
+ target.vy -= impulseN.y * invMassB;
977
+ target.angularVelocity -= cross(rB, impulseN) * invInertiaB;
978
+ }
979
+
980
+ // Friction impulse
981
+ const Vec2 tangent{-normal.y, normal.x};
982
+ const double vt = dot(vRel, tangent);
983
+ const double crossAT = cross(rA, tangent);
984
+ const double crossBT = cross(rB, tangent);
985
+ const double kt = invMassA + invMassB + crossAT * crossAT * invInertiaA + crossBT * crossBT * invInertiaB;
986
+
987
+ if (kt > kEpsilon) {
988
+ const double friction = std::sqrt(std::max(0.0, bullet.friction * target.friction));
989
+ const double jtRaw = -vt / kt;
990
+ const double maxJt = friction * jn;
991
+ const double jt = clamp(jtRaw, -maxJt, maxJt);
992
+ const Vec2 impulseT = scale(tangent, jt);
993
+
994
+ bullet.vx += impulseT.x * invMassA;
995
+ bullet.vy += impulseT.y * invMassA;
996
+ bullet.angularVelocity += cross(rA, impulseT) * invInertiaA;
997
+
998
+ if (target.type == BodyType::Dynamic) {
999
+ target.vx -= impulseT.x * invMassB;
1000
+ target.vy -= impulseT.y * invMassB;
1001
+ target.angularVelocity -= cross(rB, impulseT) * invInertiaB;
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+
1007
+ // 3. Integrate post-impact motion across residual time
1008
+ if (tResidual > 0.0) {
1009
+ bullet.x += bullet.vx * tResidual;
1010
+ bullet.y += bullet.vy * tResidual;
1011
+ bullet.angle += bullet.angularVelocity * tResidual;
1012
+
1013
+ if (target.type != BodyType::Static) {
1014
+ target.x += target.vx * tResidual;
1015
+ target.y += target.vy * tResidual;
1016
+ target.angle += target.angularVelocity * tResidual;
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ return kStepOk;
1022
+ }
1023
+
1024
+ std::int32_t stepWithCcd(
1025
+ PhysicsContext2D& context,
1026
+ Body* bodies,
1027
+ std::uint32_t bodyCount,
1028
+ const StepOptions& options,
1029
+ const bool* bulletFlags,
1030
+ CcdStepStats2D* stats) {
1031
+ if (bodies == nullptr || bodyCount == 0) return kStepInvalidArguments;
1032
+ if (!validOptions(options)) return kStepInvalidArguments;
1033
+
1034
+ const double substepDt = options.dt / static_cast<double>(options.substeps);
1035
+ const GeometrySource2D geometrySource{&context, nullptr, 0};
1036
+ bool ccdHandled[kMaxBodies]{};
1037
+
1038
+ for (std::uint32_t substep = 0; substep < options.substeps; ++substep) {
1039
+ std::fill_n(ccdHandled, std::min(bodyCount, kMaxBodies), false);
1040
+
1041
+ // 1. Velocity integration (apply gravity and forces)
1042
+ for (std::uint32_t i = 0; i < bodyCount; ++i) {
1043
+ Body& b = bodies[i];
1044
+ if (b.type == BodyType::Dynamic) {
1045
+ b.vx += (options.gravityX + b.forceX / b.mass) * substepDt;
1046
+ b.vy += (options.gravityY + b.forceY / b.mass) * substepDt;
1047
+ b.angularVelocity += (b.torque / b.inertia) * substepDt;
1048
+ }
1049
+ }
1050
+
1051
+ // 2. Resolve continuous contacts for fast-moving bullets
1052
+ StepOptions subOpts = options;
1053
+ subOpts.dt = substepDt;
1054
+ subOpts.substeps = 1;
1055
+
1056
+ for (std::uint32_t i = 0; i < bodyCount; ++i) {
1057
+ Body& bullet = bodies[i];
1058
+ if (!isBulletBody(bullet, bulletFlags, i, substepDt)) continue;
1059
+
1060
+ const BodyAabb2D bulletSwept = computeSweptAabb(geometrySource, bullet, substepDt);
1061
+ ToiResult2D earliestImpact;
1062
+ earliestImpact.hit = false;
1063
+ earliestImpact.toi = 1.0;
1064
+ std::uint32_t targetIndex = kMaxBodies;
1065
+
1066
+ for (std::uint32_t j = 0; j < bodyCount; ++j) {
1067
+ if (i == j) continue;
1068
+ Body& target = bodies[j];
1069
+ const BodyAabb2D targetSwept = computeSweptAabb(geometrySource, target, substepDt);
1070
+ if (!aabbsOverlap(bulletSwept, targetSwept)) continue;
1071
+
1072
+ if (stats != nullptr) stats->pairsChecked += 1;
1073
+
1074
+ const ToiResult2D toi = computeTimeOfImpact2D(context, bullet, target, substepDt);
1075
+ if (toi.hit && toi.toi < earliestImpact.toi) {
1076
+ earliestImpact = toi;
1077
+ targetIndex = j;
1078
+ }
1079
+ }
1080
+
1081
+ if (!earliestImpact.hit || targetIndex >= bodyCount) continue;
1082
+
1083
+ Body& target = bodies[targetIndex];
1084
+ const double tHit = earliestImpact.time;
1085
+ const double tResidual = substepDt - tHit;
1086
+
1087
+ if (stats != nullptr) {
1088
+ stats->impactsResolved += 1;
1089
+ stats->earliestToi = std::min(stats->earliestToi, earliestImpact.toi);
1090
+ }
1091
+
1092
+ // Advance both to impact point
1093
+ bullet.x += bullet.vx * tHit;
1094
+ bullet.y += bullet.vy * tHit;
1095
+ bullet.angle += bullet.angularVelocity * tHit;
1096
+
1097
+ if (target.type != BodyType::Static) {
1098
+ target.x += target.vx * tHit;
1099
+ target.y += target.vy * tHit;
1100
+ target.angle += target.angularVelocity * tHit;
1101
+ }
1102
+
1103
+ // Impact impulse
1104
+ const Vec2 normal = earliestImpact.normal;
1105
+ const Vec2 contactPoint = earliestImpact.point;
1106
+ const Vec2 rA = sub(contactPoint, {bullet.x, bullet.y});
1107
+ const Vec2 rB = sub(contactPoint, {target.x, target.y});
1108
+ const Vec2 vA = add({bullet.vx, bullet.vy}, {-bullet.angularVelocity * rA.y, bullet.angularVelocity * rA.x});
1109
+ const Vec2 vB = (target.type == BodyType::Static) ? Vec2{0.0, 0.0} :
1110
+ add({target.vx, target.vy}, {-target.angularVelocity * rB.y, target.angularVelocity * rB.x});
1111
+ const Vec2 vRel = sub(vA, vB);
1112
+ const double vn = dot(vRel, normal);
1113
+
1114
+ if (vn < 0.0) {
1115
+ const double invMassA = bullet.mass > 0.0 ? 1.0 / bullet.mass : 0.0;
1116
+ const double invMassB = (target.type == BodyType::Dynamic && target.mass > 0.0) ? 1.0 / target.mass : 0.0;
1117
+ const double invInertiaA = bullet.inertia > 0.0 ? 1.0 / bullet.inertia : 0.0;
1118
+ const double invInertiaB = (target.type == BodyType::Dynamic && target.inertia > 0.0) ? 1.0 / target.inertia : 0.0;
1119
+
1120
+ const double crossAN = cross(rA, normal);
1121
+ const double crossBN = cross(rB, normal);
1122
+ const double kn = invMassA + invMassB + crossAN * crossAN * invInertiaA + crossBN * crossBN * invInertiaB;
1123
+
1124
+ if (kn > kEpsilon) {
1125
+ const double restitution = std::max(bullet.restitution, target.restitution);
1126
+ const double jn = -(1.0 + restitution) * vn / kn;
1127
+ const Vec2 impulseN = scale(normal, jn);
1128
+
1129
+ bullet.vx += impulseN.x * invMassA;
1130
+ bullet.vy += impulseN.y * invMassA;
1131
+ bullet.angularVelocity += cross(rA, impulseN) * invInertiaA;
1132
+
1133
+ if (target.type == BodyType::Dynamic) {
1134
+ target.vx -= impulseN.x * invMassB;
1135
+ target.vy -= impulseN.y * invMassB;
1136
+ target.angularVelocity -= cross(rB, impulseN) * invInertiaB;
1137
+ }
1138
+
1139
+ const Vec2 tangent{-normal.y, normal.x};
1140
+ const double vt = dot(vRel, tangent);
1141
+ const double crossAT = cross(rA, tangent);
1142
+ const double crossBT = cross(rB, tangent);
1143
+ const double kt = invMassA + invMassB + crossAT * crossAT * invInertiaA + crossBT * crossBT * invInertiaB;
1144
+
1145
+ if (kt > kEpsilon) {
1146
+ const double friction = std::sqrt(std::max(0.0, bullet.friction * target.friction));
1147
+ const double jtRaw = -vt / kt;
1148
+ const double maxJt = friction * jn;
1149
+ const double jt = clamp(jtRaw, -maxJt, maxJt);
1150
+ const Vec2 impulseT = scale(tangent, jt);
1151
+
1152
+ bullet.vx += impulseT.x * invMassA;
1153
+ bullet.vy += impulseT.y * invMassA;
1154
+ bullet.angularVelocity += cross(rA, impulseT) * invInertiaA;
1155
+
1156
+ if (target.type == BodyType::Dynamic) {
1157
+ target.vx -= impulseT.x * invMassB;
1158
+ target.vy -= impulseT.y * invMassB;
1159
+ target.angularVelocity -= cross(rB, impulseT) * invInertiaB;
1160
+ }
1161
+ }
1162
+ }
1163
+ }
1164
+
1165
+ // Residual time integration
1166
+ if (tResidual > 0.0) {
1167
+ bullet.x += bullet.vx * tResidual;
1168
+ bullet.y += bullet.vy * tResidual;
1169
+ bullet.angle += bullet.angularVelocity * tResidual;
1170
+
1171
+ if (target.type != BodyType::Static) {
1172
+ target.x += target.vx * tResidual;
1173
+ target.y += target.vy * tResidual;
1174
+ target.angle += target.angularVelocity * tResidual;
1175
+ }
1176
+ }
1177
+
1178
+ ccdHandled[i] = true;
1179
+ if (target.type != BodyType::Static) ccdHandled[targetIndex] = true;
1180
+ }
1181
+
1182
+ // 3. Integrate positions for non-CCD bodies
1183
+ for (std::uint32_t i = 0; i < bodyCount; ++i) {
1184
+ if (ccdHandled[i]) continue;
1185
+ Body& b = bodies[i];
1186
+ if (b.type != BodyType::Static) {
1187
+ b.x += b.vx * substepDt;
1188
+ b.y += b.vy * substepDt;
1189
+ b.angle += b.angularVelocity * substepDt;
1190
+ }
1191
+ }
1192
+ }
1193
+
1194
+ for (std::uint32_t i = 0; i < bodyCount; ++i) {
1195
+ bodies[i].forceX = 0.0;
1196
+ bodies[i].forceY = 0.0;
1197
+ bodies[i].torque = 0.0;
1198
+ }
1199
+
1200
+ return kStepOk;
1201
+ }
1202
+
1203
+ std::int32_t stepWithCcd(
1204
+ Body* bodies,
1205
+ std::uint32_t bodyCount,
1206
+ const StepOptions& options,
1207
+ const bool* bulletFlags,
1208
+ CcdStepStats2D* stats) {
1209
+ return stepWithCcd(detail::legacyPhysicsContext(), bodies, bodyCount, options, bulletFlags, stats);
1210
+ }
1211
+
1212
+ } // namespace rundot::kinetix::physics2d
1213
+
1214
+ extern "C" {
1215
+
1216
+ std::uint32_t rundot_physics2d_ccd_abi_version() {
1217
+ return rundot::kinetix::physics2d::kCcdAbiVersion;
1218
+ }
1219
+
1220
+ std::int32_t rundot_physics2d_ccd_time_of_impact(
1221
+ const rundot::kinetix::physics2d::Body* bodyA,
1222
+ const rundot::kinetix::physics2d::Body* bodyB,
1223
+ double dt,
1224
+ double* outToi,
1225
+ double* outNormalX,
1226
+ double* outNormalY,
1227
+ double* outPointX,
1228
+ double* outPointY) {
1229
+ if (bodyA == nullptr || bodyB == nullptr || dt <= 0.0) return -1;
1230
+ const auto res = rundot::kinetix::physics2d::computeTimeOfImpact2D(
1231
+ rundot::kinetix::physics2d::detail::legacyPhysicsContext(), *bodyA, *bodyB, dt);
1232
+ if (outToi != nullptr) *outToi = res.toi;
1233
+ if (outNormalX != nullptr) *outNormalX = res.normal.x;
1234
+ if (outNormalY != nullptr) *outNormalY = res.normal.y;
1235
+ if (outPointX != nullptr) *outPointX = res.point.x;
1236
+ if (outPointY != nullptr) *outPointY = res.point.y;
1237
+ return res.hit ? 1 : 0;
1238
+ }
1239
+
1240
+ std::int32_t rundot_physics2d_ccd_time_of_impact_ex(
1241
+ const rundot::kinetix::physics2d::Body* bodyA,
1242
+ const rundot::kinetix::physics2d::Body* bodyB,
1243
+ double dt,
1244
+ double targetSeparation,
1245
+ std::uint32_t maxIterations,
1246
+ double* outToi,
1247
+ double* outTime,
1248
+ double* outNormalX,
1249
+ double* outNormalY,
1250
+ double* outPointX,
1251
+ double* outPointY,
1252
+ double* outSeparation,
1253
+ std::uint32_t* outIterations) {
1254
+ if (bodyA == nullptr || bodyB == nullptr || !std::isfinite(dt) || dt <= 0.0
1255
+ || !std::isfinite(targetSeparation) || targetSeparation < 0.0
1256
+ || maxIterations == 0 || maxIterations > 256) return -1;
1257
+ const auto result = rundot::kinetix::physics2d::computeTimeOfImpact2D(
1258
+ rundot::kinetix::physics2d::detail::legacyPhysicsContext(),
1259
+ *bodyA,
1260
+ *bodyB,
1261
+ dt,
1262
+ targetSeparation,
1263
+ maxIterations);
1264
+ if (outToi != nullptr) *outToi = result.toi;
1265
+ if (outTime != nullptr) *outTime = result.time;
1266
+ if (outNormalX != nullptr) *outNormalX = result.normal.x;
1267
+ if (outNormalY != nullptr) *outNormalY = result.normal.y;
1268
+ if (outPointX != nullptr) *outPointX = result.point.x;
1269
+ if (outPointY != nullptr) *outPointY = result.point.y;
1270
+ if (outSeparation != nullptr) *outSeparation = result.separation;
1271
+ if (outIterations != nullptr) *outIterations = result.iterations;
1272
+ return result.hit ? 1 : 0;
1273
+ }
1274
+
1275
+ std::int32_t rundot_physics2d_ccd_step(
1276
+ rundot::kinetix::physics2d::Body* bodies,
1277
+ std::uint32_t bodyCount,
1278
+ double dt,
1279
+ double gravityX,
1280
+ double gravityY,
1281
+ std::uint32_t substeps,
1282
+ std::uint32_t velocityIterations,
1283
+ const std::uint8_t* bulletFlags) {
1284
+ if (bodies == nullptr || bodyCount == 0 || dt <= 0.0) return -1;
1285
+ rundot::kinetix::physics2d::StepOptions options{};
1286
+ options.dt = dt;
1287
+ options.gravityX = gravityX;
1288
+ options.gravityY = gravityY;
1289
+ options.substeps = substeps > 0 ? substeps : 1;
1290
+ options.velocityIterations = velocityIterations > 0 ? velocityIterations : 6;
1291
+
1292
+ bool flags[rundot::kinetix::physics2d::kMaxBodies]{};
1293
+ if (bulletFlags != nullptr) {
1294
+ const std::uint32_t count = std::min(bodyCount, rundot::kinetix::physics2d::kMaxBodies);
1295
+ for (std::uint32_t i = 0; i < count; ++i) flags[i] = (bulletFlags[i] != 0);
1296
+ }
1297
+
1298
+ return rundot::kinetix::physics2d::stepWithCcd(
1299
+ bodies, bodyCount, options, bulletFlags != nullptr ? flags : nullptr, nullptr);
1300
+ }
1301
+
1302
+ }