@series-inc/rundot-syncplay 6.0.0-rc.62 → 6.0.0-rc.63

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.
@@ -1278,6 +1278,9 @@ Collision collide(SolverOperation& operation, const Body& a, const Body& b);
1278
1278
  Collision collideMaterialCurrent(SolverOperation& operation, const Body& a, const Body& b);
1279
1279
  Collision convexSupportCollision(SolverOperation& operation, const Body& a, const Body& b);
1280
1280
  bool robustConvexBodiesOverlap(SolverOperation& operation, const Body& a, const Body& b);
1281
+ bool triangleSoupBody(const Body& body);
1282
+ bool triangleSoupPartner(const Body& body);
1283
+ Collision triangleSoupCollision(SolverOperation& operation, const Body& geometry, const Body& convex);
1281
1284
  struct ToiDistance {
1282
1285
  double distance = 0.0;
1283
1286
  Vec3 normal;
@@ -1988,6 +1991,12 @@ Collision boundsPair(
1988
1991
  }
1989
1992
 
1990
1993
  Collision geometryPair(SolverOperation& operation, const Body& geometryA, const Body& geometryB) {
1994
+ if (!operation.fixedAxisQueryContacts) {
1995
+ if (triangleSoupBody(geometryA) && triangleSoupPartner(geometryB))
1996
+ return triangleSoupCollision(operation, geometryA, geometryB);
1997
+ if (triangleSoupBody(geometryB) && triangleSoupPartner(geometryA))
1998
+ return flipCollision(triangleSoupCollision(operation, geometryB, geometryA));
1999
+ }
1991
2000
  if (geometryA.shape == ShapeKind::Mesh && geometryA.geometryFormat == 2
1992
2001
  && geometryA.geometryCount >= 3 && geometryA.geometryCount % 3 == 0) {
1993
2002
  Collision best;
@@ -2070,6 +2079,8 @@ Collision geometryPair(SolverOperation& operation, const Body& geometryA, const
2070
2079
  }
2071
2080
 
2072
2081
  Collision geometryBox(SolverOperation& operation, const Body& geometry, const Body& box) {
2082
+ if (!operation.fixedAxisQueryContacts && triangleSoupBody(geometry))
2083
+ return triangleSoupCollision(operation, geometry, box);
2073
2084
  if (geometry.shape == ShapeKind::Heightfield && geometry.geometryFormat == 3) {
2074
2085
  if (geometry.geometryCount < 5) return {};
2075
2086
  const std::uint32_t metadata = geometry.geometryOffset * 3;
@@ -2327,12 +2338,12 @@ void collectSupportAxes(const Body& a, const Body& b, const Vec3& centerA, const
2327
2338
  }
2328
2339
  }
2329
2340
 
2330
- bool curvedConvexPair(const Body& a, const Body& b);
2331
- Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const Body& b);
2341
+ bool exactConvexPair(const Body& a, const Body& b);
2342
+ Collision exactConvexCollision(SolverOperation& operation, const Body& a, const Body& b);
2332
2343
 
2333
2344
  Collision convexSupportCollision(SolverOperation& operation, const Body& a, const Body& b) {
2334
2345
  if (!robustConvexBodiesOverlap(operation, a, b)) return {};
2335
- if (curvedConvexPair(a, b) && !operation.fixedAxisQueryContacts) return curvedConvexCollision(operation, a, b);
2346
+ if (exactConvexPair(a, b) && !operation.fixedAxisQueryContacts) return exactConvexCollision(operation, a, b);
2336
2347
 
2337
2348
  const Vec3 centerA{a.x + a.shapeOffsetX, a.y + a.shapeOffsetY, a.z + a.shapeOffsetZ};
2338
2349
  const Vec3 centerB{b.x + b.shapeOffsetX, b.y + b.shapeOffsetY, b.z + b.shapeOffsetZ};
@@ -2360,7 +2371,7 @@ Collision convexSupportCollision(SolverOperation& operation, const Body& a, cons
2360
2371
  // position correction pushes the pair apart with no velocity response
2361
2372
  // left. The closest-core direction is the exact normal. It goes last, so a
2362
2373
  // matching axis above keeps its place and its result. (Simulation contacts
2363
- // with cylinders, cones and tapered capsules take curvedConvexCollision
2374
+ // with cylinders, cones and tapered capsules take exactConvexCollision
2364
2375
  // instead. Overlap and shape cast queries still come here.)
2365
2376
  const bool sphereA = a.shape == ShapeKind::Sphere;
2366
2377
  const bool sphereB = b.shape == ShapeKind::Sphere;
@@ -2419,6 +2430,18 @@ Collision convexSupportCollision(SolverOperation& operation, const Body& a, cons
2419
2430
  const double sign = sphereA ? 1.0 : -1.0;
2420
2431
  bestPointA = addVec3(center, scaleVec3(bestNormal, sign * (sphereA ? radius : coreDistance)));
2421
2432
  bestPointB = addVec3(center, scaleVec3(bestNormal, sign * (sphereA ? coreDistance : radius)));
2433
+ } else if (sphereA != sphereB && !operation.fixedAxisQueryContacts) {
2434
+ // On any other axis the sphere center still fixes both points. The
2435
+ // support midpoint is wrong there: a thin hull wall has a whole side as
2436
+ // its support, so the point lay up to a wall size off the sphere and the
2437
+ // impulse turned into spin (a sphere passed a 0.02 m hull wall at 15 m/s).
2438
+ const Vec3 center = sphereA ? centerA : centerB;
2439
+ const double radius = sphereA ? a.shape0 : b.shape0;
2440
+ const double sign = sphereA ? 1.0 : -1.0;
2441
+ const Vec3 surface = addVec3(center, scaleVec3(bestNormal, sign * radius));
2442
+ const Vec3 inner = subtractVec3(surface, scaleVec3(bestNormal, sign * std::max(0.0, minPenetration)));
2443
+ bestPointA = sphereA ? surface : inner;
2444
+ bestPointB = sphereA ? inner : surface;
2422
2445
  }
2423
2446
 
2424
2447
  return {
@@ -2770,25 +2793,28 @@ bool robustConvexBodiesOverlap(SolverOperation& operation, const Body& a, const
2770
2793
 
2771
2794
  void contactTangentBasis(const Vec3& normal, Vec3& first, Vec3& second);
2772
2795
 
2773
- // Curved convex contacts.
2774
- //
2775
- // The fixed SAT axes above miss the contact normal of a cylinder, cone or
2776
- // tapered capsule in general, so the depth they report is too deep. Bodies
2777
- // on the split contact path (any joint, every portal clone) then lose their
2778
- // velocity response: the position pass pushes the pair fully apart and the
2779
- // velocity pass finds no contact. Pairs with a curved shape therefore also
2780
- // test the exact normal (the closest-core normal when a sphere or capsule
2781
- // core is outside the other shape, else the EPA normal), and build their
2782
- // contact points from the support features along the chosen normal.
2796
+ // Exact convex contacts. The fixed SAT axes above miss the normal of a curved
2797
+ // shape and every hull face, and their support midpoint can lie metres from
2798
+ // both bodies (a far corner of a large hull floor). Pairs with a curved shape
2799
+ // or a hull (a mesh or heightfield triangle is a three-point hull) also test
2800
+ // the exact normal (closest core, else EPA) and take their points from the
2801
+ // support features. Hull-sphere keeps the exact sphere route above.
2783
2802
 
2784
2803
  bool curvedConvexShape(ShapeKind shape) {
2785
2804
  return shape == ShapeKind::Cylinder || shape == ShapeKind::Cone
2786
2805
  || shape == ShapeKind::TaperedCapsule;
2787
2806
  }
2788
2807
 
2789
- bool curvedConvexPair(const Body& a, const Body& b) {
2790
- return (curvedConvexShape(a.shape) || curvedConvexShape(b.shape))
2791
- && toiSupported(a) && toiSupported(b);
2808
+ bool exactConvexPair(const Body& a, const Body& b) {
2809
+ if (!toiSupported(a) || !toiSupported(b)) return false;
2810
+ if (curvedConvexShape(a.shape) || curvedConvexShape(b.shape)) return true;
2811
+ return (a.shape == ShapeKind::Hull || b.shape == ShapeKind::Hull)
2812
+ && a.shape != ShapeKind::Sphere && b.shape != ShapeKind::Sphere;
2813
+ }
2814
+
2815
+ // A hull of three points is a triangle of a mesh or heightfield.
2816
+ bool triangleHull(const Body& body) {
2817
+ return body.shape == ShapeKind::Hull && body.geometryFormat == 0 && body.geometryCount == 3;
2792
2818
  }
2793
2819
 
2794
2820
  Vec3 minkowskiSupport(SolverOperation& operation, const Body& a, const Body& b, const Vec3& direction) {
@@ -3143,6 +3169,23 @@ void hullFeature(SolverOperation& operation, const Body& body, const Vec3& direc
3143
3169
  if (feature.count >= 3) {
3144
3170
  feature.face = true;
3145
3171
  feature.faceNormal = direction;
3172
+ // The true face normal (Newell), not the support direction: the choice
3173
+ // of the reference face compares the two face normals with the contact
3174
+ // normal, and a direction one ulp off flipped that choice between calls,
3175
+ // so the feature ids of one contact changed and its episodes broke.
3176
+ Vec3 newell{};
3177
+ for (std::uint32_t index = 0; index < feature.count; index += 1) {
3178
+ const Vec3& current = feature.points[index];
3179
+ const Vec3& next = feature.points[(index + 1) % feature.count];
3180
+ newell.x += (current.y - next.y) * (current.z + next.z);
3181
+ newell.y += (current.z - next.z) * (current.x + next.x);
3182
+ newell.z += (current.x - next.x) * (current.y + next.y);
3183
+ }
3184
+ const double lengthSq = dotVec3(newell, newell);
3185
+ if (lengthSq > 1e-30) {
3186
+ newell = scaleVec3(newell, 1.0 / solverSqrt(lengthSq));
3187
+ feature.faceNormal = dotVec3(newell, direction) < 0.0 ? scaleVec3(newell, -1.0) : newell;
3188
+ }
3146
3189
  }
3147
3190
  }
3148
3191
 
@@ -3518,7 +3561,7 @@ std::uint32_t diskPatchPoints(const ContactFeature& from, const ContactFeature&
3518
3561
  }
3519
3562
 
3520
3563
  // Contact points for a pair on a known normal (a to b) and depth.
3521
- Collision curvedConvexManifold(SolverOperation& operation, const Body& a, const Body& b,
3564
+ Collision convexFeatureManifold(SolverOperation& operation, const Body& a, const Body& b,
3522
3565
  const Vec3& normal, double penetration) {
3523
3566
  const Vec3 supportA = supportPointForBody(operation, a, normal);
3524
3567
  const Vec3 supportB = supportPointForBody(operation, b, scaleVec3(normal, -1.0));
@@ -3683,13 +3726,33 @@ Collision curvedConvexManifold(SolverOperation& operation, const Body& a, const
3683
3726
  return result;
3684
3727
  }
3685
3728
 
3686
- Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const Body& b) {
3729
+ Collision exactConvexCollision(SolverOperation& operation, const Body& a, const Body& b) {
3687
3730
  const Vec3 centerA{a.x + a.shapeOffsetX, a.y + a.shapeOffsetY, a.z + a.shapeOffsetZ};
3688
3731
  const Vec3 centerB{b.x + b.shapeOffsetX, b.y + b.shapeOffsetY, b.z + b.shapeOffsetZ};
3689
3732
  const Vec3 centerDiff = subtractVec3(centerB, centerA);
3690
3733
  std::array<Vec3, 24> axes{};
3691
3734
  std::uint32_t axisCount = 0;
3692
3735
  collectSupportAxes(a, b, centerA, centerB, centerDiff, axes, axisCount);
3736
+ // A triangle face is an axis too, toward the side of the other center: a
3737
+ // body that rests on a triangle has that face normal as its contact normal.
3738
+ // It is exact, so a near axis does not replace it: on a large triangle an
3739
+ // axis 0.2 degrees off reports a depth 30 times too deep.
3740
+ for (const Body* body : {&a, &b}) {
3741
+ if (!triangleHull(*body) || axisCount >= axes.size()) continue;
3742
+ const auto values = geometryForBody(operation, *body);
3743
+ const std::uint32_t first = body->geometryOffset * 3;
3744
+ std::array<Vec3, 3> corner{};
3745
+ for (std::uint32_t point = 0; point < 3; point += 1) {
3746
+ corner[point] = rotateByOrientation(*body, {values[first + point * 3],
3747
+ values[first + point * 3 + 1], values[first + point * 3 + 2]});
3748
+ }
3749
+ const Vec3 face = crossVec3(subtractVec3(corner[1], corner[0]), subtractVec3(corner[2], corner[0]));
3750
+ const double lengthSq = dotVec3(face, face);
3751
+ if (lengthSq <= 1e-24) continue;
3752
+ Vec3 unit = scaleVec3(face, 1.0 / solverSqrt(lengthSq));
3753
+ if (dotVec3(unit, centerDiff) < 0.0) unit = scaleVec3(unit, -1.0);
3754
+ axes[axisCount++] = unit;
3755
+ }
3693
3756
  if (axisCount == 0) axes[axisCount++] = {1.0, 0.0, 0.0};
3694
3757
 
3695
3758
  double minPenetration = std::numeric_limits<double>::infinity();
@@ -3709,10 +3772,13 @@ Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const
3709
3772
 
3710
3773
  // The exact normal. A sphere or capsule core outside the other shape
3711
3774
  // gives it directly; otherwise EPA finds it. A fixed axis that is as good
3712
- // keeps its place.
3775
+ // keeps its place. A hull pair that touches without overlap (a resting
3776
+ // hull, depth zero) also takes the closest-point normal: EPA needs the
3777
+ // origin enclosed and fails there, and no fixed axis is a hull face.
3713
3778
  Vec3 exact{};
3714
3779
  bool haveExact = false;
3715
- if (toiRadius(a) > 0.0 || toiRadius(b) > 0.0) {
3780
+ const bool hullPair = a.shape == ShapeKind::Hull || b.shape == ShapeKind::Hull;
3781
+ if (toiRadius(a) > 0.0 || toiRadius(b) > 0.0 || hullPair) {
3716
3782
  const ToiDistance core = toiCoreDistance(operation, a, b);
3717
3783
  const double lengthSq = dotVec3(core.normal, core.normal);
3718
3784
  if (!core.overlap && lengthSq > 1e-24) {
@@ -3729,7 +3795,7 @@ Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const
3729
3795
  bestNormal = exact;
3730
3796
  }
3731
3797
  }
3732
- return curvedConvexManifold(operation, a, b, bestNormal, std::max(0.0, minPenetration));
3798
+ return convexFeatureManifold(operation, a, b, bestNormal, std::max(0.0, minPenetration));
3733
3799
  }
3734
3800
 
3735
3801
 
@@ -5629,6 +5695,209 @@ Collision finalizeCompoundManifold(
5629
5695
  return best;
5630
5696
  }
5631
5697
 
5698
+ // A mesh or heightfield: triangles in a fixed order.
5699
+ bool triangleSoupBody(const Body& body) {
5700
+ return (body.shape == ShapeKind::Mesh && body.geometryFormat == 2 && body.geometryCount >= 3)
5701
+ || (body.shape == ShapeKind::Heightfield && body.geometryFormat == 3 && body.geometryCount >= 5);
5702
+ }
5703
+
5704
+ // The shapes that meet a triangle on the exact convex path. A sphere and a
5705
+ // capsule have their own exact triangle routines.
5706
+ bool triangleSoupPartner(const Body& body) {
5707
+ return toiSupported(body) && body.shape != ShapeKind::Sphere && body.shape != ShapeKind::Capsule;
5708
+ }
5709
+
5710
+ struct SoupTriangle {
5711
+ std::uint32_t index = 0;
5712
+ std::array<Vec3, 3> corner{};
5713
+ };
5714
+
5715
+ // The contact patch of a convex body on the triangles that lie in the contact
5716
+ // plane. The body's support feature against the plane is clipped to each such
5717
+ // triangle, and points within the feature tolerance count, as for one face. So
5718
+ // a patch over a shared triangle edge keeps all its corners, even where the
5719
+ // test of one triangle alone reads a touch at depth zero as a miss (a corner
5720
+ // then went missing and the impulse spun the body). Unclipped points keep the
5721
+ // body feature ids, so the points solve in the order of one face contact.
5722
+ // Returns nothing when no triangle lies in the plane (an edge contact).
5723
+ std::optional<Collision> triangleSoupPatch(SolverOperation& operation, const Body& convex, const Collision& best,
5724
+ std::span<const SoupTriangle> triangles) {
5725
+ const Vec3 normal{best.nx, best.ny, best.nz};
5726
+ const ContactFeature body = supportFeature(operation, convex, scaleVec3(normal, -1.0));
5727
+ struct Point { Vec3 position; std::uint32_t id; double depth; };
5728
+ std::vector<Point> points;
5729
+ for (const SoupTriangle& triangle : triangles) {
5730
+ Vec3 face = crossVec3(subtractVec3(triangle.corner[1], triangle.corner[0]),
5731
+ subtractVec3(triangle.corner[2], triangle.corner[0]));
5732
+ const double lengthSq = dotVec3(face, face);
5733
+ if (lengthSq <= 1e-24) continue;
5734
+ face = scaleVec3(face, 1.0 / solverSqrt(lengthSq));
5735
+ if (dotVec3(face, normal) < 0.0) face = scaleVec3(face, -1.0);
5736
+ const double alignment = dotVec3(face, normal);
5737
+ if (alignment < 0.98) continue;
5738
+ ContactFeature reference;
5739
+ reference.face = true;
5740
+ reference.faceNormal = face;
5741
+ for (std::uint32_t corner = 0; corner < 3; corner += 1) addFeaturePoint(reference, triangle.corner[corner], corner);
5742
+ std::array<FeatureClipVertex, 32> clipped{};
5743
+ const std::uint32_t count = clipFeatureToFace(body, reference, normal, clipped);
5744
+ const double surface = dotVec3(face, triangle.corner[0]);
5745
+ for (std::uint32_t index = 0; index < count; index += 1) {
5746
+ const Vec3& point = clipped[index].point;
5747
+ const double depth = (surface - dotVec3(face, point)) / alignment;
5748
+ if (depth < -featureTolerance) continue;
5749
+ bool bodyFeature = false;
5750
+ for (std::uint32_t corner = 0; corner < body.count; corner += 1) bodyFeature = bodyFeature || body.ids[corner] == clipped[index].id;
5751
+ std::uint32_t id = bodyFeature ? clipped[index].id
5752
+ : clipped[index].id ^ ((triangle.index + 1u) * 2166136261u);
5753
+ const Vec3 position = addVec3(point, scaleVec3(normal, 0.5 * depth));
5754
+ bool coincident = false;
5755
+ for (const Point& other : points) {
5756
+ const Vec3 delta = subtractVec3(position, other.position);
5757
+ coincident = coincident || dotVec3(delta, delta) <= 1e-12;
5758
+ }
5759
+ if (coincident) continue;
5760
+ // The ids of one manifold are distinct (each keys a contact episode). A
5761
+ // body corner inside two triangles that are not coplanar gives two
5762
+ // places with one id; the later one takes the triangle index.
5763
+ for (bool taken = true; taken;) {
5764
+ taken = false;
5765
+ for (const Point& other : points) taken = taken || other.id == id;
5766
+ if (taken) id = (id * 16777619u) ^ ((triangle.index + 1u) * 2166136261u);
5767
+ }
5768
+ points.push_back({position, id, depth});
5769
+ }
5770
+ }
5771
+ if (points.empty()) return std::nullopt;
5772
+ Collision result = best;
5773
+ result.pointCount = 0;
5774
+ // Keep the deepest point, then the points that spread the patch most.
5775
+ std::array<std::size_t, 4> selected{};
5776
+ std::uint32_t selectedCount = 0;
5777
+ while (selectedCount < std::min<std::size_t>(4, points.size())) {
5778
+ std::size_t chosen = 0;
5779
+ double bestScore = -1.0;
5780
+ bool found = false;
5781
+ for (std::size_t index = 0; index < points.size(); index += 1) {
5782
+ bool used = false;
5783
+ for (std::uint32_t taken = 0; taken < selectedCount; taken += 1) used = used || selected[taken] == index;
5784
+ if (used) continue;
5785
+ double score = points[index].depth;
5786
+ if (selectedCount != 0) {
5787
+ score = std::numeric_limits<double>::infinity();
5788
+ for (std::uint32_t taken = 0; taken < selectedCount; taken += 1) {
5789
+ const Vec3 delta = subtractVec3(points[index].position, points[selected[taken]].position);
5790
+ score = std::min(score, dotVec3(delta, delta));
5791
+ }
5792
+ }
5793
+ if (!found || score > bestScore || (score == bestScore && points[index].id < points[chosen].id)) {
5794
+ chosen = index;
5795
+ bestScore = score;
5796
+ found = true;
5797
+ }
5798
+ }
5799
+ selected[selectedCount++] = chosen;
5800
+ }
5801
+ std::sort(selected.begin(), selected.begin() + selectedCount,
5802
+ [&](std::size_t left, std::size_t right) { return points[left].id < points[right].id; });
5803
+ if (selectedCount == 1) {
5804
+ result.pointX = points[selected[0]].position.x;
5805
+ result.pointY = points[selected[0]].position.y;
5806
+ result.pointZ = points[selected[0]].position.z;
5807
+ return result;
5808
+ }
5809
+ Vec3 sum{};
5810
+ for (std::uint32_t index = 0; index < selectedCount; index += 1) {
5811
+ const Point& point = points[selected[index]];
5812
+ result.points[index] = {point.position.x, point.position.y, point.position.z};
5813
+ result.featureIds[index] = point.id;
5814
+ sum = addVec3(sum, point.position);
5815
+ }
5816
+ result.pointCount = selectedCount;
5817
+ const Vec3 average = scaleVec3(sum, 1.0 / static_cast<double>(selectedCount));
5818
+ result.pointX = average.x;
5819
+ result.pointY = average.y;
5820
+ result.pointZ = average.z;
5821
+ return result;
5822
+ }
5823
+
5824
+ // Contacts of a convex body with a mesh or heightfield (simulation only). Each
5825
+ // triangle near the body is a three-point hull on the exact convex path; the
5826
+ // deepest result gives the normal and depth, and the patch on the triangles in
5827
+ // that contact plane gives the points. The collision points from the geometry
5828
+ // to the convex body.
5829
+ Collision triangleSoupCollision(SolverOperation& operation, const Body& geometry, const Body& convex) {
5830
+ const BroadphaseBounds bounds = queryProxyBounds(operation, convex);
5831
+ constexpr double margin = featureTolerance;
5832
+ std::vector<SoupTriangle> near;
5833
+ Collision best;
5834
+ const auto test = [&](std::uint32_t index, const Vec3& first, const Vec3& second, const Vec3& third) {
5835
+ if (std::min({first.x, second.x, third.x}) > bounds.maxX + margin
5836
+ || std::max({first.x, second.x, third.x}) < bounds.minX - margin
5837
+ || std::min({first.y, second.y, third.y}) > bounds.maxY + margin
5838
+ || std::max({first.y, second.y, third.y}) < bounds.minY - margin
5839
+ || std::min({first.z, second.z, third.z}) > bounds.maxZ + margin
5840
+ || std::max({first.z, second.z, third.z}) < bounds.minZ - margin) return;
5841
+ near.push_back({index, {first, second, third}});
5842
+ const Vec3 centroid = scaleVec3(addVec3(addVec3(first, second), third), 1.0 / 3.0);
5843
+ std::array<double, 9> local{};
5844
+ for (std::uint32_t corner = 0; corner < 3; corner += 1) {
5845
+ const Vec3 offset = subtractVec3(corner == 0 ? first : corner == 1 ? second : third, centroid);
5846
+ local[corner * 3] = offset.x;
5847
+ local[corner * 3 + 1] = offset.y;
5848
+ local[corner * 3 + 2] = offset.z;
5849
+ }
5850
+ Body triangle = geometry;
5851
+ triangle.shape = ShapeKind::Hull;
5852
+ triangle.geometryRecord = nullptr;
5853
+ triangle.geometrySource = GeometryInputSource::OwnedRecord;
5854
+ triangle.geometryView = std::span<const double>(local.data(), local.size());
5855
+ triangle.geometryFeatureOffset = 0;
5856
+ triangle.geometryFormat = 0;
5857
+ triangle.geometryOffset = 0;
5858
+ triangle.geometryCount = 3;
5859
+ triangle.x = centroid.x;
5860
+ triangle.y = centroid.y;
5861
+ triangle.z = centroid.z;
5862
+ triangle.shapeOffsetX = 0.0;
5863
+ triangle.shapeOffsetY = 0.0;
5864
+ triangle.shapeOffsetZ = 0.0;
5865
+ triangle.orientationX = 0.0;
5866
+ triangle.orientationY = 0.0;
5867
+ triangle.orientationZ = 0.0;
5868
+ triangle.orientationW = 1.0;
5869
+ triangle.shape0 = 0.0;
5870
+ triangle.shape1 = 0.0;
5871
+ triangle.shape2 = 0.0;
5872
+ const Collision candidate = convexSupportCollision(operation, triangle, convex);
5873
+ if (candidate.hit && (!best.hit || candidate.penetration > best.penetration)) best = candidate;
5874
+ };
5875
+ if (geometry.shape == ShapeKind::Mesh) {
5876
+ for (std::uint32_t point = 0; point + 2 < geometry.geometryCount; point += 3) {
5877
+ test(point / 3, geometryPoint(operation, geometry, point),
5878
+ geometryPoint(operation, geometry, point + 1), geometryPoint(operation, geometry, point + 2));
5879
+ }
5880
+ } else {
5881
+ const std::uint32_t metadata = geometry.geometryOffset * 3;
5882
+ const std::uint32_t columns = static_cast<std::uint32_t>(geometryForBody(operation, geometry)[metadata]);
5883
+ const std::uint32_t rows = static_cast<std::uint32_t>(geometryForBody(operation, geometry)[metadata + 1]);
5884
+ if (columns < 2 || rows < 2 || columns * rows + 1 > geometry.geometryCount) return {};
5885
+ for (std::uint32_t row = 0; row + 1 < rows; ++row) {
5886
+ for (std::uint32_t column = 0; column + 1 < columns; ++column) {
5887
+ const std::uint32_t first = row * columns + column;
5888
+ const Vec3 a = geometryPoint(operation, geometry, first);
5889
+ const Vec3 b = geometryPoint(operation, geometry, first + columns);
5890
+ const Vec3 c = geometryPoint(operation, geometry, first + 1);
5891
+ const Vec3 d = geometryPoint(operation, geometry, first + columns + 1);
5892
+ test(first * 2, a, b, c);
5893
+ test(first * 2 + 1, d, c, b);
5894
+ }
5895
+ }
5896
+ }
5897
+ if (!best.hit) return {};
5898
+ return triangleSoupPatch(operation, convex, best, near).value_or(best);
5899
+ }
5900
+
5632
5901
  bool isSmallDynamicWorld(const SolverOperation& operation);
5633
5902
 
5634
5903
  // The stack solver path. Above 360 bodies it is always on, and it is on while the dynamic tree
@@ -6030,6 +6299,13 @@ Collision collideUncached(SolverOperation& operation, const Body& a, const Body&
6030
6299
  if (isGeometryShape(a.shape) && isGeometryShape(b.shape)) {
6031
6300
  return geometryPair(operation, a, b);
6032
6301
  }
6302
+ // Simulation contacts of a triangle with a box, hull or curved shape, and of
6303
+ // a hull with a capsule, take the exact convex path.
6304
+ if (!operation.fixedAxisQueryContacts) {
6305
+ if (triangleSoupBody(a) && triangleSoupPartner(b)) return triangleSoupCollision(operation, a, b);
6306
+ if (triangleSoupBody(b) && triangleSoupPartner(a)) return flipCollision(triangleSoupCollision(operation, b, a));
6307
+ if (exactConvexPair(a, b)) return convexSupportCollision(operation, a, b);
6308
+ }
6033
6309
  // Compounds use child recursion. The capsule/heightfield box approximation
6034
6310
  // misses occupied vertices. Keep the terrain-capsule regression until repaired.
6035
6311
  const auto recursableCompound = [](const Body& body) {
@@ -11064,6 +11340,27 @@ void warmStartSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_
11064
11340
  }
11065
11341
  }
11066
11342
 
11343
+ // Appends the warm-start row of one contact to the contact cache, the only way a row is made. A
11344
+ // row holds an accumulated contact impulse, and the cache contract is a normal impulse that is not
11345
+ // negative (the step rejects any other row). An impulse that the motion clock re-expresses in a
11346
+ // contact frame that turned against the response frame can have a negative normal part. It is no
11347
+ // warm start for the next step, so its row holds no impulse.
11348
+ void appendContactCacheRow(std::vector<double>& cache, const ContactConstraintBlock& contact,
11349
+ const std::array<double, 3>& point) {
11350
+ const bool pushes = !(contact.impulses[0] < 0.0);
11351
+ cache.insert(cache.end(), {
11352
+ static_cast<double>(contact.bodyA),
11353
+ static_cast<double>(contact.bodyB),
11354
+ static_cast<double>(contact.featureId),
11355
+ pushes ? contact.impulses[0] : 0.0,
11356
+ pushes ? contact.impulses[1] : 0.0,
11357
+ pushes ? contact.impulses[2] : 0.0,
11358
+ point[0],
11359
+ point[1],
11360
+ point[2],
11361
+ });
11362
+ }
11363
+
11067
11364
  void finalizeContactCache(SolverOperation& operation) {
11068
11365
  operation.storage.contactCacheOutput.clear();
11069
11366
  operation.storage.contactCacheOutput.reserve(
@@ -11073,19 +11370,7 @@ void finalizeContactCache(SolverOperation& operation) {
11073
11370
  index < operation.storage.contactConstraintCount; index += 1) {
11074
11371
  const ContactConstraintBlock& constraint = operation.storage.contactConstraints[index];
11075
11372
  if (!constraint.activeForVelocityPhase && !constraint.preserveForCache) continue;
11076
- operation.storage.contactCacheOutput.insert(
11077
- operation.storage.contactCacheOutput.end(),
11078
- {
11079
- static_cast<double>(constraint.bodyA),
11080
- static_cast<double>(constraint.bodyB),
11081
- static_cast<double>(constraint.featureId),
11082
- constraint.impulses[0],
11083
- constraint.impulses[1],
11084
- constraint.impulses[2],
11085
- constraint.point[0],
11086
- constraint.point[1],
11087
- constraint.point[2],
11088
- });
11373
+ appendContactCacheRow(operation.storage.contactCacheOutput, constraint, constraint.point);
11089
11374
  }
11090
11375
  }
11091
11376
 
@@ -12267,8 +12552,10 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
12267
12552
  // enough more passes over the pairs with a cylinder to reach 24 iterations in total; pairs
12268
12553
  // without one are unchanged. Twelve settled every jittered tire run in the corpus; 24 also
12269
12554
  // shortens the small-world (sweep) tail, where 8 of 192 runs took over 90 frames at 12 and 3 at
12270
- // 24. A floor, not a fixed count, keeps every configured count off 8 and 9, where portal and
12271
- // direct pushes already differ (review 10). The owned (joint and portal) path runs one iteration per call, so
12555
+ // 24. In rc.61 and rc.62 the floor also hid portal parity defects at 8 and 9 iterations (review 10).
12556
+ // Now a portal clone moves like the direct body at every count, with or without the floor,
12557
+ // except at half-quantum ties (tests/portal-parity-ratchet.test.ts). The floor is for settling
12558
+ // only. The owned (joint and portal) path runs one iteration per call, so
12272
12559
  // its loop marks the last call, and the extra passes come before that iteration's joint and
12273
12560
  // portal work, as on the standalone path.
12274
12561
  //
@@ -12944,16 +13231,21 @@ void updateJointIslandMembership(SolverOperation& operation,
12944
13231
 
12945
13232
  for (const auto& connection : connections) {
12946
13233
  if (connection[0] < bodyCount && connection[1] < bodyCount && connection[0] != connection[1]) {
13234
+ // A proxy link joins one rigid body, so it is not a constraint. If it
13235
+ // set the joint flag, a portal clone and its original would solve their
13236
+ // contacts on the joint path, and the same body without a portal on the
13237
+ // standalone path. Above the slop the two paths give different results.
13238
+ const bool constraint = !hook.isProxyLink(connection);
12947
13239
  if (bodies[connection[0]].dynamic) {
12948
13240
  const std::uint32_t rootA = sleepFind(operation, connection[0]);
12949
- componentHasJoint[rootA] = 1;
13241
+ if (constraint) componentHasJoint[rootA] = 1;
12950
13242
  if (bodies[connection[1]].kinematic || (bodies[connection[1]].dynamic && !bodies[connection[1]].sleeping)) {
12951
13243
  componentHasActive[rootA] = 1;
12952
13244
  }
12953
13245
  }
12954
13246
  if (bodies[connection[1]].dynamic) {
12955
13247
  const std::uint32_t rootB = sleepFind(operation, connection[1]);
12956
- componentHasJoint[rootB] = 1;
13248
+ if (constraint) componentHasJoint[rootB] = 1;
12957
13249
  if (bodies[connection[0]].kinematic || (bodies[connection[0]].dynamic && !bodies[connection[0]].sleeping)) {
12958
13250
  componentHasActive[rootB] = 1;
12959
13251
  }
@@ -20579,29 +20871,105 @@ bool sameMotionSearchBody(const Body& a, const Body& b) {
20579
20871
  // skin across it.
20580
20872
  constexpr double kMotionContactSkin = 0.005;
20581
20873
 
20582
- // Returns true when the shapes of `a` and `b` are not certainly farther apart than the skin. The test
20583
- // grows one primitive body of the pair (sphere, capsule or box) by the skin and then uses collide().
20584
- // A grown box contains every point within the skin of the box, so a miss proves a gap larger than
20585
- // the skin. A pair without a primitive body returns true: its episodes stay until the substep ends.
20874
+ // Returns `body` with its shape grown (`delta` > 0) or shrunk (`delta` < 0) by |delta| on every side,
20875
+ // or nothing when the body is not a sphere, capsule or box, or when the shrunk shape would be empty.
20876
+ // A grown shape contains every point within `delta` of the shape. Every point of a shrunk shape is at
20877
+ // least |delta| inside the shape.
20878
+ std::optional<Body> offsetMotionPrimitive(Body body, double delta) {
20879
+ switch (body.shape) {
20880
+ case ShapeKind::Sphere:
20881
+ case ShapeKind::Capsule:
20882
+ if (!(body.shape0 + delta > 0.0)) return std::nullopt;
20883
+ body.shape0 += delta;
20884
+ return body;
20885
+ case ShapeKind::Box:
20886
+ if (!(body.shape0 + delta > 0.0) || !(body.shape1 + delta > 0.0) || !(body.shape2 + delta > 0.0))
20887
+ return std::nullopt;
20888
+ body.shape0 += delta;
20889
+ body.shape1 += delta;
20890
+ body.shape2 += delta;
20891
+ return body;
20892
+ default: return std::nullopt;
20893
+ }
20894
+ }
20895
+
20896
+ // A box body that contains the world bounds of `body` grown by `delta` on every side.
20897
+ Body motionBoundsBox(SolverOperation& operation, const Body& body, double delta) {
20898
+ const BroadphaseBounds bounds = queryProxyBounds(operation, body);
20899
+ Body box;
20900
+ box.id = body.id;
20901
+ box.dynamic = false;
20902
+ box.layer = body.layer;
20903
+ box.mask = body.mask;
20904
+ box.masksValid = body.masksValid;
20905
+ box.shape = ShapeKind::Box;
20906
+ box.x = (bounds.minX + bounds.maxX) * 0.5;
20907
+ box.y = (bounds.minY + bounds.maxY) * 0.5;
20908
+ box.z = (bounds.minZ + bounds.maxZ) * 0.5;
20909
+ box.orientationX = 0.0;
20910
+ box.orientationY = 0.0;
20911
+ box.orientationZ = 0.0;
20912
+ box.orientationW = 1.0;
20913
+ // The half extents round up so that the box contains the bounds after the center rounds.
20914
+ box.shape0 = std::nextafter((bounds.maxX - bounds.minX) * 0.5 + delta, std::numeric_limits<double>::infinity());
20915
+ box.shape1 = std::nextafter((bounds.maxY - bounds.minY) * 0.5 + delta, std::numeric_limits<double>::infinity());
20916
+ box.shape2 = std::nextafter((bounds.maxZ - bounds.minZ) * 0.5 + delta, std::numeric_limits<double>::infinity());
20917
+ return box;
20918
+ }
20919
+
20920
+ // Returns true when the shapes of `a` and `b` are not certainly farther apart than the skin. A miss
20921
+ // of collide() with one shape grown by the skin proves a gap larger than the skin. A sphere, capsule
20922
+ // or box grows exactly. Any other shape grows through its world bounds box, which contains the shape:
20923
+ // that test is conservative, so a pair of two such shapes leaves contact when the bounds box of one
20924
+ // body, grown by the skin, misses the other body.
20586
20925
  bool withinMotionContactSkin(SolverOperation& operation, const Body& a, const Body& b) {
20587
- const auto grown = [](Body body) -> std::optional<Body> {
20588
- switch (body.shape) {
20589
- case ShapeKind::Sphere:
20590
- case ShapeKind::Capsule:
20591
- body.shape0 += kMotionContactSkin;
20592
- return body;
20593
- case ShapeKind::Box:
20594
- body.shape0 += kMotionContactSkin;
20595
- body.shape1 += kMotionContactSkin;
20596
- body.shape2 += kMotionContactSkin;
20597
- return body;
20598
- default: return std::nullopt;
20599
- }
20600
- };
20601
20926
  triangle_adapter_private::work(operation);
20602
- if (const auto first = grown(a)) return collide(operation, *first, b).hit;
20603
- if (const auto second = grown(b)) return collide(operation, a, *second).hit;
20604
- return true;
20927
+ if (const auto first = offsetMotionPrimitive(a, kMotionContactSkin)) return collide(operation, *first, b).hit;
20928
+ if (const auto second = offsetMotionPrimitive(b, kMotionContactSkin)) return collide(operation, a, *second).hit;
20929
+ triangle_adapter_private::work(operation, 2);
20930
+ return collide(operation, motionBoundsBox(operation, a, kMotionContactSkin), b).hit
20931
+ && collide(operation, a, motionBoundsBox(operation, b, kMotionContactSkin)).hit;
20932
+ }
20933
+
20934
+ // How the watch of an engaged pair finds the time at which the pair is `depth` deep.
20935
+ // - ShrunkBody: the body `endpoint` (a sphere, capsule or box) shrunk by `depth` touches the other
20936
+ // body only where the pair is at least `depth` deep.
20937
+ // - ReportedDepth: a pair with no sphere, capsule or box (hull, mesh, heightfield, compound,
20938
+ // cylinder, cone) is `depth` deep where collide() reports a depth larger than `depth`. These pairs
20939
+ // take the exact convex contact (fixed axes and EPA), so the reported depth is the true depth.
20940
+ struct ShrunkBody {
20941
+ unsigned endpoint = 0;
20942
+ double depth = 0.0;
20943
+ };
20944
+ struct ReportedDepth {
20945
+ double depth = 0.0;
20946
+ };
20947
+ using MotionPairErosion = std::variant<ShrunkBody, ReportedDepth>;
20948
+
20949
+ bool motionPrimitive(const Body& body) {
20950
+ return body.shape == ShapeKind::Sphere || body.shape == ShapeKind::Capsule || body.shape == ShapeKind::Box;
20951
+ }
20952
+
20953
+ // Chooses how to watch an engaged pair at `depth`: shrink a sphere, capsule or box that stays
20954
+ // nonempty, the thicker one first; else read the reported depth of a pair with no sphere or capsule
20955
+ // (a hull, mesh, compound or cylinder, or one of them against a thin box wall). Returns nothing when
20956
+ // no body can be shrunk by `depth` and the pair has a sphere or capsule (their triangle and sphere
20957
+ // routes do not report the true depth) or is two boxes.
20958
+ std::optional<MotionPairErosion> erodedMotionPair(const Body& a, const Body& b, double depth) {
20959
+ const auto rounded = [](const Body& body) {
20960
+ return body.shape == ShapeKind::Sphere || body.shape == ShapeKind::Capsule;
20961
+ };
20962
+ const bool reportedDepthPair = !rounded(a) && !rounded(b)
20963
+ && !(a.shape == ShapeKind::Box && b.shape == ShapeKind::Box);
20964
+ if (!motionPrimitive(a) && !motionPrimitive(b)) return ReportedDepth{depth};
20965
+ const auto margin = [&](const Body& body) -> std::optional<double> {
20966
+ if (!offsetMotionPrimitive(body, -depth)) return std::nullopt;
20967
+ return body.shape == ShapeKind::Box ? std::min({body.shape0, body.shape1, body.shape2}) : body.shape0;
20968
+ };
20969
+ const auto first = margin(a), second = margin(b);
20970
+ if (!first && !second) return reportedDepthPair ? std::optional<MotionPairErosion>{ReportedDepth{depth}} : std::nullopt;
20971
+ if (first && (!second || *first >= *second)) return ShrunkBody{0, depth};
20972
+ return ShrunkBody{1, depth};
20605
20973
  }
20606
20974
 
20607
20975
  // An upper bound of the speed of every point of a primitive body (sphere, capsule or box) that
@@ -20625,8 +20993,9 @@ double motionPointSpeedBound(const BodyMotionEpoch& epoch, const Body& body) {
20625
20993
  class MotionContactSearch {
20626
20994
  public:
20627
20995
  MotionContactSearch(SolverOperation& operation, std::uint32_t first, std::uint32_t second,
20628
- MotionContactTransition transition = MotionContactTransition::Entry)
20629
- : operation_(operation), pair_{first, second}, transition_(transition) {}
20996
+ MotionContactTransition transition = MotionContactTransition::Entry,
20997
+ std::optional<MotionPairErosion> erosion = std::nullopt)
20998
+ : operation_(operation), pair_{first, second}, transition_(transition), erosion_(erosion) {}
20630
20999
  MotionContactSearch(const MotionContactSearch&) = delete;
20631
21000
  MotionContactSearch& operator=(const MotionContactSearch&) = delete;
20632
21001
  MotionContactSearch(MotionContactSearch&&) = delete;
@@ -20680,8 +21049,30 @@ class MotionContactSearch {
20680
21049
  if (evaluated != Status::Clear) return fail(evaluated);
20681
21050
  if (!sameSearchBody(current, bodies_[endpoint])) return fail(Status::InvalidInput);
20682
21051
  }
21052
+ searched_ = bodies_;
21053
+ if (erosion_) {
21054
+ // An eroded search watches an engaged pair on the native clock: it finds the first time at
21055
+ // which the pair is `depth` deep, as an entry of the shrunk body or of the reported depth.
21056
+ if (operation_.materialMotionEpochs != nullptr || transition_ != MotionContactTransition::Entry)
21057
+ return fail(Status::InvalidInput);
21058
+ if (const auto* shrink = std::get_if<ShrunkBody>(&*erosion_)) {
21059
+ if (shrink->endpoint > 1 || !finite(shrink->depth) || !(shrink->depth > 0.0)) return fail(Status::InvalidInput);
21060
+ const auto shrunk = offsetMotionPrimitive(bodies_[shrink->endpoint], -shrink->depth);
21061
+ if (!shrunk) return fail(Status::InvalidInput);
21062
+ searched_[shrink->endpoint] = *shrunk;
21063
+ } else {
21064
+ const double depth = std::get<ReportedDepth>(*erosion_).depth;
21065
+ if (!finite(depth) || !(depth > 0.0) || (motionPrimitive(bodies_[0]) && motionPrimitive(bodies_[1])))
21066
+ return fail(Status::InvalidInput);
21067
+ for (const Body& body : bodies_)
21068
+ if (body.shape == ShapeKind::Sphere || body.shape == ShapeKind::Capsule) return fail(Status::InvalidInput);
21069
+ reportedDepth_ = depth;
21070
+ }
21071
+ }
20683
21072
  const bool sampledNativeSearch = operation_.materialMotionEpochs == nullptr
20684
21073
  && motionContactPairKind(bodies_[0], bodies_[1]) == MotionContactPairKind::Unsupported;
21074
+ // The reported depth is a point test, so only the sampled search can read it.
21075
+ if (reportedDepth_ && !sampledNativeSearch) return fail(Status::InvalidInput);
20685
21076
  if (!sampledNativeSearch
20686
21077
  && motionContactPairKind(bodies_[0], bodies_[1]) == MotionContactPairKind::Unsupported)
20687
21078
  return fail(Status::UnsupportedGeometry);
@@ -20713,7 +21104,9 @@ class MotionContactSearch {
20713
21104
  // more than a quarter of the contact skin across it (the factor 2 covers the error of the
20714
21105
  // orientation step). A leaf is decided by the point test at its ends. A contact that starts
20715
21106
  // and ends inside a leaf penetrates less than the contact slop, so the search may ignore it,
20716
- // and the number of leaves is at most about 8 * duration * speed / skin.
21107
+ // and the number of leaves is at most about 8 * duration * speed / skin. If an event of another
21108
+ // pair falls inside that contact, the next batch finds the pair touching without episodes and
21109
+ // gives it episodes at once (MotionContactEventKind::StartContact).
20717
21110
  const double speed = std::holds_alternative<NativeSearchGeometry>(geometry_)
20718
21111
  ? motionPointSpeedBound(epochs_[0], bodies_[0]) + motionPointSpeedBound(epochs_[1], bodies_[1]) : 0.0;
20719
21112
  if (!finite(speed)) return fail(Status::Unresolved);
@@ -20726,7 +21119,7 @@ class MotionContactSearch {
20726
21119
  const auto* material = std::get_if<MaterialSearchGeometry>(&geometry_);
20727
21120
  const auto rejection = material != nullptr
20728
21121
  ? classifyMaterialMotionContactInterval(operation_, *material->sources[0], *material->sources[1], slab[0], slab[1])
20729
- : classifyMotionContactInterval(operation_, epochs_[0], bodies_[0], epochs_[1], bodies_[1], slab[0], slab[1]);
21122
+ : classifyMotionContactInterval(operation_, epochs_[0], searched_[0], epochs_[1], searched_[1], slab[0], slab[1]);
20730
21123
  switch (rejection) {
20731
21124
  case MotionContactIntervalStatus::Separated:
20732
21125
  if (!departing) {
@@ -20770,6 +21163,13 @@ class MotionContactSearch {
20770
21163
  result_.certifiedEnd = bracket[0];
20771
21164
  result_.bracket = bracket;
20772
21165
  result_.collision = departing ? std::get<Collision>(low) : collision;
21166
+ if (erosion_) {
21167
+ auto real = captureContact(bracket[1], false);
21168
+ if (const auto failure = std::get_if<Status>(&real)) return fail(*failure);
21169
+ // The shrunk body lies inside the body, so the pair touches where the shrunk body does.
21170
+ if (!std::get<Collision>(real).hit) return fail(Status::Unresolved);
21171
+ result_.collision = std::get<Collision>(std::move(real));
21172
+ }
20773
21173
  if (material != nullptr && slab[0] < slab[1]
20774
21174
  && !hasMaterialAngularMotion(material->sources[0]->body().origin)
20775
21175
  && !hasMaterialAngularMotion(material->sources[1]->body().origin)) {
@@ -20874,6 +21274,12 @@ class MotionContactSearch {
20874
21274
  result_.certifiedEnd = low;
20875
21275
  result_.bracket = {low, high};
20876
21276
  result_.collision = departing ? std::move(lowCollision) : std::move(highCollision);
21277
+ if (erosion_) {
21278
+ auto real = captureContact(high, false);
21279
+ if (const auto* failure = std::get_if<Status>(&real)) return fail(*failure);
21280
+ if (!std::get<Collision>(real).hit) return fail(Status::Unresolved);
21281
+ result_.collision = std::get<Collision>(std::move(real));
21282
+ }
20877
21283
  return finish(departing ? Status::Departure : Status::Entry);
20878
21284
  }
20879
21285
  result_.certifiedEnd = end_;
@@ -20936,7 +21342,8 @@ class MotionContactSearch {
20936
21342
  }
20937
21343
  return Status::Clear;
20938
21344
  }
20939
- std::variant<Collision, MotionContactSearchStatus> captureContact(double time) {
21345
+ // The contact of the pair at `time`. An eroded search tests the shrunk body unless `eroded` is false.
21346
+ std::variant<Collision, MotionContactSearchStatus> captureContact(double time, bool eroded = true) {
20940
21347
  using Status = MotionContactSearchStatus;
20941
21348
  if (const auto* material = std::get_if<MaterialSearchGeometry>(&geometry_)) {
20942
21349
  std::shared_ptr<const MaterialContactWitness> witness;
@@ -20956,11 +21363,13 @@ class MotionContactSearch {
20956
21363
  std::array<Body, 2> trials;
20957
21364
  for (unsigned endpoint = 0; endpoint < 2; ++endpoint) {
20958
21365
  triangle_adapter_private::work(operation_);
20959
- if (!evaluateBodyMotionEpoch(epochs_[endpoint], bodies_[endpoint], time, trials[endpoint]))
21366
+ if (!evaluateBodyMotionEpoch(epochs_[endpoint], eroded ? searched_[endpoint] : bodies_[endpoint], time, trials[endpoint]))
20960
21367
  return Status::Unresolved;
20961
21368
  }
20962
21369
  triangle_adapter_private::work(operation_);
20963
21370
  const Collision collision = collide(operation_, trials[0], trials[1]);
21371
+ // A watch on the reported depth counts a contact only where it is deeper than the watched depth.
21372
+ if (eroded && reportedDepth_ && collision.hit && !(collision.penetration > *reportedDepth_)) return Collision{};
20964
21373
  if (collision.hit) {
20965
21374
  triangle_adapter_private::work(operation_);
20966
21375
  if (collision.pointCount > 4) return Status::Unresolved;
@@ -20976,7 +21385,11 @@ class MotionContactSearch {
20976
21385
  SolverOperation& operation_;
20977
21386
  const std::array<std::uint32_t, 2> pair_;
20978
21387
  const MotionContactTransition transition_;
21388
+ const std::optional<MotionPairErosion> erosion_;
21389
+ std::optional<double> reportedDepth_;
20979
21390
  std::array<Body, 2> bodies_;
21391
+ // The bodies that the classifier and the point tests use: `bodies_` with the erosion applied.
21392
+ std::array<Body, 2> searched_;
20980
21393
  std::array<BodyMotionEpoch, 2> epochs_;
20981
21394
  std::variant<NativeSearchGeometry, MaterialSearchGeometry> geometry_;
20982
21395
  const Body* bodyData_ = nullptr;
@@ -20996,12 +21409,22 @@ enum class MotionContactEventBatchStatus : std::uint8_t {
20996
21409
  Selected, Complete, InvalidInput, StaleInput, Unresolved, ResourceExhausted,
20997
21410
  AllocationFailure, UnsupportedGeometry, Consumed,
20998
21411
  };
20999
- // A native batch event is always an entry: a pair that is not engaged touches at `bracket[1]`.
21000
- // A pair leaves contact through the contact skin (see withinMotionContactSkin), not through an event.
21412
+ // What a native batch event starts. A pair leaves contact through the contact skin (see
21413
+ // withinMotionContactSkin), not through an event.
21414
+ enum class MotionContactEventKind : std::uint8_t {
21415
+ // A pair without contact episodes touches at `bracket[1]`, after the batch time.
21416
+ Entry,
21417
+ // A pair without contact episodes touches at the batch time. `bracket` is {now, now}.
21418
+ StartContact,
21419
+ // A pair with contact episodes becomes one contact skin deeper at `bracket[1]` than it was at the
21420
+ // batch time. Its current contact features that have no episode get one.
21421
+ Deepening,
21422
+ };
21001
21423
  struct MotionContactBatchEvent {
21002
21424
  std::array<std::uint32_t, 2> pair;
21003
21425
  std::array<double, 2> bracket;
21004
21426
  Collision collision;
21427
+ MotionContactEventKind kind = MotionContactEventKind::Entry;
21005
21428
  };
21006
21429
  struct MotionContactEventBatchView {
21007
21430
  double time = 0.0;
@@ -21118,12 +21541,18 @@ class MotionContactEventBatch {
21118
21541
  MotionContactEventBatch& operator=(MotionContactEventBatch&&) = delete;
21119
21542
  Status retireDepartures(ContactEventPhaseOwner& phase);
21120
21543
  Status activateEntries(ContactEventPhaseOwner& phase);
21121
- // Selects the earliest entry events. On the native path a bullet pair is engaged when it touches
21122
- // or when it has contact episodes (in operation.contactPhaseOwner) and stays within the contact
21123
- // skin. An engaged pair is not searched, so it causes no event. An entry needs a pair that is not
21124
- // engaged, and a pair stops being engaged only when its gap is larger than the skin. So each event
21125
- // after the first event of a pair needs a closing motion of the full skin, and the number of
21126
- // events in a substep is finite.
21544
+ // Selects the earliest events. On the native path a bullet pair is engaged when it has contact
21545
+ // episodes (in operation.contactPhaseOwner) and stays within the contact skin; a pair stops being
21546
+ // engaged only when its gap is larger than the skin.
21547
+ // - A pair that touches now and is not engaged is a StartContact event now: a touching pair always
21548
+ // has episodes, so it always gets a response. The next batch at the same time finds it engaged.
21549
+ // - A pair that touches now and is engaged is watched: an eroded search finds when it becomes one
21550
+ // skin deeper than now (Deepening). So a touching pair cannot sink or pass through a thin body
21551
+ // between two responses.
21552
+ // - A pair that does not touch now and is not engaged is searched for an entry.
21553
+ // Each Entry after the first of a pair needs a closing motion of the full skin, each Deepening
21554
+ // needs a deepening motion of the full skin, and a StartContact needs a pair that touches without
21555
+ // episodes, which happens at most once per batch time. So the number of events in a substep is finite.
21127
21556
  Status run() {
21128
21557
  if (ran_) return Status::Consumed;
21129
21558
  ran_ = true;
@@ -21169,23 +21598,28 @@ class MotionContactEventBatch {
21169
21598
  if ((!a.bullet && !b.bullet) || !bodiesCanCollide(a, b)
21170
21599
  || collisionDisabled(operation_, first, second)) continue;
21171
21600
  triangle_adapter_private::work(operation_);
21172
- if (collide(operation_, a, b).hit) continue;
21173
- if (hasEpisodes(operation_, first, second)) {
21601
+ const Collision touching = collide(operation_, a, b);
21602
+ const bool engaged = hasEpisodes(operation_, first, second);
21603
+ if (touching.hit && !engaged) {
21604
+ if (native.now < native.time) { native.events.clear(); native.time = native.now; }
21605
+ triangle_adapter_private::append(operation_, native.events, MotionContactBatchEvent{
21606
+ {first, second}, {native.now, native.now}, touching, MotionContactEventKind::StartContact});
21607
+ continue;
21608
+ }
21609
+ if (!touching.hit && engaged) {
21174
21610
  if (withinMotionContactSkin(operation_, a, b)) continue;
21175
21611
  triangle_adapter_private::append(operation_, native.separated, std::array<std::uint32_t, 2>{first, second});
21176
21612
  }
21613
+ // A StartContact event decides the batch time, so no later event can be selected.
21614
+ if (native.time == native.now) continue;
21615
+ if (touching.hit) {
21616
+ const auto status = watchEngagedPair(native, first, second, touching);
21617
+ if (status != Status::Complete) return fail(status);
21618
+ continue;
21619
+ }
21177
21620
  MotionContactSearch search(operation_, first, second, MotionContactTransition::Entry);
21178
- const auto result = search.run();
21179
- if (result == MotionContactSearchStatus::Clear) continue;
21180
- if (result != MotionContactSearchStatus::Entry) return fail(searchFailure(result));
21181
- MotionContactSearchView view;
21182
- const auto checked = search.read(operation_, view);
21183
- if (checked != result) return fail(searchFailure(checked));
21184
- if (view.timeDomain != MotionTimeDomain::NativeBinary64) return fail(Status::Unresolved);
21185
- if (view.bracket[1] > native.time) continue;
21186
- if (view.bracket[1] < native.time) { native.events.clear(); native.time = view.bracket[1]; }
21187
- triangle_adapter_private::append(operation_, native.events,
21188
- MotionContactBatchEvent{{first, second}, view.bracket, view.collision});
21621
+ const auto status = selectSearchEvent(native, search, search.run(), first, second, MotionContactEventKind::Entry);
21622
+ if (status != Status::Complete) return fail(status);
21189
21623
  }
21190
21624
  }
21191
21625
  const auto checked = validateSource();
@@ -21224,6 +21658,46 @@ class MotionContactEventBatch {
21224
21658
  private:
21225
21659
  static bool hasEpisodes(SolverOperation& operation, std::uint32_t first, std::uint32_t second);
21226
21660
  struct Source { Body body; BodyMotionEpoch epoch; };
21661
+ struct NativeSelection;
21662
+ // Adds the event of a search that returned `result` to the selection if it is not later than the
21663
+ // selected time.
21664
+ Status selectSearchEvent(NativeSelection& native, MotionContactSearch& search, MotionContactSearchStatus result,
21665
+ std::uint32_t first, std::uint32_t second, MotionContactEventKind kind) {
21666
+ if (result == MotionContactSearchStatus::Clear) return Status::Complete;
21667
+ if (result != MotionContactSearchStatus::Entry) return searchFailure(result);
21668
+ MotionContactSearchView view;
21669
+ const auto checked = search.read(operation_, view);
21670
+ if (checked != result) return searchFailure(checked);
21671
+ if (view.timeDomain != MotionTimeDomain::NativeBinary64 || !(view.bracket[1] > native.now)) return Status::Unresolved;
21672
+ if (view.bracket[1] > native.time) return Status::Complete;
21673
+ if (view.bracket[1] < native.time) { native.events.clear(); native.time = view.bracket[1]; }
21674
+ triangle_adapter_private::append(operation_, native.events,
21675
+ MotionContactBatchEvent{{first, second}, view.bracket, view.collision, kind});
21676
+ return Status::Complete;
21677
+ }
21678
+ // Watches an engaged pair that touches now: a Deepening event is the first time at which the pair
21679
+ // is one contact skin deeper than its depth now. The depth that collide() reports can be smaller
21680
+ // than the depth at which the shrunk body touches (a mesh pair reports the depth of one triangle),
21681
+ // so the watch doubles the extra depth until the shrunk body does not touch now. A pair with no
21682
+ // sphere, capsule or box is watched on its reported depth (ReportedDepth). A pair that is deeper
21683
+ // than its shrunk bodies can measure is not watched: it already overlaps more than the thinner
21684
+ // measurable body.
21685
+ Status watchEngagedPair(NativeSelection& native, std::uint32_t first, std::uint32_t second, const Collision& touching) {
21686
+ if (!finite(touching.penetration)) return Status::Unresolved;
21687
+ const auto& a = native.sources[first].body;
21688
+ const auto& b = native.sources[second].body;
21689
+ const double depth = std::max(touching.penetration, 0.0);
21690
+ for (double extra = kMotionContactSkin; finite(extra); extra *= 2.0) {
21691
+ triangle_adapter_private::work(operation_);
21692
+ const auto erosion = erodedMotionPair(a, b, depth + extra);
21693
+ if (!erosion) return Status::Complete;
21694
+ MotionContactSearch search(operation_, first, second, MotionContactTransition::Entry, erosion);
21695
+ const auto result = search.run();
21696
+ if (result == MotionContactSearchStatus::StartContact) continue;
21697
+ return selectSearchEvent(native, search, result, first, second, MotionContactEventKind::Deepening);
21698
+ }
21699
+ return Status::Unresolved;
21700
+ }
21227
21701
  struct NativeSelection {
21228
21702
  const Body* bodyData = nullptr;
21229
21703
  const BodyMotionEpoch* epochData = nullptr;
@@ -22344,11 +22818,7 @@ class ContactEventPhaseOwner {
22344
22818
  const auto& material = accepted ? accepted->material : warm->material;
22345
22819
  const auto& point = sameContactFrame(material.frame, geometry.frame)
22346
22820
  ? episode.constraint.point : contact.point;
22347
- staged.insert(staged.end(), {
22348
- static_cast<double>(contact.bodyA), static_cast<double>(contact.bodyB),
22349
- static_cast<double>(contact.featureId), contact.impulses[0], contact.impulses[1],
22350
- contact.impulses[2], point[0], point[1], point[2],
22351
- });
22821
+ appendContactCacheRow(staged, contact, point);
22352
22822
  }
22353
22823
  triangle_adapter_private::work(operation_);
22354
22824
  operation_.storage.contactCacheOutput.swap(staged);
@@ -22924,8 +23394,17 @@ MotionContactEventBatchStatus MotionContactEventBatch::activateEntries(ContactEv
22924
23394
  const auto& collision = event.collision;
22925
23395
  const Vec3 normal{collision.nx, collision.ny, collision.nz};
22926
23396
  const auto count = contactPointCount(collision);
23397
+ // A pair that touches without episodes must get at least one, or its batch time cannot pass.
23398
+ if (!collision.hit || (event.kind != MotionContactEventKind::Deepening && count == 0)) return reject(Status::Unresolved);
22927
23399
  for (std::uint32_t pointIndex = 0; pointIndex < count; ++pointIndex) {
22928
23400
  triangle_adapter_private::work(operation_);
23401
+ // A deepening pair keeps the episodes of the features that it already has.
23402
+ if (event.kind == MotionContactEventKind::Deepening) {
23403
+ const auto feature = contactFeatureId(collision, pointIndex);
23404
+ const auto index = phase.findEpisode(event.pair[0], event.pair[1], feature);
23405
+ if (index < phase.episodes_.size() && phase.episodes_[index].key == std::tuple{event.pair[0], event.pair[1], feature})
23406
+ continue;
23407
+ }
22929
23408
  const auto point = contactPoint(collision, a, b, pointIndex);
22930
23409
  const auto levers = triangle_adapter_private::collisionLevers(operation_, collision, pointIndex, a, b, point);
22931
23410
  const auto velocity = dotVec3(contactRelativeVelocity(a, b, levers[0], levers[1]), normal);
@@ -23117,7 +23596,14 @@ ContactEventPhaseOwner::ClockStatus ContactEventPhaseOwner::advanceMotionClock(
23117
23596
  MotionContactEventBatchView selected;
23118
23597
  const auto read = batch.read(operation_, selected);
23119
23598
  if (read != status) return batchFailure(read);
23120
- if (!(selected.time > operation_.committedMotionTime)
23599
+ // Only pairs that touch without episodes stop the clock without a time step. They get episodes
23600
+ // here, so the next batch at the same time cannot select them again.
23601
+ const bool startsNow = status == MotionContactEventBatchStatus::Selected && !selected.events.empty()
23602
+ && std::all_of(selected.events.begin(), selected.events.end(), [](const MotionContactBatchEvent& event) {
23603
+ return event.kind == MotionContactEventKind::StartContact;
23604
+ });
23605
+ if (!(selected.time > operation_.committedMotionTime
23606
+ || (startsNow && selected.time == operation_.committedMotionTime))
23121
23607
  || !stageBodyMotionAtTime(operation_, selected.time)
23122
23608
  || !publishStagedBodyMotion(operation_)) return reject(ClockStatus::Unresolved);
23123
23609
  }