@series-inc/rundot-syncplay 6.0.0-rc.128 → 6.0.0-rc.129

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.
@@ -6285,6 +6285,23 @@ std::int32_t syncplay_adapter_torque_representable(const double inertia[6], cons
6285
6285
  return kSyncplayAdapterOk;
6286
6286
  }
6287
6287
 
6288
+ } // extern "C"
6289
+ namespace {
6290
+ std::vector<std::int32_t>& stepProfileSlotsScratch() {
6291
+ static thread_local std::vector<std::int32_t> slots;
6292
+ return slots;
6293
+ }
6294
+ std::vector<std::uint8_t>& stepProfileTypesScratch() {
6295
+ static thread_local std::vector<std::uint8_t> types;
6296
+ return types;
6297
+ }
6298
+ std::vector<double>& stepProfileCentersScratch() {
6299
+ static thread_local std::vector<double> centers;
6300
+ return centers;
6301
+ }
6302
+ } // namespace
6303
+ extern "C" {
6304
+
6288
6305
  std::int32_t syncplay_adapter_world_reserve_step_rows(std::uint32_t slot, std::uint32_t* outRows) {
6289
6306
  WorldSlot* world = getWorld(slot);
6290
6307
  if (world == nullptr) return kSyncplayAdapterBadWorld;
@@ -6295,7 +6312,7 @@ std::int32_t syncplay_adapter_world_reserve_step_rows(std::uint32_t slot, std::u
6295
6312
  // the step creates does not touch (it would begin), so the contacts before the step bound both.
6296
6313
  const b3Counters counters = b3World_GetCounters(world->world);
6297
6314
  std::uint64_t rows = 2u * static_cast<std::uint64_t>(std::max(counters.contactCount, 0));
6298
- if (world->sensorEventsEnabled) {
6315
+ if (world->sensorEventsEnabled && syncplay_world_sensor_count(world->worldIndex) > 0u) {
6299
6316
  static thread_local std::vector<b3ShapeId> shapes;
6300
6317
  for (std::uint32_t bodyIndex = 0; bodyIndex < world->bodyCount; ++bodyIndex) {
6301
6318
  const BodyEntry& entry = world->bodies[bodyIndex];
@@ -6312,6 +6329,9 @@ std::int32_t syncplay_adapter_world_reserve_step_rows(std::uint32_t slot, std::u
6312
6329
  }
6313
6330
  rows = std::min<std::uint64_t>(rows, kSyncplayAdapterMaxPhysicsEvents);
6314
6331
  growPhysicsEventTable(*world, static_cast<std::size_t>(rows));
6332
+ stepProfileSlotsScratch().reserve(world->bodyCount);
6333
+ stepProfileTypesScratch().reserve(world->bodyCount);
6334
+ stepProfileCentersScratch().reserve(static_cast<std::size_t>(world->bodyCount) * 3u);
6315
6335
  *outRows = static_cast<std::uint32_t>(rows);
6316
6336
  return kSyncplayAdapterOk;
6317
6337
  }
@@ -6344,6 +6364,14 @@ std::int32_t syncplay_adapter_world_step(std::uint32_t slot, double timeStep,
6344
6364
  // The heap buffers of the step, before its first write: an allocation failure
6345
6365
  // here throws before the step changes the world or its step state (inStep), so the caller's image restores.
6346
6366
  reserveFirstImpacts(*world);
6367
+ {
6368
+ auto& slots = stepProfileSlotsScratch();
6369
+ auto& types = stepProfileTypesScratch();
6370
+ auto& centers = stepProfileCentersScratch();
6371
+ slots.reserve(world->bodyCount);
6372
+ types.reserve(world->bodyCount);
6373
+ centers.reserve(static_cast<std::size_t>(world->bodyCount) * 3u);
6374
+ }
6347
6375
  // The step-total joint reaction accumulator of the fork (syncplay_snapshot.h). The fork clears the
6348
6376
  // buffer and samples every live joint once per substep, so a read after the step gives the impulse
6349
6377
  // of the whole step and not the impulse of the last substep.
@@ -6649,18 +6677,27 @@ std::int32_t syncplay_adapter_world_step(std::uint32_t slot, double timeStep,
6649
6677
  // world center before the step and after it. Capture the start centers and the time step now, so
6650
6678
  // the profile read of the finished step has both halves of the predicate (solver.c:772-790).
6651
6679
  world->lastStepDt = timeStep;
6652
- for (std::uint32_t bodyIndex = 0; bodyIndex < world->bodyCount; ++bodyIndex) {
6653
- BodyEntry& entry = world->bodies[bodyIndex];
6654
- if (!b3Body_IsValid(entry.body)) {
6655
- entry.previousCenter[0] = 0.0;
6656
- entry.previousCenter[1] = 0.0;
6657
- entry.previousCenter[2] = 0.0;
6658
- continue;
6680
+ {
6681
+ auto& prevSlots = stepProfileSlotsScratch();
6682
+ auto& prevTypes = stepProfileTypesScratch();
6683
+ auto& prevCenters = stepProfileCentersScratch();
6684
+ const std::uint32_t count = world->bodyCount;
6685
+ prevSlots.resize(count);
6686
+ prevTypes.resize(count);
6687
+ prevCenters.resize(static_cast<std::size_t>(count) * 3u);
6688
+ for (std::uint32_t bodyIndex = 0; bodyIndex < count; ++bodyIndex) {
6689
+ const BodyEntry& entry = world->bodies[bodyIndex];
6690
+ prevSlots[bodyIndex] = entry.body.index1 - 1;
6691
+ prevTypes[bodyIndex] = static_cast<std::uint8_t>(entry.type);
6692
+ }
6693
+ syncplay_world_capture_prev_centers(world->worldIndex, prevSlots.data(), prevTypes.data(), count,
6694
+ prevCenters.data());
6695
+ for (std::uint32_t bodyIndex = 0; bodyIndex < count; ++bodyIndex) {
6696
+ BodyEntry& entry = world->bodies[bodyIndex];
6697
+ entry.previousCenter[0] = prevCenters[static_cast<std::size_t>(bodyIndex) * 3u + 0u];
6698
+ entry.previousCenter[1] = prevCenters[static_cast<std::size_t>(bodyIndex) * 3u + 1u];
6699
+ entry.previousCenter[2] = prevCenters[static_cast<std::size_t>(bodyIndex) * 3u + 2u];
6659
6700
  }
6660
- const b3Pos center = b3Body_GetWorldCenter(entry.body);
6661
- entry.previousCenter[0] = center.x;
6662
- entry.previousCenter[1] = center.y;
6663
- entry.previousCenter[2] = center.z;
6664
6701
  }
6665
6702
  // The public active-driven sleep rule: a motor with a target and a positive limit keeps its bodies
6666
6703
  // awake. The port's isJointActivelyDriven resets the sleep time of the driven bodies, so the island
@@ -7758,6 +7795,46 @@ std::int32_t syncplay_adapter_body_read(std::uint32_t slot, std::uint32_t logica
7758
7795
  return kSyncplayAdapterOk;
7759
7796
  }
7760
7797
 
7798
+ std::int32_t syncplay_adapter_bodies_read_step(std::uint32_t slot, std::uint32_t count,
7799
+ const std::uint32_t* logicalIds,
7800
+ const std::uint8_t* readMask,
7801
+ double* outStates13, std::uint8_t* outAwake) {
7802
+ WorldSlot* world = getWorld(slot);
7803
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
7804
+ if (count == 0) return kSyncplayAdapterOk;
7805
+ if (logicalIds == nullptr || readMask == nullptr || outStates13 == nullptr || outAwake == nullptr) {
7806
+ return kSyncplayAdapterBadArgument;
7807
+ }
7808
+ auto& bodySlots = stepProfileSlotsScratch();
7809
+ bodySlots.resize(count);
7810
+ for (std::uint32_t i = 0; i < count; ++i) {
7811
+ if (readMask[i] == 0u) {
7812
+ bodySlots[i] = -1;
7813
+ continue;
7814
+ }
7815
+ const BodyEntry* entry = findBody(*world, logicalIds[i]);
7816
+ if (entry == nullptr) return kSyncplayAdapterBadBody;
7817
+ bodySlots[i] = entry->body.index1 - 1;
7818
+ }
7819
+ g_activeSlot = static_cast<int>(slot);
7820
+ const std::int32_t status = syncplay_world_step_body_readback(
7821
+ world->worldIndex, bodySlots.data(), readMask, count, outStates13, outAwake);
7822
+ g_activeSlot = -1;
7823
+ return status == SYNCPLAY_SNAPSHOT_OK ? kSyncplayAdapterOk : kSyncplayAdapterBadBody;
7824
+ }
7825
+
7826
+ std::int32_t syncplay_adapter_touching_body_pairs_read(std::uint32_t slot, std::uint32_t* outPairs,
7827
+ std::uint32_t pairCapacity,
7828
+ std::uint32_t* outPairCount) {
7829
+ WorldSlot* world = getWorld(slot);
7830
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
7831
+ if (outPairCount == nullptr) return kSyncplayAdapterBadArgument;
7832
+ const std::int32_t status =
7833
+ syncplay_world_touching_body_pairs(world->worldIndex, outPairs, pairCapacity, outPairCount);
7834
+ if (status == SYNCPLAY_SNAPSHOT_CAPACITY) return kSyncplayAdapterCapacity;
7835
+ return status == SYNCPLAY_SNAPSHOT_OK ? kSyncplayAdapterOk : kSyncplayAdapterBadArgument;
7836
+ }
7837
+
7761
7838
  std::int32_t syncplay_adapter_body_world_center_read(std::uint32_t slot, std::uint32_t logicalId, double* out) {
7762
7839
  WorldSlot* world = getWorld(slot);
7763
7840
  if (world == nullptr) return kSyncplayAdapterBadWorld;
@@ -13357,6 +13434,42 @@ std::int32_t syncplay_adapter_profile_read_counters(std::uint32_t slot, double*
13357
13434
  return profileRead(slot, out, false);
13358
13435
  }
13359
13436
 
13437
+ } // extern "C"
13438
+ namespace {
13439
+ std::vector<double>& touchingManifoldRowsScratch() {
13440
+ static thread_local std::vector<double> rows;
13441
+ return rows;
13442
+ }
13443
+ ContactScratch& touchingManifoldContactScratch() {
13444
+ static thread_local ContactScratch scratch;
13445
+ return scratch;
13446
+ }
13447
+ } // namespace
13448
+ extern "C" {
13449
+
13450
+ std::int32_t syncplay_adapter_reserve_body_touching(std::uint32_t slot, std::uint32_t logicalId,
13451
+ std::uint32_t* outCapacity) {
13452
+ WorldSlot* world = getWorld(slot);
13453
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
13454
+ if (outCapacity == nullptr) return kSyncplayAdapterBadArgument;
13455
+ BodyEntry* entry = findBody(*world, logicalId);
13456
+ if (entry == nullptr) return kSyncplayAdapterBadBody;
13457
+ g_activeSlot = static_cast<int>(slot);
13458
+ const int cap = std::max(b3Body_GetContactCapacity(entry->body), 0);
13459
+ g_activeSlot = -1;
13460
+ const std::size_t capacity = static_cast<std::size_t>(cap);
13461
+ ContactScratch& scratch = touchingManifoldContactScratch();
13462
+ if (scratch.contacts.size() < capacity) {
13463
+ scratch.contacts.resize(capacity);
13464
+ scratch.bodyOfShapeA.resize(capacity);
13465
+ scratch.bodyOfShapeB.resize(capacity);
13466
+ }
13467
+ std::vector<double>& rows = touchingManifoldRowsScratch();
13468
+ if (rows.capacity() < capacity * 70u) rows.reserve(capacity * 70u);
13469
+ *outCapacity = static_cast<std::uint32_t>(capacity);
13470
+ return kSyncplayAdapterOk;
13471
+ }
13472
+
13360
13473
  std::int32_t syncplay_adapter_touching_manifolds_read(std::uint32_t slot, std::uint32_t body,
13361
13474
  double* out, std::uint32_t capacity,
13362
13475
  std::uint32_t* outCount) {
@@ -13364,8 +13477,8 @@ std::int32_t syncplay_adapter_touching_manifolds_read(std::uint32_t slot, std::u
13364
13477
  if (world == nullptr) return kSyncplayAdapterBadWorld;
13365
13478
  if (outCount == nullptr) return kSyncplayAdapterBadArgument;
13366
13479
  *outCount = 0;
13367
- static thread_local std::vector<double> rows;
13368
- static thread_local ContactScratch scratch;
13480
+ std::vector<double>& rows = touchingManifoldRowsScratch();
13481
+ ContactScratch& scratch = touchingManifoldContactScratch();
13369
13482
  rows.clear();
13370
13483
  std::uint32_t firstBody = 0;
13371
13484
  std::uint32_t lastBody = world->bodyCount;
@@ -13454,6 +13567,26 @@ std::int32_t profileRead(std::uint32_t slot, double* out, bool walkContacts) {
13454
13567
  std::uint32_t contactPoints = 0;
13455
13568
  std::uint32_t awakeBodies = 0;
13456
13569
  std::uint32_t continuousSweeps = 0;
13570
+ if (!walkContacts) {
13571
+ auto& bodySlots = stepProfileSlotsScratch();
13572
+ auto& bodyTypes = stepProfileTypesScratch();
13573
+ auto& prevCenters = stepProfileCentersScratch();
13574
+ const std::uint32_t count = world->bodyCount;
13575
+ bodySlots.resize(count);
13576
+ bodyTypes.resize(count);
13577
+ prevCenters.resize(static_cast<std::size_t>(count) * 3u);
13578
+ for (std::uint32_t bodyIndex = 0; bodyIndex < count; ++bodyIndex) {
13579
+ const BodyEntry& entry = world->bodies[bodyIndex];
13580
+ bodySlots[bodyIndex] = entry.body.index1 - 1;
13581
+ bodyTypes[bodyIndex] = static_cast<std::uint8_t>(entry.type);
13582
+ prevCenters[static_cast<std::size_t>(bodyIndex) * 3u + 0u] = entry.previousCenter[0];
13583
+ prevCenters[static_cast<std::size_t>(bodyIndex) * 3u + 1u] = entry.previousCenter[1];
13584
+ prevCenters[static_cast<std::size_t>(bodyIndex) * 3u + 2u] = entry.previousCenter[2];
13585
+ }
13586
+ syncplay_world_read_step_profile(world->worldIndex, bodySlots.data(), bodyTypes.data(),
13587
+ prevCenters.data(), count, world->lastStepDt,
13588
+ &awakeBodies, &continuousSweeps);
13589
+ } else {
13457
13590
  for (std::uint32_t bodyIndex = 0; bodyIndex < world->bodyCount; ++bodyIndex) {
13458
13591
  BodyEntry& entry = world->bodies[bodyIndex];
13459
13592
  if (entry.type != kSyncplayAdapterStaticBody && b3Body_IsAwake(entry.body)) awakeBodies += 1;
@@ -13482,7 +13615,6 @@ std::int32_t profileRead(std::uint32_t slot, double* out, bool walkContacts) {
13482
13615
  const double maxMotion = std::max(maxDeltaPosition, maxVelocity * world->lastStepDt);
13483
13616
  if (maxMotion > safetyFactor * minExtent) continuousSweeps += 1;
13484
13617
  }
13485
- if (!walkContacts) continue;
13486
13618
  static thread_local ContactScratch scratch;
13487
13619
  const BodyContacts list = contactsOfBody(slot, *world, bodyIndex, scratch);
13488
13620
  const int count = list.count;
@@ -13495,6 +13627,7 @@ std::int32_t profileRead(std::uint32_t slot, double* out, bool walkContacts) {
13495
13627
  }
13496
13628
  }
13497
13629
  }
13630
+ }
13498
13631
  g_activeSlot = -1;
13499
13632
  out[0] = static_cast<double>(counters.contactCount);
13500
13633
  out[1] = static_cast<double>(counters.contactCount);
@@ -286,6 +286,19 @@ std::int32_t syncplay_adapter_body_create_heightfield(
286
286
 
287
287
  // Writes 13 doubles: position xyz, rotation xyzw, linear velocity xyz, angular velocity xyz.
288
288
  std::int32_t syncplay_adapter_body_read(std::uint32_t slot, std::uint32_t logicalId, double* out);
289
+ // Batched step-end body readback: reads awake flags and (per readMask) transforms + velocities in one call.
290
+ // readMask[i]: 0 = skip, 1 = always read 13 doubles, 2 = read 13 doubles only if awake.
291
+ std::int32_t syncplay_adapter_bodies_read_step(std::uint32_t slot, std::uint32_t count,
292
+ const std::uint32_t* logicalIds,
293
+ const std::uint8_t* readMask,
294
+ double* outStates13, std::uint8_t* outAwake);
295
+ // Reserve adapter touching-manifold scratch buffers for one body without extracting manifolds.
296
+ std::int32_t syncplay_adapter_reserve_body_touching(std::uint32_t slot, std::uint32_t logicalId,
297
+ std::uint32_t* outCapacity);
298
+ // Lightweight touching solid contact pairs (logicalA, logicalB) without manifold extraction.
299
+ std::int32_t syncplay_adapter_touching_body_pairs_read(std::uint32_t slot, std::uint32_t* outPairs,
300
+ std::uint32_t pairCapacity,
301
+ std::uint32_t* outPairCount);
289
302
  // Writes 6 doubles: the world centre of mass that the Box3D body holds (b3Body_GetWorldCenter,
290
303
  // bodySim->center), then its local centre of mass (b3Body_GetMassData), as they are.
291
304
  // b3Body_SetMassData moves the linear velocity by w x (new centre - this centre), so a replay of
@@ -452,6 +452,9 @@ struct Box3dBackendState {
452
452
  std::vector<StaleSleep> counterSnapshotStale;
453
453
  // Monotonic epoch bumped on every mirror mutation, sync, step, restore, or drop.
454
454
  std::uint64_t stateEpoch = 1;
455
+ // Recycled per-world WorldState scratch swapped with world.state_ on steady-state steps.
456
+ // Lives on the world (not thread_local) so world destruction releases all capacity cleanly.
457
+ WorldState stepStateScratch;
455
458
  };
456
459
 
457
460
  namespace {
@@ -3566,8 +3569,9 @@ bool saveMirrorImage(const BackendMirror& mirror, std::vector<std::uint8_t>& out
3566
3569
  return false;
3567
3570
  }
3568
3571
  image.resize(written);
3572
+ const std::size_t mirrorGrowthBytes = std::clamp<std::size_t>(written / 32u, 4096u, 64u * 1024u);
3569
3573
  mirror.canonicalSizeHint = static_cast<std::uint32_t>(
3570
- std::min<std::size_t>(static_cast<std::size_t>(written) + 512u, kBox3dCanonicalMaxBytes));
3574
+ std::min<std::size_t>(static_cast<std::size_t>(written) + mirrorGrowthBytes, kBox3dCanonicalMaxBytes));
3571
3575
  if (mirror.portalSlices.empty()) {
3572
3576
  output = std::move(image);
3573
3577
  return true;
@@ -3846,8 +3850,8 @@ std::uint32_t captureCanonicalImage(const World& world, Box3dCanonicalBytes& out
3846
3850
  return kBox3dCanonicalFailed;
3847
3851
  }
3848
3852
  output.resize(prefixBytes + written);
3849
- // Allow small changes in contact and event counts to fit on the first save.
3850
- const std::size_t growthBytes = std::clamp<std::size_t>(written / 256u, 512u, 16u * 1024u);
3853
+ // Allow changes in contact and event counts during blasts to fit on the first save.
3854
+ const std::size_t growthBytes = std::clamp<std::size_t>(written / 32u, 4096u, 64u * 1024u);
3851
3855
  mirror->canonicalSizeHint = static_cast<std::uint32_t>(
3852
3856
  std::min<std::size_t>(static_cast<std::size_t>(written) + growthBytes, kBox3dCanonicalMaxBytes));
3853
3857
  if (flags != 0) {
@@ -5936,10 +5940,54 @@ bool readOnDemandManifolds(const World& constWorld, BodyId body,
5936
5940
  }
5937
5941
  }
5938
5942
 
5943
+ bool readOnDemandTouchingPairs(const World& constWorld,
5944
+ std::vector<std::pair<BodyId, BodyId>>& output) noexcept {
5945
+ try {
5946
+ const BackendMirror* mirror = mirrorOf(constWorld);
5947
+ const WorldState& state = constWorld.state();
5948
+ if (mirror == nullptr || !lastStepHeld(*mirror) || mirror->frame != state.frame) return false;
5949
+ output.clear();
5950
+ if (!mirror->steppedSinceBuild && mirror->lastStep.has_value()) {
5951
+ output.reserve(mirror->lastStep->bodies.size());
5952
+ for (const auto& pair : mirror->lastStep->bodies) {
5953
+ output.emplace_back(pair[0], pair[1]);
5954
+ }
5955
+ return true;
5956
+ }
5957
+ static thread_local std::vector<std::uint32_t> rawPairs;
5958
+ std::uint32_t count = 0;
5959
+ std::int32_t status = syncplay_adapter_touching_body_pairs_read(
5960
+ mirror->slot, rawPairs.data(), static_cast<std::uint32_t>(rawPairs.size() / 2), &count);
5961
+ if (status == kSyncplayAdapterCapacity) {
5962
+ rawPairs.resize(static_cast<std::size_t>(count) * 2);
5963
+ status = syncplay_adapter_touching_body_pairs_read(mirror->slot, rawPairs.data(), count, &count);
5964
+ }
5965
+ if (status != kSyncplayAdapterOk) return false;
5966
+ std::vector<std::int32_t> denseOf;
5967
+ denseIndexByLogical(*mirror, state, denseOf);
5968
+ output.reserve(count);
5969
+ for (std::uint32_t i = 0; i < count; ++i) {
5970
+ const std::uint32_t logicalA = rawPairs[static_cast<std::size_t>(i) * 2];
5971
+ const std::uint32_t logicalB = rawPairs[static_cast<std::size_t>(i) * 2 + 1];
5972
+ if (logicalA >= denseOf.size() || logicalB >= denseOf.size()) continue;
5973
+ const std::int32_t indexA = denseOf[logicalA];
5974
+ const std::int32_t indexB = denseOf[logicalB];
5975
+ if (indexA < 0 || indexB < 0) continue;
5976
+ output.emplace_back(state.topology.bodyIds[static_cast<std::size_t>(indexA)],
5977
+ state.topology.bodyIds[static_cast<std::size_t>(indexB)]);
5978
+ }
5979
+ return true;
5980
+ } catch (...) {
5981
+ output.clear();
5982
+ return false;
5983
+ }
5984
+ }
5985
+
5939
5986
  struct Box3dContactReaderInstaller {
5940
5987
  Box3dContactReaderInstaller() {
5941
5988
  installBox3dContactReader(readOnDemandContacts);
5942
5989
  installBox3dManifoldReader(readOnDemandManifolds);
5990
+ installBox3dTouchingPairsReader(readOnDemandTouchingPairs);
5943
5991
  }
5944
5992
  };
5945
5993
  const Box3dContactReaderInstaller g_box3dContactReaderInstaller{};
@@ -8146,13 +8194,13 @@ StepRollback& heldRollback(HeldStep& held) noexcept { return held.rollback; }
8146
8194
  // the step either fails before it with the world as it was (StepRollback), or publishes, consumes its one-step
8147
8195
  // inputs and commits as one unit. Work that can fail (an allocation, a read) belongs in backendStep before the
8148
8196
  // call, never here.
8149
- void publishCompletedStep(World& world, WorldState&& updated, std::vector<WorldBodyMoveEvent>&& moves,
8197
+ void publishCompletedStep(World& world, WorldState& updated, std::vector<WorldBodyMoveEvent>&& moves,
8150
8198
  std::vector<double>& manifoldRows, const StepCounters& counters, bool portalStep,
8151
8199
  BackendMirror& mirror, StepRollback& rollback, bool held) noexcept {
8152
8200
  // The one publication point of a routed step (world.hpp: the state is the state this world
8153
8201
  // already held, stepped). It keeps the query index exact across the publication, so no step may
8154
8202
  // write state_ anywhere else.
8155
- publishBox3dStepState(world, std::move(updated));
8203
+ publishBox3dStepState(world, updated);
8156
8204
  // The step published, so it consumes its one-step inputs here and not before: a step that fails returns
8157
8205
  // above with every input still staged, as World::step keeps the rules of a failed step. The pair-filter
8158
8206
  // inputs (the exclusions, the restricted bodies, the allowed pairs and the contact groups) apply to one
@@ -8350,6 +8398,17 @@ BackendResult syncMirrorToState(World& world, const WorldState& source, const St
8350
8398
  // Its room is made before any live write, so filling it after the removal or the edit allocates nothing.
8351
8399
  std::vector<std::uint8_t> keepAwakeAfterEdit;
8352
8400
  keepAwakeAfterEdit.reserve(bodyCount);
8401
+ // Pre-sized before any live write so batched state sync allocates nothing in the Live phase.
8402
+ std::vector<std::uint32_t> syncLogicalIds;
8403
+ std::vector<std::uint8_t> syncMask;
8404
+ std::vector<std::uint8_t> syncAwake;
8405
+ std::vector<double> syncStates;
8406
+ if (revisionChanged) {
8407
+ syncLogicalIds.resize(bodyCount);
8408
+ syncMask.assign(bodyCount, 1u);
8409
+ syncAwake.resize(bodyCount);
8410
+ syncStates.resize(bodyCount * 13u);
8411
+ }
8353
8412
  // `asleepBefore(index)`: the survivor slept natively before the removal or the edit in place.
8354
8413
  const auto keepAwakeOf = [&](const auto& asleepBefore) -> bool {
8355
8414
  keepAwakeAfterEdit.assign(bodyCount, 0);
@@ -8706,18 +8765,20 @@ BackendResult syncMirrorToState(World& world, const WorldState& source, const St
8706
8765
  // flag differs from that native state: a body that a write of this sync woke or put to sleep through its
8707
8766
  // island is no request. The sleeps go first, then the writes (a write after a sleep keeps its velocity),
8708
8767
  // then the wakes, so a wake of a body survives the sleep of another body of its island.
8709
- for (std::size_t index = 0; index < bodyCount && valid; ++index) {
8710
- if (syncplay_adapter_body_read(slot, adapterBodyId(mirror, index), current[index].data()) != kSyncplayAdapterOk) {
8711
- valid = false;
8712
- break;
8768
+ {
8769
+ for (std::size_t index = 0; index < bodyCount; ++index) {
8770
+ syncLogicalIds[index] = adapterBodyId(mirror, index);
8713
8771
  }
8714
- bool awake = false;
8715
- if (!adapterBodyAwake(slot, adapterBodyId(mirror, index), awake)) {
8772
+ if (syncplay_adapter_bodies_read_step(slot, static_cast<std::uint32_t>(bodyCount),
8773
+ syncLogicalIds.data(), syncMask.data(), syncStates.data(), syncAwake.data())
8774
+ != kSyncplayAdapterOk) {
8716
8775
  valid = false;
8717
- g_backendError = "body awake read of the state sync";
8718
- break;
8776
+ } else {
8777
+ for (std::size_t index = 0; index < bodyCount; ++index) {
8778
+ std::memcpy(current[index].data(), syncStates.data() + index * 13u, 13u * sizeof(double));
8779
+ awakeBefore[index] = syncAwake[index] != 0u ? 1 : 0;
8780
+ }
8719
8781
  }
8720
- awakeBefore[index] = awake ? 1 : 0;
8721
8782
  }
8722
8783
  const auto shouldBeAwake = [&](std::size_t index) {
8723
8784
  const std::uint32_t motion = static_cast<std::uint32_t>(source.bodies[index * bodyStride + 9]);
@@ -9195,7 +9256,7 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9195
9256
  : backendDefinitionSignature(world, source, bodyStride);
9196
9257
  const std::uint64_t signature = backendSignatureFromDefinition(definitionSignature, options);
9197
9258
  const bool ownedByThisWorld = mirror.built;
9198
- const RemovalWake removalWake = removalWakeOf(mirror, source);
9259
+ const RemovalWake removalWake = steadyStepCacheHit ? RemovalWake{} : removalWakeOf(mirror, source);
9199
9260
  // A mirror that a canonical image installed has the bookkeeping of the mirror that stepped to the restored state
9200
9261
  // (adoptRestoredState): its frame, its revision and the signature of its definition and step options. So the
9201
9262
  // gates below decide for it exactly as for the producer: a step input that the caller writes after the restore (a
@@ -9293,6 +9354,10 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9293
9354
  std::vector<std::int32_t> touchingDense;
9294
9355
  std::vector<WorldContactManifold> touchingManifolds;
9295
9356
  std::vector<WorldContactManifold> rowManifolds;
9357
+ std::vector<std::uint32_t> readLogicalIds;
9358
+ std::vector<std::uint8_t> readMask;
9359
+ std::vector<double> readStates;
9360
+ std::vector<std::uint8_t> readAwake;
9296
9361
  };
9297
9362
  static thread_local LiveWindowScratch live;
9298
9363
  live.current.resize(bodyCount);
@@ -9304,6 +9369,10 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9304
9369
  live.contactsAfterRead.assign(bodyCount, 0);
9305
9370
  live.materialSides.resize(bodyCount);
9306
9371
  live.materialSideKnown.assign(bodyCount, 0);
9372
+ live.readLogicalIds.resize(bodyCount);
9373
+ live.readMask.resize(bodyCount);
9374
+ live.readStates.resize(bodyCount * 13u);
9375
+ live.readAwake.resize(bodyCount);
9307
9376
  live.oneWayRows.reserve(bodyCount * kBackendOneWayRowValues);
9308
9377
  live.supportRows.springs.reserve(source.tickSupports.springs.size() * kBackendSupportSpringStride);
9309
9378
  live.supportRows.forces.reserve(source.tickSupports.forces.size() * kBackendSupportForceStride);
@@ -9347,7 +9416,37 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9347
9416
  && !readLiveSensorOverlaps(world, source, source, bodyStride, mirror, live.overlapsAfter)) {
9348
9417
  return failBackend("the sensor overlap read before the step failed");
9349
9418
  }
9350
- WorldState updated = source;
9419
+ // Reuse the per-world swapped-out WorldState scratch buffers across ticks and skip copying fields that
9420
+ // the completed step clears/rebuilds (contactEvents, contactCache, tickForces, tickSupports,
9421
+ // jointWarmState, jointReactions, jointBreakEvents, fluidInteractions).
9422
+ WorldState localFallbackUpdated;
9423
+ WorldState& updated = backendState != nullptr ? backendState->stepStateScratch : localFallbackUpdated;
9424
+ struct ScratchGeometryRelease {
9425
+ WorldState& state;
9426
+ ~ScratchGeometryRelease() noexcept {
9427
+ state.geometry = std::vector<double>{};
9428
+ }
9429
+ } scratchGeometryRelease{updated};
9430
+ updated.bodies = source.bodies;
9431
+ updated.joints = source.joints;
9432
+ updated.geometry = source.geometry;
9433
+ updated.contactCache.clear();
9434
+ updated.forces = source.forces;
9435
+ updated.tickForces.clear();
9436
+ updated.tickSupports = WorldTickSupports{};
9437
+ updated.fluids = source.fluids;
9438
+ updated.jointWarmState.clear();
9439
+ updated.topology = source.topology;
9440
+ updated.bodyMaterials = source.bodyMaterials;
9441
+ updated.bodyMaterialFrames = source.bodyMaterialFrames;
9442
+ updated.frame = source.frame;
9443
+ updated.surfaceVelocities = source.surfaceVelocities;
9444
+ updated.contactEvents.clear();
9445
+ updated.jointReactions.clear();
9446
+ updated.jointBreakEvents.clear();
9447
+ updated.fluidInteractions.clear();
9448
+ updated.contactCacheH = source.contactCacheH;
9449
+ updated.backendSettings = source.backendSettings;
9351
9450
  // The contact rows of the step before the merge of one key (mergeContactRowsOfOneKey): in a step where no contact
9352
9451
  // or overlap begins, each open row of the source gives at most an end, a stay and a hit row.
9353
9452
  updated.contactEvents.reserve(source.contactEvents.size() * 3 + stepRows + carriedKeys);
@@ -9382,6 +9481,7 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9382
9481
  // edit saves the image) is not read, and a read that fails changes no result of the step.
9383
9482
  if (ownedByThisWorld && mirror.built && !mirror.pendingSync && mirror.signature == signature) {
9384
9483
  bool denseRead = false;
9484
+ std::uint32_t maxBodyCap = 0;
9385
9485
  const auto moving = [&](std::size_t index) {
9386
9486
  return (static_cast<std::uint32_t>(source.bodies[index * bodyStride + 9]) & 3u) != 0u;
9387
9487
  };
@@ -9396,10 +9496,10 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9396
9496
  denseIndexByLogical(mirror, source, live.touchingDense);
9397
9497
  denseRead = true;
9398
9498
  }
9399
- live.touchingManifolds.clear();
9400
- if (readTouchingManifolds(world, source, bodyStride, mirror, live.touchingDense, adapterBodyId(mirror, side),
9401
- live.touchingManifolds)) {
9402
- live.touchingOfBody[side].reserve(live.touchingManifolds.size());
9499
+ std::uint32_t cap = 0;
9500
+ if (syncplay_adapter_reserve_body_touching(slot, adapterBodyId(mirror, side), &cap) == kSyncplayAdapterOk) {
9501
+ if (live.touchingOfBody[side].capacity() < cap) live.touchingOfBody[side].reserve(cap);
9502
+ if (cap > maxBodyCap) maxBodyCap = cap;
9403
9503
  }
9404
9504
  };
9405
9505
  for (const WorldContactEvent& open : source.contactEvents) {
@@ -9407,6 +9507,9 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9407
9507
  readBefore(open.bodyA, open.bodyB);
9408
9508
  }
9409
9509
  for (const ManifoldKey& key : mirror.carriedTouching) readBefore(key.bodyA, key.bodyB);
9510
+ if (maxBodyCap > 0 && live.touchingManifolds.capacity() < maxBodyCap) {
9511
+ live.touchingManifolds.reserve(maxBodyCap);
9512
+ }
9410
9513
  live.touchingRead.assign(bodyCount, 0);
9411
9514
  }
9412
9515
  if (dropsPortalSlices) {
@@ -9654,31 +9757,41 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9654
9757
  const bool incrementalBounds = canSkipUnchangedBodies && mirror.bodyBounds.size() == bodyCount * 6;
9655
9758
  if (!incrementalBounds) mirror.bodyBounds.assign(bodyCount * 6, 0.0);
9656
9759
  for (std::size_t index = 0; index < bodyCount; ++index) {
9657
- double* body = updated.bodies.data() + index * bodyStride;
9760
+ const double* body = updated.bodies.data() + index * bodyStride;
9658
9761
  const std::uint32_t motion = static_cast<std::uint32_t>(body[9]);
9659
9762
  const std::uint32_t bodyKind = motion & 3u;
9660
- if (canSkipUnchangedBodies && bodyKind == 0u) continue;
9661
- bool adapterAwake = false;
9662
- const bool wasSleeping = (motion & kMotionSleeping) != 0;
9663
- if (bodyKind != 0u) {
9664
- if (!adapterBodyAwake(slot, adapterBodyId(mirror, index), adapterAwake)) {
9665
- return failBackend("body awake read after the step");
9666
- }
9763
+ live.readLogicalIds[index] = adapterBodyId(mirror, index);
9764
+ if (canSkipUnchangedBodies && bodyKind == 0u) {
9765
+ live.readMask[index] = 0u;
9766
+ } else if (bodyKind != 0u) {
9767
+ const bool wasSleeping = (motion & kMotionSleeping) != 0;
9667
9768
  const bool hasVeto = index < mirror.removalSleepVeto.size() && mirror.removalSleepVeto[index] != 0;
9668
- if (canSkipUnchangedBodies && wasSleeping && !adapterAwake && !hasVeto
9669
- && options.enableSleep && body[41] != 0.0) {
9670
- continue;
9671
- }
9672
- }
9673
- double state[13] = {};
9674
- if (syncplay_adapter_body_read(slot, adapterBodyId(mirror, index), state) != kSyncplayAdapterOk) {
9675
- return BackendResult::failed;
9769
+ live.readMask[index] = (canSkipUnchangedBodies && wasSleeping && !hasVeto
9770
+ && options.enableSleep && body[41] != 0.0) ? 2u : 1u;
9771
+ } else {
9772
+ live.readMask[index] = 1u;
9676
9773
  }
9774
+ }
9775
+ if (syncplay_adapter_bodies_read_step(slot, static_cast<std::uint32_t>(bodyCount),
9776
+ live.readLogicalIds.data(), live.readMask.data(),
9777
+ live.readStates.data(), live.readAwake.data()) != kSyncplayAdapterOk) {
9778
+ return BackendResult::failed;
9779
+ }
9780
+ for (std::size_t index = 0; index < bodyCount; ++index) {
9781
+ const std::uint8_t mode = live.readMask[index];
9782
+ if (mode == 0u) continue;
9783
+ const bool adapterAwake = live.readAwake[index] != 0u;
9784
+ if (mode == 2u && !adapterAwake) continue;
9785
+ double* body = updated.bodies.data() + index * bodyStride;
9786
+ const std::uint32_t motion = static_cast<std::uint32_t>(body[9]);
9787
+ const std::uint32_t bodyKind = motion & 3u;
9788
+ const bool wasSleeping = (motion & kMotionSleeping) != 0;
9789
+ const double* state = live.readStates.data() + index * 13u;
9677
9790
  // A step that produces a value that is not finite is rejected as a whole: the public state stays
9678
9791
  // at its previous frame and the mirror is dropped, as the previous engine rejected such a frame
9679
9792
  // before it published anything.
9680
- for (const double value : state) {
9681
- if (std::isfinite(value)) continue;
9793
+ for (int f = 0; f < 13; ++f) {
9794
+ if (std::isfinite(state[f])) continue;
9682
9795
  g_backendError = "the step produced a body state that is not finite";
9683
9796
  return BackendResult::failed;
9684
9797
  }
@@ -9710,14 +9823,6 @@ BackendResult backendStep(World& world, const StepOptions& options) {
9710
9823
  double timer = wasSleeping ? previousTimer
9711
9824
  : (sleepSpeed < body[40] ? previousTimer + timerStep : 0.0);
9712
9825
  if (!wasSleeping && source.frame == 0 && !source.surfaceVelocities.empty()) timer = 0.0;
9713
- // Box3D is the only sleep authority of this route. Box3D sleeps a whole island when the smallest
9714
- // sleep time of its bodies reaches B3_TIME_TO_SLEEP (solver.c b3FinalizeBodiesTask, then
9715
- // b3TrySleepIsland in b3SolverStep), and a kinematic body sleeps with the island that rests on
9716
- // it (island.c). A per-body timer cannot decide this: it sleeps a body whose island partner still
9717
- // moves, and the sleep call on that body then sleeps the whole Box3D island before Box3D does
9718
- // (box3d-solver-sleep-gaps gap 8, box3d-tree-broadphase-stack). So the public flag copies the
9719
- // native island state. The public timer is published for the public record only; no decision of
9720
- // this route reads it.
9721
9826
  const bool awake = !options.enableSleep || body[41] == 0.0 || adapterAwake;
9722
9827
  if (!options.enableSleep || body[41] == 0.0) timer = 0.0;
9723
9828
  if (awake) {
@@ -10533,7 +10638,7 @@ BackendResult backendStep(World& world, const StepOptions& options) {
10533
10638
  // The manifolds of the step are read on demand (World::latestManifolds), so the step hands none over.
10534
10639
  static thread_local std::vector<double> noManifoldRows;
10535
10640
  noManifoldRows.clear();
10536
- publishCompletedStep(world, std::move(updated), std::move(moves), noManifoldRows, counters, portalStep, mirror,
10641
+ publishCompletedStep(world, updated, std::move(moves), noManifoldRows, counters, portalStep, mirror,
10537
10642
  rollback, holding);
10538
10643
  heldExit.published = true;
10539
10644
  return BackendResult::ok;