@series-inc/rundot-syncplay 6.0.0-rc.90 → 6.0.0-rc.92
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.
- package/README.md +7 -0
- package/core/native/physics/physics.cpp +146 -24
- package/core/native/physics2d/owned_abi.cpp +32 -0
- package/core/native/physics2d/owned_abi.hpp +18 -0
- package/core/physics2d-owned.d.ts +1 -0
- package/core/scripts/box3d-native-build.mjs +56 -2
- package/core/scripts/build-wasm-physics.mjs +161 -16
- package/core/src/kinetix-owned-runtime-adapter.mjs +10 -5
- package/core/src/kinetix-runtime-adapter-utils.mjs +15 -10
- package/core/src/physics/physics-profile-wasm-module.generated.mjs +4 -4
- package/core/src/physics/physics-profile.wasm +0 -0
- package/core/src/physics/physics-wasm-module.generated.mjs +4 -4
- package/core/src/physics/physics.wasm +0 -0
- package/core/src/physics/world.mjs +47 -2
- package/core/src/physics2d/owned-transport.mjs +37 -0
- package/core/src/physics2d/owned-world.mjs +5 -0
- package/core/src/physics2d/physics2d-wasm-module.generated.mjs +5 -5
- package/core/src/physics2d/physics2d.wasm +0 -0
- package/dist/dev-authority-room.js +5 -1
- package/dist/networked-client.js +18 -0
- package/dist/physics/2d.d.ts +1 -0
- package/dist/physics/2d.js +4 -1
- package/dist/presentation.d.ts +51 -0
- package/dist/presentation.js +98 -0
- package/package.json +19 -3
package/README.md
CHANGED
|
@@ -284,6 +284,13 @@ metadata never silently passes negotiation.
|
|
|
284
284
|
|
|
285
285
|
## Presentation frames
|
|
286
286
|
|
|
287
|
+
The optional `@series-inc/rundot-syncplay/presentation` entry provides reusable
|
|
288
|
+
2D pose and 3D motion buffers, plus helpers for Three.js instanced matrices and PixiJS 2D
|
|
289
|
+
transforms. It imports neither renderer. See
|
|
290
|
+
[`SYNCPLAY-PRESENTATION.md`](../sdk-docs/rundot-developer-platform/api/SYNCPLAY-PRESENTATION.md)
|
|
291
|
+
for buffer ownership, slot mapping, and examples. This entry is staged
|
|
292
|
+
for 6.0.0-rc.91. Use it after that version is published.
|
|
293
|
+
|
|
287
294
|
`session.getState()` returns a detached deep copy of the current frame, which
|
|
288
295
|
costs O(state) per read and is unaffordable for a large mutable world (a
|
|
289
296
|
destructible voxel city, a big streaming map).
|
|
@@ -3634,7 +3634,140 @@ Vec3 toiCoreSupport(SolverOperation& operation, const Body& body, const Vec3& di
|
|
|
3634
3634
|
return supportPointForBody(operation, body, direction);
|
|
3635
3635
|
}
|
|
3636
3636
|
|
|
3637
|
-
ToiDistance
|
|
3637
|
+
ToiDistance toiCoreDistanceImpl(SolverOperation& operation, const Body& first, const Body& second,
|
|
3638
|
+
bool segmentFallback);
|
|
3639
|
+
|
|
3640
|
+
// The two ends of a capsule core segment, in world space.
|
|
3641
|
+
void capsuleSegmentEnds(const Body& capsule, Vec3& start, Vec3& end) {
|
|
3642
|
+
const Vec3 center{capsule.x + capsule.shapeOffsetX, capsule.y + capsule.shapeOffsetY,
|
|
3643
|
+
capsule.z + capsule.shapeOffsetZ};
|
|
3644
|
+
const Vec3 axis = rotateByOrientation(capsule, {0.0, 1.0, 0.0});
|
|
3645
|
+
start = addVec3(center, scaleVec3(axis, -capsule.shape1));
|
|
3646
|
+
end = addVec3(center, scaleVec3(axis, capsule.shape1));
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
// Closest points of two segments (Ericson 5.1.9, clamped). Returns the vector
|
|
3650
|
+
// from the closest point of the second segment to the closest point of the first.
|
|
3651
|
+
double clampUnitInterval(double v) { return v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v); }
|
|
3652
|
+
|
|
3653
|
+
Vec3 segmentSegmentClosest(const Vec3& p1, const Vec3& q1, const Vec3& p2, const Vec3& q2) {
|
|
3654
|
+
const Vec3 d1 = subtractVec3(q1, p1);
|
|
3655
|
+
const Vec3 d2 = subtractVec3(q2, p2);
|
|
3656
|
+
const Vec3 r = subtractVec3(p1, p2);
|
|
3657
|
+
const double a = dotVec3(d1, d1);
|
|
3658
|
+
const double e = dotVec3(d2, d2);
|
|
3659
|
+
const double f = dotVec3(d2, r);
|
|
3660
|
+
double s = 0.0;
|
|
3661
|
+
double t = 0.0;
|
|
3662
|
+
if (a <= 1e-24 && e <= 1e-24) return r;
|
|
3663
|
+
if (a <= 1e-24) {
|
|
3664
|
+
t = e > 0.0 ? clampUnitInterval(f / e) : 0.0;
|
|
3665
|
+
} else {
|
|
3666
|
+
const double c = dotVec3(d1, r);
|
|
3667
|
+
if (e <= 1e-24) {
|
|
3668
|
+
s = clampUnitInterval(-c / a);
|
|
3669
|
+
} else {
|
|
3670
|
+
const double b = dotVec3(d1, d2);
|
|
3671
|
+
const double denom = a * e - b * b;
|
|
3672
|
+
s = denom > 1e-24 ? clampUnitInterval((b * f - c * e) / denom) : 0.0;
|
|
3673
|
+
t = (b * s + f) / e;
|
|
3674
|
+
if (t < 0.0) {
|
|
3675
|
+
t = 0.0;
|
|
3676
|
+
s = clampUnitInterval(-c / a);
|
|
3677
|
+
} else if (t > 1.0) {
|
|
3678
|
+
t = 1.0;
|
|
3679
|
+
s = clampUnitInterval((b - c) / a);
|
|
3680
|
+
}
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
return subtractVec3(addVec3(p1, scaleVec3(d1, s)), addVec3(p2, scaleVec3(d2, t)));
|
|
3684
|
+
}
|
|
3685
|
+
|
|
3686
|
+
// Exact capsule-segment distance for the non-converged GJK exits (issues 7194
|
|
3687
|
+
// and 7195). A capsule core is a segment: tied support points can cycle the
|
|
3688
|
+
// simplex without enclosing the origin, whether an end lies inside the other
|
|
3689
|
+
// core or the segment crosses it with both ends outside. The minimum of the
|
|
3690
|
+
// point-to-core distance along the segment is the true core distance, and
|
|
3691
|
+
// that function is convex, so a fixed-count ternary search finds it. Point
|
|
3692
|
+
// cores have no segment cycle. Capsule-capsule and capsule-sphere pairs use
|
|
3693
|
+
// the closed forms above. Returns false when neither body is a capsule.
|
|
3694
|
+
bool capsuleSegmentFallback(SolverOperation& operation, const Body& first, const Body& second, ToiDistance& out) {
|
|
3695
|
+
const Body* capsule = first.shape == ShapeKind::Capsule ? &first
|
|
3696
|
+
: second.shape == ShapeKind::Capsule ? &second : nullptr;
|
|
3697
|
+
if (capsule == nullptr) return false;
|
|
3698
|
+
const Body& other = capsule == &first ? second : first;
|
|
3699
|
+
const bool capsuleIsFirst = capsule == &first;
|
|
3700
|
+
Vec3 start;
|
|
3701
|
+
Vec3 end;
|
|
3702
|
+
capsuleSegmentEnds(*capsule, start, end);
|
|
3703
|
+
auto finish = [](const Vec3& closestVec) {
|
|
3704
|
+
const double distance = solverSqrt(dotVec3(closestVec, closestVec));
|
|
3705
|
+
if (distance <= 1e-12) return ToiDistance{0.0, {}, true};
|
|
3706
|
+
return ToiDistance{distance, scaleVec3(closestVec, -1.0 / distance), false};
|
|
3707
|
+
};
|
|
3708
|
+
if (other.shape == ShapeKind::Capsule) {
|
|
3709
|
+
Vec3 otherStart;
|
|
3710
|
+
Vec3 otherEnd;
|
|
3711
|
+
capsuleSegmentEnds(other, otherStart, otherEnd);
|
|
3712
|
+
out = capsuleIsFirst
|
|
3713
|
+
? finish(segmentSegmentClosest(start, end, otherStart, otherEnd))
|
|
3714
|
+
: finish(segmentSegmentClosest(otherStart, otherEnd, start, end));
|
|
3715
|
+
return true;
|
|
3716
|
+
}
|
|
3717
|
+
if (other.shape == ShapeKind::Sphere) {
|
|
3718
|
+
const Vec3 center{other.x + other.shapeOffsetX, other.y + other.shapeOffsetY, other.z + other.shapeOffsetZ};
|
|
3719
|
+
out = capsuleIsFirst
|
|
3720
|
+
? finish(segmentSegmentClosest(start, end, center, center))
|
|
3721
|
+
: finish(segmentSegmentClosest(center, center, start, end));
|
|
3722
|
+
return true;
|
|
3723
|
+
}
|
|
3724
|
+
auto pointAt = [&](double t) {
|
|
3725
|
+
Body point = *capsule;
|
|
3726
|
+
point.shape = ShapeKind::Sphere;
|
|
3727
|
+
point.shape0 = 0.0;
|
|
3728
|
+
point.shapeOffsetX = point.shapeOffsetY = point.shapeOffsetZ = 0.0;
|
|
3729
|
+
const Vec3 at = addVec3(start, scaleVec3(subtractVec3(end, start), t));
|
|
3730
|
+
point.x = at.x;
|
|
3731
|
+
point.y = at.y;
|
|
3732
|
+
point.z = at.z;
|
|
3733
|
+
return capsuleIsFirst
|
|
3734
|
+
? toiCoreDistanceImpl(operation, point, other, false)
|
|
3735
|
+
: toiCoreDistanceImpl(operation, other, point, false);
|
|
3736
|
+
};
|
|
3737
|
+
ToiDistance best{};
|
|
3738
|
+
double bestValue = 0.0;
|
|
3739
|
+
bool haveBest = false;
|
|
3740
|
+
auto consider = [&](const ToiDistance& candidate) {
|
|
3741
|
+
const double value = candidate.overlap ? 0.0 : candidate.distance;
|
|
3742
|
+
if (!haveBest || value < bestValue) {
|
|
3743
|
+
best = candidate;
|
|
3744
|
+
bestValue = value;
|
|
3745
|
+
haveBest = true;
|
|
3746
|
+
}
|
|
3747
|
+
};
|
|
3748
|
+
consider(pointAt(0.0));
|
|
3749
|
+
if (best.overlap) { out = best; return true; }
|
|
3750
|
+
consider(pointAt(1.0));
|
|
3751
|
+
if (best.overlap) { out = best; return true; }
|
|
3752
|
+
double lo = 0.0;
|
|
3753
|
+
double hi = 1.0;
|
|
3754
|
+
for (int i = 0; i < 90; i += 1) {
|
|
3755
|
+
const double m1 = lo + (hi - lo) / 3.0;
|
|
3756
|
+
const double m2 = hi - (hi - lo) / 3.0;
|
|
3757
|
+
const ToiDistance d1 = pointAt(m1);
|
|
3758
|
+
consider(d1);
|
|
3759
|
+
if (best.overlap) { out = best; return true; }
|
|
3760
|
+
const ToiDistance d2 = pointAt(m2);
|
|
3761
|
+
consider(d2);
|
|
3762
|
+
if (best.overlap) { out = best; return true; }
|
|
3763
|
+
if (d1.distance <= d2.distance) hi = m2; else lo = m1;
|
|
3764
|
+
}
|
|
3765
|
+
out = best.distance <= 1e-12 ? ToiDistance{0.0, {}, true} : best;
|
|
3766
|
+
return true;
|
|
3767
|
+
}
|
|
3768
|
+
|
|
3769
|
+
ToiDistance toiCoreDistanceImpl(SolverOperation& operation, const Body& first, const Body& second,
|
|
3770
|
+
bool segmentFallback) {
|
|
3638
3771
|
Vec3 direction{
|
|
3639
3772
|
first.x + first.shapeOffsetX - second.x - second.shapeOffsetX,
|
|
3640
3773
|
first.y + first.shapeOffsetY - second.y - second.shapeOffsetY,
|
|
@@ -3648,6 +3781,7 @@ ToiDistance toiCoreDistance(SolverOperation& operation, const Body& first, const
|
|
|
3648
3781
|
simplex.points[0] = support(scaleVec3(direction, -1.0));
|
|
3649
3782
|
simplex.count = 1;
|
|
3650
3783
|
Vec3 closest = simplex.points[0];
|
|
3784
|
+
bool converged = false;
|
|
3651
3785
|
for (std::uint32_t iteration = 0; iteration < 24; iteration += 1) {
|
|
3652
3786
|
const ToiClosest result = toiClosestToOrigin(simplex);
|
|
3653
3787
|
if (result.overlap) return {0.0, {}, true};
|
|
@@ -3661,7 +3795,7 @@ ToiDistance toiCoreDistance(SolverOperation& operation, const Body& first, const
|
|
|
3661
3795
|
simplex = reduced;
|
|
3662
3796
|
const Vec3 search = scaleVec3(closest, -1.0);
|
|
3663
3797
|
const Vec3 candidate = support(search);
|
|
3664
|
-
if (dotVec3(candidate, search) - dotVec3(closest, search) < 1e-10) break;
|
|
3798
|
+
if (dotVec3(candidate, search) - dotVec3(closest, search) < 1e-10) { converged = true; break; }
|
|
3665
3799
|
bool repeated = false;
|
|
3666
3800
|
for (std::uint32_t index = 0; index < simplex.count; index += 1) {
|
|
3667
3801
|
const Vec3 delta = subtractVec3(simplex.points[index], candidate);
|
|
@@ -3674,28 +3808,12 @@ ToiDistance toiCoreDistance(SolverOperation& operation, const Body& first, const
|
|
|
3674
3808
|
simplex.points[simplex.count] = candidate;
|
|
3675
3809
|
simplex.count += 1;
|
|
3676
3810
|
}
|
|
3677
|
-
//
|
|
3678
|
-
//
|
|
3679
|
-
//
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
if (
|
|
3683
|
-
const Body& other = capsule == &first ? second : first;
|
|
3684
|
-
const Vec3 center{capsule->x + capsule->shapeOffsetX, capsule->y + capsule->shapeOffsetY,
|
|
3685
|
-
capsule->z + capsule->shapeOffsetZ};
|
|
3686
|
-
const Vec3 axis = rotateByOrientation(*capsule, {0.0, 1.0, 0.0});
|
|
3687
|
-
for (const double sign : {1.0, -1.0}) {
|
|
3688
|
-
Body point = *capsule;
|
|
3689
|
-
point.shape = ShapeKind::Sphere;
|
|
3690
|
-
point.shape0 = 0.0;
|
|
3691
|
-
point.shapeOffsetX = point.shapeOffsetY = point.shapeOffsetZ = 0.0;
|
|
3692
|
-
const Vec3 end = addVec3(center, scaleVec3(axis, sign * capsule->shape1));
|
|
3693
|
-
point.x = end.x;
|
|
3694
|
-
point.y = end.y;
|
|
3695
|
-
point.z = end.z;
|
|
3696
|
-
const ToiDistance endDistance = toiCoreDistance(operation, point, other);
|
|
3697
|
-
if (endDistance.overlap || endDistance.distance <= 1e-12) return {0.0, {}, true};
|
|
3698
|
-
}
|
|
3811
|
+
// Only a non-converged exit (repeated support, full simplex, or the
|
|
3812
|
+
// iteration cap) can report a false positive distance for a capsule pair.
|
|
3813
|
+
// Converged exits keep the simplex result and pay no fallback cost.
|
|
3814
|
+
if (segmentFallback && !converged) {
|
|
3815
|
+
ToiDistance fallback;
|
|
3816
|
+
if (capsuleSegmentFallback(operation, first, second, fallback)) return fallback;
|
|
3699
3817
|
}
|
|
3700
3818
|
const double distance = solverSqrt(dotVec3(closest, closest));
|
|
3701
3819
|
return {
|
|
@@ -3705,6 +3823,10 @@ ToiDistance toiCoreDistance(SolverOperation& operation, const Body& first, const
|
|
|
3705
3823
|
};
|
|
3706
3824
|
}
|
|
3707
3825
|
|
|
3826
|
+
ToiDistance toiCoreDistance(SolverOperation& operation, const Body& first, const Body& second) {
|
|
3827
|
+
return toiCoreDistanceImpl(operation, first, second, true);
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3708
3830
|
bool robustConvexBodiesOverlap(SolverOperation& operation, const Body& a, const Body& b) {
|
|
3709
3831
|
if (a.shape == ShapeKind::Mesh || b.shape == ShapeKind::Mesh) return false;
|
|
3710
3832
|
if (!toiSupported(a) || !toiSupported(b)) return convexBodiesOverlap(operation, a, b);
|
|
@@ -482,6 +482,7 @@ using namespace rundot::kinetix::physics2d::owned_abi;
|
|
|
482
482
|
extern "C" {
|
|
483
483
|
|
|
484
484
|
std::uint32_t rundot_physics2d_owned_c_abi_version() noexcept { return kCAbiVersion; }
|
|
485
|
+
std::uint32_t rundot_physics2d_owned_body_pose_size() noexcept { return sizeof(BodyPose2D); }
|
|
485
486
|
std::uint32_t rundot_physics2d_owned_world_storage_abi_version() noexcept { return kWorldStorageAbiVersion; }
|
|
486
487
|
std::uint32_t rundot_physics2d_owned_snapshot_version() noexcept { return kSnapshotVersion; }
|
|
487
488
|
std::uint32_t rundot_physics2d_owned_required_settings_abi_version() noexcept { return kSettingsAbiVersion; }
|
|
@@ -931,6 +932,37 @@ std::uint64_t rundot_physics2d_owned_world_read_body(std::uint64_t registry,
|
|
|
931
932
|
});
|
|
932
933
|
}
|
|
933
934
|
|
|
935
|
+
std::uint64_t rundot_physics2d_owned_world_write_body_poses(std::uint64_t registry,
|
|
936
|
+
const WorldKey* key, BodyPose2D* poses, std::uint32_t* ids,
|
|
937
|
+
std::uint32_t capacity, std::uint32_t* count) noexcept {
|
|
938
|
+
std::size_t poseBytes = 0;
|
|
939
|
+
std::size_t idBytes = 0;
|
|
940
|
+
if (!checkedBytes(capacity, sizeof(BodyPose2D), poseBytes)
|
|
941
|
+
|| !checkedBytes(capacity, sizeof(std::uint32_t), idBytes)
|
|
942
|
+
|| poseBytes > std::numeric_limits<std::uint32_t>::max()
|
|
943
|
+
|| idBytes > std::numeric_limits<std::uint32_t>::max()) {
|
|
944
|
+
return admissionFailure(AdmitStatus::InvalidRange);
|
|
945
|
+
}
|
|
946
|
+
const CallerRange ranges[] = {inOne(key), outBytes(poses, poseBytes),
|
|
947
|
+
outBytes(ids, idBytes), outOne(count)};
|
|
948
|
+
return withWorld(registry, ranges, [capacity](Call& call) noexcept {
|
|
949
|
+
BodyPose2D* poseOut = nullptr;
|
|
950
|
+
std::uint32_t* idOut = nullptr;
|
|
951
|
+
std::uint32_t* countOut = nullptr;
|
|
952
|
+
if (!bindArray(call.pins, 1, poseOut) || !bindArray(call.pins, 2, idOut)
|
|
953
|
+
|| !bindScalar(call.pins, 3, countOut)) return failure(Status::InvalidArguments);
|
|
954
|
+
const auto state = call.op.world->state();
|
|
955
|
+
if (state.bodyCount > capacity) return failure(Status::OutputCapacity);
|
|
956
|
+
for (std::uint32_t index = 0; index < state.bodyCount; ++index) {
|
|
957
|
+
const Body& body = state.bodies[index];
|
|
958
|
+
poseOut[index] = {body.x, body.y, body.angle};
|
|
959
|
+
idOut[index] = body.id;
|
|
960
|
+
}
|
|
961
|
+
*countOut = state.bodyCount;
|
|
962
|
+
return success();
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
|
|
934
966
|
std::uint64_t rundot_physics2d_owned_world_read_joint(std::uint64_t registry,
|
|
935
967
|
const WorldKey* key, const EntityHandle2D* handlePointer,
|
|
936
968
|
JointRecord2D* outputJoint, JointState2D* outputState) noexcept {
|
|
@@ -72,6 +72,16 @@ struct WorldCapacity {
|
|
|
72
72
|
};
|
|
73
73
|
static_assert(sizeof(WorldCapacity) == 24);
|
|
74
74
|
|
|
75
|
+
struct BodyPose2D {
|
|
76
|
+
double x;
|
|
77
|
+
double y;
|
|
78
|
+
double angle;
|
|
79
|
+
};
|
|
80
|
+
static_assert(sizeof(BodyPose2D) == 24);
|
|
81
|
+
static_assert(offsetof(BodyPose2D, x) == 0);
|
|
82
|
+
static_assert(offsetof(BodyPose2D, y) == 8);
|
|
83
|
+
static_assert(offsetof(BodyPose2D, angle) == 16);
|
|
84
|
+
|
|
75
85
|
struct CheckpointToken {
|
|
76
86
|
std::uint32_t slotIndex = 0;
|
|
77
87
|
std::uint32_t generation = 0;
|
|
@@ -260,6 +270,7 @@ extern "C" {
|
|
|
260
270
|
// A registry handle names one directory entry. A copy of the handle is the same name.
|
|
261
271
|
|
|
262
272
|
std::uint32_t rundot_physics2d_owned_c_abi_version() noexcept;
|
|
273
|
+
std::uint32_t rundot_physics2d_owned_body_pose_size() noexcept;
|
|
263
274
|
std::uint32_t rundot_physics2d_owned_world_storage_abi_version() noexcept;
|
|
264
275
|
std::uint32_t rundot_physics2d_owned_snapshot_version() noexcept;
|
|
265
276
|
std::uint32_t rundot_physics2d_owned_required_settings_abi_version() noexcept;
|
|
@@ -359,6 +370,13 @@ std::uint64_t rundot_physics2d_owned_world_read_body(
|
|
|
359
370
|
const rundot::kinetix::physics2d::EntityHandle2D* body,
|
|
360
371
|
rundot::kinetix::physics2d::Body* outputBody,
|
|
361
372
|
rundot::kinetix::physics2d::PolygonGeometry* outputGeometry) noexcept;
|
|
373
|
+
std::uint64_t rundot_physics2d_owned_world_write_body_poses(
|
|
374
|
+
std::uint64_t registry,
|
|
375
|
+
const rundot::kinetix::physics2d::owned_abi::WorldKey* world,
|
|
376
|
+
rundot::kinetix::physics2d::owned_abi::BodyPose2D* poses,
|
|
377
|
+
std::uint32_t* ids,
|
|
378
|
+
std::uint32_t capacity,
|
|
379
|
+
std::uint32_t* count) noexcept;
|
|
362
380
|
std::uint64_t rundot_physics2d_owned_world_read_joint(
|
|
363
381
|
std::uint64_t registry,
|
|
364
382
|
const rundot::kinetix::physics2d::owned_abi::WorldKey* world,
|
|
@@ -712,6 +712,7 @@ export interface OwnedPhysicsWorld2D {
|
|
|
712
712
|
setGravity(x: MetersPerSecondSquared, y: MetersPerSecondSquared): void;
|
|
713
713
|
edit<T = unknown>(build: (ops: PhysicsEditOps2D) => T): PhysicsEditResult2D<T>;
|
|
714
714
|
readBody(handle: PhysicsBodyHandle2D): PhysicsBody2D;
|
|
715
|
+
writeBodyPosesInto(poses: Float64Array, ids: Uint32Array): number;
|
|
715
716
|
readJoint(handle: PhysicsJointHandle2D): PhysicsJointRecord2D;
|
|
716
717
|
readFluid(handle: PhysicsFluidHandle2D): PhysicsFluid2D;
|
|
717
718
|
resolveBody(id: number): PhysicsBodyHandle2D;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Internal native Box3D build inputs. This module has no direct-invocation side effects.
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import {
|
|
7
7
|
ALL_C_SOURCES as BOX3D_C_SOURCES,
|
|
@@ -38,6 +38,41 @@ export const BOX3D_NATIVE_CXX_FLAGS = [
|
|
|
38
38
|
// no code of a C function, only the unwind data beside it.
|
|
39
39
|
export const BOX3D_C_UNWIND_FLAGS = Object.freeze(['-fexceptions']);
|
|
40
40
|
|
|
41
|
+
// One builder at a time across processes. The archive container bytes are not
|
|
42
|
+
// reproducible across builds (the members are), and build-native.mjs hashes
|
|
43
|
+
// the archive into its binary fingerprint, so parallel test processes must
|
|
44
|
+
// share one built archive instead of each publishing their own. The lock
|
|
45
|
+
// shape mirrors acquireWasmBuildLock in build-wasm-physics.mjs.
|
|
46
|
+
function acquireBox3dNativeBuildLock() {
|
|
47
|
+
const lockPath = join(outDir, 'box3d-native-build.lock');
|
|
48
|
+
mkdirSync(outDir, { recursive: true });
|
|
49
|
+
const started = Date.now();
|
|
50
|
+
for (;;) {
|
|
51
|
+
try {
|
|
52
|
+
mkdirSync(lockPath);
|
|
53
|
+
break;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error.code !== 'EEXIST') throw error;
|
|
56
|
+
let age = 0;
|
|
57
|
+
try {
|
|
58
|
+
age = Date.now() - statSync(lockPath).mtimeMs;
|
|
59
|
+
} catch (statError) {
|
|
60
|
+
if (statError.code === 'ENOENT') continue;
|
|
61
|
+
throw statError;
|
|
62
|
+
}
|
|
63
|
+
if (age > 3600000) {
|
|
64
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (Date.now() - started > 600000) {
|
|
68
|
+
throw new Error(`KINETIX_BOX3D_NATIVE_BUILD_BUSY ${lockPath}`);
|
|
69
|
+
}
|
|
70
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return () => rmSync(lockPath, { recursive: true, force: true });
|
|
74
|
+
}
|
|
75
|
+
|
|
41
76
|
export function buildBox3dArchive() {
|
|
42
77
|
const hash = createHash('sha256');
|
|
43
78
|
hash.update(BOX3D_NATIVE_FLAGS.join(' '));
|
|
@@ -56,7 +91,21 @@ export function buildBox3dArchive() {
|
|
|
56
91
|
const key = hash.digest('hex').slice(0, 16);
|
|
57
92
|
const objectDirectory = join(outDir, `box3d-native-${key}`);
|
|
58
93
|
const archive = join(objectDirectory, 'libbox3d.a');
|
|
94
|
+
// Cache hit: the archive only ever appears via the atomic rename below, so
|
|
95
|
+
// its mere existence guarantees a complete file.
|
|
59
96
|
if (existsSync(archive)) return archive;
|
|
97
|
+
const releaseLock = acquireBox3dNativeBuildLock();
|
|
98
|
+
try {
|
|
99
|
+
// A process that waited on the lock rechecks: the builder ahead of it
|
|
100
|
+
// may have published this exact archive.
|
|
101
|
+
if (existsSync(archive)) return archive;
|
|
102
|
+
return buildBox3dArchiveLocked(objectDirectory, archive);
|
|
103
|
+
} finally {
|
|
104
|
+
releaseLock();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function buildBox3dArchiveLocked(objectDirectory, archive) {
|
|
60
109
|
mkdirSync(objectDirectory, { recursive: true });
|
|
61
110
|
const objects = [];
|
|
62
111
|
for (const source of BOX3D_C_SOURCES) {
|
|
@@ -91,7 +140,12 @@ export function buildBox3dArchive() {
|
|
|
91
140
|
if (built.status !== 0) throw new Error(`KINETIX_LZMA_NATIVE_BUILD_FAILED ${built.stderr}`);
|
|
92
141
|
objects.push(object);
|
|
93
142
|
}
|
|
94
|
-
|
|
143
|
+
// Archive to a per-process staging path, then atomically publish. The lock
|
|
144
|
+
// already excludes other builders; the rename keeps a killed build from
|
|
145
|
+
// leaving a partial archive that the cache check above would trust.
|
|
146
|
+
const stagingArchive = `${archive}.${process.pid}.tmp`;
|
|
147
|
+
const archived = spawnSync('ar', ['rcs', stagingArchive, ...objects], { encoding: 'utf8' });
|
|
95
148
|
if (archived.status !== 0) throw new Error(`KINETIX_BOX3D_NATIVE_ARCHIVE_FAILED ${archived.stderr}`);
|
|
149
|
+
renameSync(stagingArchive, archive);
|
|
96
150
|
return archive;
|
|
97
151
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
3
|
import { mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { availableParallelism } from 'node:os';
|
|
4
5
|
import { dirname, join, resolve } from 'node:path';
|
|
5
6
|
import { fileURLToPath } from 'node:url';
|
|
6
7
|
|
|
@@ -530,6 +531,7 @@ const profiles = {
|
|
|
530
531
|
exportedFunctions: [
|
|
531
532
|
'_malloc', '_free',
|
|
532
533
|
'_rundot_physics2d_owned_c_abi_version',
|
|
534
|
+
'_rundot_physics2d_owned_body_pose_size',
|
|
533
535
|
'_rundot_physics2d_owned_checkpoint_token_size',
|
|
534
536
|
'_rundot_physics2d_owned_instance_ledger_info',
|
|
535
537
|
'_rundot_physics2d_owned_instance_ledger_reset',
|
|
@@ -577,6 +579,7 @@ const profiles = {
|
|
|
577
579
|
'_rundot_physics2d_owned_world_resolve_joint',
|
|
578
580
|
'_rundot_physics2d_owned_world_resolve_fluid',
|
|
579
581
|
'_rundot_physics2d_owned_world_read_body',
|
|
582
|
+
'_rundot_physics2d_owned_world_write_body_poses',
|
|
580
583
|
'_rundot_physics2d_owned_world_read_joint',
|
|
581
584
|
'_rundot_physics2d_owned_world_read_fluid',
|
|
582
585
|
'_rundot_physics2d_owned_world_read_contour_edges',
|
|
@@ -757,6 +760,17 @@ function sourceHash(profile) {
|
|
|
757
760
|
return hash.digest('hex');
|
|
758
761
|
}
|
|
759
762
|
|
|
763
|
+
function isLinkOnlyFlag(flag) {
|
|
764
|
+
return flag === '--no-entry'
|
|
765
|
+
|| flag === '--profiling-funcs'
|
|
766
|
+
|| flag.startsWith('-Wl,')
|
|
767
|
+
|| /^-s[A-Z_]/u.test(flag);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function compileUnitFlags(profile) {
|
|
771
|
+
return compilerFlags(profile).filter((flag) => !isLinkOnlyFlag(flag));
|
|
772
|
+
}
|
|
773
|
+
|
|
760
774
|
function compilerFlags(profile) {
|
|
761
775
|
return [
|
|
762
776
|
'-std=c++20', profile.optimizationFlag ?? '-O3', '-ffp-contract=off', profile.exceptionFlag, '-fno-rtti',
|
|
@@ -770,6 +784,117 @@ function compilerFlags(profile) {
|
|
|
770
784
|
];
|
|
771
785
|
}
|
|
772
786
|
|
|
787
|
+
// The bound on parallel compile units. The default is the core count the OS reports. A caller
|
|
788
|
+
// on a loaded or memory-bound host can narrow it; 1 runs the units in series in this process.
|
|
789
|
+
function wasmCompileJobs() {
|
|
790
|
+
const raw = process.env.SYNCPLAY_WASM_JOBS;
|
|
791
|
+
if (raw === undefined || raw === '') return availableParallelism();
|
|
792
|
+
const jobs = Number(raw);
|
|
793
|
+
if (!Number.isInteger(jobs) || jobs < 1) {
|
|
794
|
+
throw new Error(`KINETIX_WASM_JOBS_INVALID SYNCPLAY_WASM_JOBS=${raw}`);
|
|
795
|
+
}
|
|
796
|
+
return jobs;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
function runCompileJob(spec, job) {
|
|
800
|
+
return new Promise((resolveJob) => {
|
|
801
|
+
const child = spawn(job.command, job.args, {
|
|
802
|
+
cwd: spec.cwd,
|
|
803
|
+
env: { ...process.env, EM_CACHE: spec.emCache },
|
|
804
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
805
|
+
});
|
|
806
|
+
let stderr = '';
|
|
807
|
+
child.stderr.setEncoding('utf8');
|
|
808
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
809
|
+
child.on('error', (error) => resolveJob({ status: 1, stderr: `${stderr}${error.message}` }));
|
|
810
|
+
child.on('close', (status) => resolveJob({ status: status ?? 1, stderr }));
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// The pool body. It runs in a helper process of this script (see the `--compile-jobs` branch of
|
|
815
|
+
// the entry block), so the exported build functions keep their synchronous shape: the caller
|
|
816
|
+
// blocks in one spawnSync while the helper runs the units across cores. A worker stops taking
|
|
817
|
+
// new units after the first failure; units already running finish. Results stay in job order.
|
|
818
|
+
async function runCompileJobs(specPath) {
|
|
819
|
+
const spec = JSON.parse(readFileSync(specPath, 'utf8'));
|
|
820
|
+
const results = new Array(spec.jobs.length).fill(null);
|
|
821
|
+
let next = 0;
|
|
822
|
+
let failed = false;
|
|
823
|
+
const worker = async () => {
|
|
824
|
+
while (!failed) {
|
|
825
|
+
const index = next;
|
|
826
|
+
next += 1;
|
|
827
|
+
if (index >= spec.jobs.length) return;
|
|
828
|
+
results[index] = await runCompileJob(spec, spec.jobs[index]);
|
|
829
|
+
if (results[index].status !== 0) failed = true;
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
const workers = Math.min(spec.concurrency, spec.jobs.length);
|
|
833
|
+
await Promise.all(Array.from({ length: workers }, () => worker()));
|
|
834
|
+
writeFileSync(spec.resultsPath, JSON.stringify(results));
|
|
835
|
+
return results.every((result) => result !== null && result.status === 0) ? 0 : 1;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// Run every compile unit of one profile, then report in unit order. The first failure in unit
|
|
839
|
+
// order throws the same error the serial loop threw. C++ warnings go to stderr in unit order,
|
|
840
|
+
// without link-only flags on the -c calls; C warnings stay dropped, as the C loop did.
|
|
841
|
+
function compileUnits(profile, jobs) {
|
|
842
|
+
const emCache = join(buildDirectory, 'em-cache');
|
|
843
|
+
const concurrency = wasmCompileJobs();
|
|
844
|
+
let results;
|
|
845
|
+
if (concurrency === 1 || jobs.length === 1) {
|
|
846
|
+
results = [];
|
|
847
|
+
for (const job of jobs) {
|
|
848
|
+
const result = spawnSync(job.command, job.args, {
|
|
849
|
+
cwd: root,
|
|
850
|
+
encoding: 'utf8',
|
|
851
|
+
env: { ...process.env, EM_CACHE: emCache },
|
|
852
|
+
});
|
|
853
|
+
results.push({ status: result.status ?? 1, stderr: result.stderr ?? `${result.error ?? ''}` });
|
|
854
|
+
if (results[results.length - 1].status !== 0) break;
|
|
855
|
+
}
|
|
856
|
+
while (results.length < jobs.length) results.push(null);
|
|
857
|
+
} else {
|
|
858
|
+
const specPath = join(buildDirectory, `compile-jobs-${process.pid}-${profile.wasmName}.json`);
|
|
859
|
+
const resultsPath = `${specPath}.results`;
|
|
860
|
+
try {
|
|
861
|
+
writeFileSync(specPath, JSON.stringify({
|
|
862
|
+
concurrency,
|
|
863
|
+
cwd: root,
|
|
864
|
+
emCache,
|
|
865
|
+
resultsPath,
|
|
866
|
+
jobs: jobs.map((job) => ({ command: job.command, args: job.args })),
|
|
867
|
+
}));
|
|
868
|
+
const helper = spawnSync(process.execPath, [fileURLToPath(import.meta.url), `--compile-jobs=${specPath}`], {
|
|
869
|
+
cwd: root,
|
|
870
|
+
encoding: 'utf8',
|
|
871
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
872
|
+
});
|
|
873
|
+
try {
|
|
874
|
+
results = JSON.parse(readFileSync(resultsPath, 'utf8'));
|
|
875
|
+
} catch {
|
|
876
|
+
throw new Error(`KINETIX_WASM_BUILD_FAILED compiler=compile-pool artifact=${profile.wasmName}\n${helper.stderr ?? ''}`);
|
|
877
|
+
}
|
|
878
|
+
} finally {
|
|
879
|
+
rmSync(specPath, { force: true });
|
|
880
|
+
rmSync(resultsPath, { force: true });
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
if (!Array.isArray(results) || results.length !== jobs.length) {
|
|
884
|
+
throw new Error(`KINETIX_WASM_BUILD_FAILED compiler=compile-pool artifact=${profile.wasmName}\ncompile pool returned no result per unit`);
|
|
885
|
+
}
|
|
886
|
+
for (const [index, job] of jobs.entries()) {
|
|
887
|
+
const result = results[index];
|
|
888
|
+
if (job.forwardStderr && result !== null && result.status === 0 && result.stderr !== '') {
|
|
889
|
+
process.stderr.write(result.stderr);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
const failure = results.findIndex((result) => result === null || result.status !== 0);
|
|
893
|
+
if (failure >= 0) {
|
|
894
|
+
throw new Error(`KINETIX_WASM_BUILD_FAILED compiler=${jobs[failure].command} artifact=${profile.wasmName}\n${results[failure]?.stderr ?? 'compile pool stopped before this unit'}`);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
773
898
|
function compileWasm(profile, compiler, wasmPath) {
|
|
774
899
|
// Sources go to the compiler relative to the working directory (`root`), as the include paths do. Then
|
|
775
900
|
// __FILE__ (the assert macros of the fork) holds a relative path, and the WASM bytes do not depend on the
|
|
@@ -777,25 +902,39 @@ function compileWasm(profile, compiler, wasmPath) {
|
|
|
777
902
|
mkdirSync(buildDirectory, { recursive: true });
|
|
778
903
|
const cSources = profile.compileSources.filter((source) => source.endsWith('.c'));
|
|
779
904
|
const cppSources = profile.compileSources.filter((source) => !source.endsWith('.c'));
|
|
780
|
-
const cObjects =
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
905
|
+
const cObjects = cSources.map((source) => join(buildDirectory, `${profile.wasmName}-${source.replaceAll('/', '_').replaceAll('.c', '.o')}`));
|
|
906
|
+
const cppObjects = cppSources.map((source) => join(buildDirectory, `${profile.wasmName}-${source.replaceAll('/', '_').replace(/\.(?:cpp|cc|cxx)$/u, '.o')}`));
|
|
907
|
+
const objects = [...cObjects, ...cppObjects];
|
|
908
|
+
if (new Set(objects).size !== objects.length) {
|
|
909
|
+
throw new Error(`KINETIX_WASM_OBJECT_COLLISION artifact=${profile.wasmName}`);
|
|
910
|
+
}
|
|
911
|
+
const jobs = [];
|
|
912
|
+
const unitFlags = compileUnitFlags(profile);
|
|
913
|
+
for (const [index, source] of cSources.entries()) {
|
|
914
|
+
jobs.push({
|
|
915
|
+
command: 'emcc',
|
|
916
|
+
args: [
|
|
917
|
+
profile.exceptionFlag, ...unitFlags.filter((flag) => flag !== '-std=c++20' && flag !== profile.exceptionFlag),
|
|
918
|
+
'-std=gnu17', '-c', source, '-o', cObjects[index],
|
|
919
|
+
],
|
|
920
|
+
forwardStderr: false,
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
for (const [index, source] of cppSources.entries()) {
|
|
924
|
+
jobs.push({
|
|
925
|
+
command: compiler,
|
|
926
|
+
args: [
|
|
927
|
+
...unitFlags,
|
|
928
|
+
'-c', source, '-o', cppObjects[index],
|
|
929
|
+
],
|
|
930
|
+
forwardStderr: true,
|
|
790
931
|
});
|
|
791
|
-
if (cResult.status !== 0) {
|
|
792
|
-
throw new Error(`KINETIX_WASM_BUILD_FAILED compiler=emcc artifact=${profile.wasmName}\n${cResult.stderr}`);
|
|
793
|
-
}
|
|
794
|
-
cObjects.push(object);
|
|
795
932
|
}
|
|
933
|
+
if (jobs.length !== 0) compileUnits(profile, jobs);
|
|
934
|
+
// The link keeps the order the single call used: every C++ unit first, then every C object.
|
|
796
935
|
const result = spawnSync(compiler, [
|
|
797
936
|
...compilerFlags(profile),
|
|
798
|
-
...
|
|
937
|
+
...cppObjects,
|
|
799
938
|
...cObjects,
|
|
800
939
|
'-o', wasmPath,
|
|
801
940
|
], {
|
|
@@ -1202,6 +1341,12 @@ function acquireWasmBuildLock() {
|
|
|
1202
1341
|
}
|
|
1203
1342
|
|
|
1204
1343
|
if (invokedDirectly()) {
|
|
1344
|
+
// Internal: the compile pool helper. It must run before any build lock, because the parent
|
|
1345
|
+
// process that spawns it already holds that lock.
|
|
1346
|
+
const compileJobsArgument = process.argv.find((argument) => argument.startsWith('--compile-jobs='));
|
|
1347
|
+
if (compileJobsArgument !== undefined) {
|
|
1348
|
+
process.exit(await runCompileJobs(compileJobsArgument.slice('--compile-jobs='.length)));
|
|
1349
|
+
}
|
|
1205
1350
|
const box3dCounterArgument = process.argv.find((argument) => argument.startsWith('--box3d-counter='));
|
|
1206
1351
|
if (box3dCounterArgument !== undefined) {
|
|
1207
1352
|
const record = await buildPhysicsWasmCounter(box3dCounterArgument.slice('--box3d-counter='.length));
|
|
@@ -932,6 +932,13 @@ export function createOwnedInstalledRuntimeAdapter(options) {
|
|
|
932
932
|
|
|
933
933
|
runtime.pinCheckpointSnapshot = (checkpoint) => {
|
|
934
934
|
const cell = lookupCell(checkpoint);
|
|
935
|
+
// Compute everything that can run a hook before taking any pin: a hook
|
|
936
|
+
// failure here must not strand a cell ref or an inner pin (issue 7156).
|
|
937
|
+
const cachedSerialized = cell.serialized !== null ? copyUint8Array(cell.serialized) : null;
|
|
938
|
+
const cachedWireChecksum = cell.wireChecksumHex ??= strongReport
|
|
939
|
+
? strongWireChecksum(cell)
|
|
940
|
+
: ensureChecksumHex(cell);
|
|
941
|
+
|
|
935
942
|
let innerPin;
|
|
936
943
|
const capturedPinMethod = extractCapturedPinMethod(cell.captured);
|
|
937
944
|
if (hooks.pinSnapshot !== undefined || capturedPinMethod !== undefined) {
|
|
@@ -949,6 +956,9 @@ export function createOwnedInstalledRuntimeAdapter(options) {
|
|
|
949
956
|
|| typeof innerPin.release !== 'function'
|
|
950
957
|
|| (innerPin.encodeBaselineDelta !== undefined && typeof innerPin.encodeBaselineDelta !== 'function')
|
|
951
958
|
) {
|
|
959
|
+
if (innerPin !== null && typeof innerPin === 'object' && typeof innerPin.release === 'function') {
|
|
960
|
+
try { innerPin.release(); } catch { /* the codec error below is the failure that matters */ }
|
|
961
|
+
}
|
|
952
962
|
fail('KINETIX_RUNTIME_CODEC_INVALID: invalid pinned snapshot handle');
|
|
953
963
|
}
|
|
954
964
|
}
|
|
@@ -958,11 +968,6 @@ export function createOwnedInstalledRuntimeAdapter(options) {
|
|
|
958
968
|
pin(cell);
|
|
959
969
|
heldCell = cell;
|
|
960
970
|
}
|
|
961
|
-
|
|
962
|
-
const cachedSerialized = cell.serialized !== null ? copyUint8Array(cell.serialized) : null;
|
|
963
|
-
const cachedWireChecksum = cell.wireChecksumHex ??= strongReport
|
|
964
|
-
? strongWireChecksum(cell)
|
|
965
|
-
: ensureChecksumHex(cell);
|
|
966
971
|
const baselineDigest = initialBaselineDigest;
|
|
967
972
|
const hasCustomAsync = Boolean(
|
|
968
973
|
innerPin !== undefined
|