castle-web-cli 0.4.240 → 0.4.242

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/bundle.d.ts +9 -1
  2. package/dist/bundle.js +214 -25
  3. package/dist/init.js +1 -1
  4. package/dist/multiplayerDoc.d.ts +1 -1
  5. package/dist/multiplayerDoc.js +2 -0
  6. package/dist/platformDoc.js +3 -3
  7. package/dist/playPagePolicy.js +7 -6
  8. package/dist/roomLogs.d.ts +1 -0
  9. package/dist/roomLogs.js +30 -6
  10. package/dist/save-deck.js +20 -3
  11. package/kits/base/castle.json +1 -1
  12. package/kits/base/sdk/README.md +7 -0
  13. package/kits/base/sdk/context.d.ts +5 -0
  14. package/kits/base/sdk/debugConsole.d.ts +1 -0
  15. package/kits/base/sdk/debugConsole.js +87 -14
  16. package/kits/base/sdk/runtime.js +5 -4
  17. package/kits/hub-game/code/client/chrome.js +8 -4
  18. package/kits/hub-game/code/client/padCues.js +11 -7
  19. package/kits/hub-game/code/client/padReadability.js +3 -3
  20. package/kits/hub-game/code/client/visibility.js +14 -4
  21. package/kits/hub-game/code/server/hub.js +146 -30
  22. package/kits/hub-game/code/server/players.js +6 -1
  23. package/kits/hub-game/code/server/standing.js +7 -3
  24. package/kits/hub-game/code/systems/hub.js +11 -3
  25. package/kits/hub-game/docs/contract.md +25 -4
  26. package/kits/hub-game/scripts/test-ballot.mjs +1 -1
  27. package/kits/hub-game/scripts/test-hub-trip.mjs +24 -0
  28. package/kits/hub-game/scripts/test-pad-cues.mjs +39 -0
  29. package/kits/hub-game/scripts/test-placeat-server.mjs +259 -6
  30. package/kits/hub-game/scripts/test-rehello.mjs +5 -3
  31. package/kits/hub-game/scripts/test-standing.mjs +135 -2
  32. package/kits/hub-game/scripts/test-stuck.mjs +5 -1
  33. package/kits/hub-game/scripts/test-visibility.mjs +54 -0
  34. package/kits/multiplayer-3d/castle.json +1 -1
  35. package/kits/multiplayer-3d/code/client/resumeGate.js +18 -1
  36. package/kits/multiplayer-3d/code/systems/multiplayer.js +41 -7
  37. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +226 -0
  38. package/kits/physics-3d/castle.json +1 -1
  39. package/kits/physics-3d/package.json +1 -1
  40. package/kits/physics-3d/scripts/test-coaxial-escape.mjs +176 -0
  41. package/kits/physics-3d/systems/physics3d.js +8 -0
  42. package/package.json +1 -1
@@ -71,7 +71,7 @@ export const RESYNC_REPLY_MS = 3000;
71
71
  // `replyExpired` whether its unanswered reply has been reported, and `hiddenAt`
72
72
  // the page time the page hid with a resync out (`suspendReply`).
73
73
  export function makeGate() {
74
- return { armed: false, since: 0, serverAt: null, shownAt: null, dropped: false, lostAt: null, backAt: null, asked: false, askedAt: null, replyExpired: false, hiddenAt: null };
74
+ return { armed: false, since: 0, serverAt: null, shownAt: null, dropped: false, lostAt: null, backAt: null, asked: false, askedAt: null, replyExpired: false, hiddenAt: null, pausedAt: null };
75
75
  }
76
76
 
77
77
  // Arm the gate for an away that began at page time `since`, when the server's
@@ -92,6 +92,7 @@ export function arm(gate, since, serverAt) {
92
92
  gate.askedAt = null;
93
93
  gate.replyExpired = false;
94
94
  gate.hiddenAt = null;
95
+ gate.pausedAt = null;
95
96
  return true;
96
97
  }
97
98
 
@@ -106,6 +107,7 @@ export function clear(gate) {
106
107
  gate.askedAt = null;
107
108
  gate.replyExpired = false;
108
109
  gate.hiddenAt = null;
110
+ gate.pausedAt = null;
109
111
  }
110
112
 
111
113
  // Whether to ask for a resync now, at page time `now`: once per away, an away
@@ -202,6 +204,15 @@ export function current(gate, msg) {
202
204
  return msg.t >= expected - Math.max(LAG_MS, away * LAG_SHARE);
203
205
  }
204
206
 
207
+ // A gate whose visible wait must not count an away (the report wait after a
208
+ // reconnect) is paused at page time `at`, when the page hid or its frames
209
+ // stopped; the next visible `waited` moves its start on by the time away.
210
+ export function pauseWait(gate, at) {
211
+ if (gate.armed && gate.pausedAt === null) {
212
+ gate.pausedAt = at;
213
+ }
214
+ }
215
+
205
216
  // Note one frame while armed. `visible` is whether the page is shown. Returns
206
217
  // true when the gate has waited `RESUME_WAIT_MS` of visible time and should
207
218
  // give up.
@@ -209,6 +220,12 @@ export function waited(gate, now, visible) {
209
220
  if (!gate.armed || !visible) {
210
221
  return false;
211
222
  }
223
+ if (gate.pausedAt !== null) {
224
+ if (gate.shownAt !== null) {
225
+ gate.shownAt += Math.max(0, now - gate.pausedAt);
226
+ }
227
+ gate.pausedAt = null;
228
+ }
212
229
  gate.shownAt ??= now;
213
230
  return now - gate.shownAt > RESUME_WAIT_MS;
214
231
  }
@@ -227,6 +227,9 @@ class MultiplayerSystem {
227
227
  this.resume = ResumeGate.makeGate();
228
228
  // How long to wait for a resync reply before forcing recovery; 0 turns it off.
229
229
  this.resyncReplyMs = ResumeGate.RESYNC_REPLY_MS;
230
+ // A reconnect can retain joined and the old local pose. It must not
231
+ // report that pose as acknowledgement of this connection's placement.
232
+ this.reportPlacement = ResumeGate.makeGate();
230
233
  this.frameAt = 0;
231
234
  this.wasAway = false;
232
235
  this.gaveUp = false;
@@ -293,6 +296,7 @@ class MultiplayerSystem {
293
296
  this.gaveUp = false;
294
297
  } else {
295
298
  this.away(last || now);
299
+ this.waitForPlacement(now);
296
300
  }
297
301
  ResumeGate.noteConnection(this.resume, connected, now);
298
302
  if (gaitModel()) {
@@ -324,6 +328,11 @@ class MultiplayerSystem {
324
328
  this.resumed();
325
329
  this.gaveUp = true;
326
330
  }
331
+ // A WORLD without a self row (including a resync) can release the cover
332
+ // without placing us. Bound the separate report wait by the same timeout.
333
+ if (ResumeGate.waited(this.reportPlacement, now, !pageHidden())) {
334
+ ResumeGate.clear(this.reportPlacement);
335
+ }
327
336
  this.applyGone(scene);
328
337
  this.reportGone(scene);
329
338
 
@@ -343,7 +352,7 @@ class MultiplayerSystem {
343
352
  // Deck code can make a final local adjustment after engine Player behavior
344
353
  // and physics, then optionally replace the kit's standard report.
345
354
  game.beforeReport?.(scene, local, this);
346
- if (!this.joined) {
355
+ if (!this.joined || this.reportPlacement.armed) {
347
356
  // Nothing reported until the session has placed this player.
348
357
  } else if (game.report) {
349
358
  game.report(scene, local, this);
@@ -425,6 +434,7 @@ class MultiplayerSystem {
425
434
  return;
426
435
  }
427
436
  this.net = net;
437
+ if (this.joined) {this.waitForPlacement(performance.now());}
428
438
  this.joinCommitted = true;
429
439
  if (net.status().state === 'connected') { this.joinStage('connected'); }
430
440
  this.joinRetryAt = 0;
@@ -645,6 +655,8 @@ class MultiplayerSystem {
645
655
  // kept behind the cover from now until a current snapshot (`receive`). The
646
656
  // cover goes up at once, because this runs from the page's hidden event.
647
657
  away(since) {
658
+ // The report wait counts visible time only, like the cover's give-up.
659
+ ResumeGate.pauseWait(this.reportPlacement, since);
648
660
  if (!this.net || !this.joined || this.gaveUp || this.net.status().solo || this.joinError) {
649
661
  return;
650
662
  }
@@ -662,11 +674,21 @@ class MultiplayerSystem {
662
674
  reconnected() {
663
675
  const now = performance.now();
664
676
  this.gaveUp = false;
677
+ ResumeGate.clear(this.reportPlacement);
678
+ this.waitForPlacement(now);
665
679
  this.away(this.frameAt || now);
666
680
  ResumeGate.noteConnection(this.resume, false, now);
667
681
  ResumeGate.noteConnection(this.resume, true, now);
668
682
  }
669
683
 
684
+ waitForPlacement(now) {
685
+ if (!this.joined || this.gaveUp || this.net?.status().solo) {return;}
686
+ if (ResumeGate.arm(this.reportPlacement, now, null)) {
687
+ this.placedTo = null;
688
+ this.clampedTo = null;
689
+ }
690
+ }
691
+
670
692
  // A current snapshot arrived after an away. Every displayed pose is
671
693
  // forgotten, so this frame draws each object and player at its current pose
672
694
  // rather than smoothing from the one shown before the away, and each live
@@ -719,6 +741,7 @@ class MultiplayerSystem {
719
741
  // gone, and the join overlay covers the next one.
720
742
  endAway() {
721
743
  ResumeGate.clear(this.resume);
744
+ ResumeGate.clear(this.reportPlacement);
722
745
  this.wasAway = false;
723
746
  this.gaveUp = false;
724
747
  }
@@ -852,7 +875,8 @@ class MultiplayerSystem {
852
875
  for (const [id, x, y, z, facing, clamped] of msg.ps ?? []) {
853
876
  if (id !== selfId) {
854
877
  sample(this.players, msg, id, [x, y, z, facing]);
855
- } else if (msg.k === WORLD && !again) {
878
+ } else if (!again && (msg.k === WORLD || this.reportPlacement.armed) &&
879
+ (!this.reportPlacement.armed || msg.localMs >= this.reportPlacement.since)) {
856
880
  // The WORLD snapshot that starts a session carries where this player
857
881
  // left off. The body is moved there in one step, behind the overlay.
858
882
  this.placedTo = { x, y, z };
@@ -1199,6 +1223,11 @@ class MultiplayerSystem {
1199
1223
  // Without a body yet, the placement waits for one.
1200
1224
  if (this.placedTo && body) {
1201
1225
  body.setTranslation(this.placedTo, true);
1226
+ scene.physics3d.resetInterpolation?.(local);
1227
+ // Physics already synced this frame: reports and hooks must see the
1228
+ // correction too, rather than the Transform from before it.
1229
+ Object.assign(local.components.Transform, this.placedTo);
1230
+ ResumeGate.clear(this.reportPlacement);
1202
1231
  body.setLinvel({ x: 0, y: 0, z: 0 }, true);
1203
1232
  this.placedTo = null;
1204
1233
  this.settleFrames = 1;
@@ -1218,23 +1247,25 @@ class MultiplayerSystem {
1218
1247
  // intermediate positions as valid movement.
1219
1248
  if (Math.hypot(off.x, off.y, off.z) > CLAMP_SNAP) {
1220
1249
  body.setTranslation(to, true);
1250
+ scene.physics3d.resetInterpolation?.(local);
1251
+ Object.assign(local.components.Transform, to);
1221
1252
  body.setLinvel({ x: 0, y: 0, z: 0 }, true);
1222
1253
  return;
1223
1254
  }
1224
1255
 
1225
1256
  // Ease smaller corrections to avoid an abrupt backward change after an
1226
1257
  // ordinary dropped frame or client stall.
1227
- body.setTranslation(
1228
- { x: at.x + off.x * CLAMP_EASE, y: at.y + off.y * CLAMP_EASE, z: at.z + off.z * CLAMP_EASE },
1229
- true,
1230
- );
1258
+ const eased = { x: at.x + off.x * CLAMP_EASE, y: at.y + off.y * CLAMP_EASE, z: at.z + off.z * CLAMP_EASE };
1259
+ body.setTranslation(eased, true);
1260
+ scene.physics3d.resetInterpolation?.(local);
1261
+ Object.assign(local.components.Transform, eased);
1231
1262
  }
1232
1263
 
1233
1264
  // Report the post-physics local Player pose, poses of locally owned objects,
1234
1265
  // and proximity-based ownership requests. Engine Player behavior and local
1235
1266
  // Rapier simulation have already completed for this frame.
1236
1267
  report(scene, local) {
1237
- if (!local) {
1268
+ if (!local || this.reportPlacement.armed) {
1238
1269
  return;
1239
1270
  }
1240
1271
  const now = performance.now();
@@ -1444,6 +1475,9 @@ class MultiplayerSystem {
1444
1475
  // Other players' avatars are the kit's own and are not reported. Nothing is
1445
1476
  // reported before the session has placed this player.
1446
1477
  reportGone(scene) {
1478
+ // Keep the previous set until reporting resumes, so removals during the
1479
+ // wait are reported afterwards rather than lost or sent to an old world.
1480
+ if (this.reportPlacement.armed) {return;}
1447
1481
  const ids = new Set(scene.actors.keys());
1448
1482
  if (this.seen && this.joined) {
1449
1483
  const avatars = new Set(this.avatars.actors.values());
@@ -37,10 +37,22 @@ const stubs = {
37
37
  register(
38
38
  `data:text/javascript,${encodeURIComponent(`
39
39
  import { readFile } from 'node:fs/promises';
40
+ import { existsSync } from 'node:fs';
41
+ import { fileURLToPath } from 'node:url';
40
42
  const stubs = ${JSON.stringify(stubs)};
41
43
  const kits = ${JSON.stringify(kits)};
42
44
  const baseline = ${JSON.stringify(baseline)};
43
45
  export async function resolve(s, c, next) {
46
+ // Exercise the live physics step/writeBack/API with a stationary stand-in
47
+ // Rapier body. Frozen rendering is outside this interpolation regression.
48
+ if (c.parentURL?.endsWith('/physics-3d/systems/physics3d.js')) {
49
+ if (s === '../engine3d/rapier.js') return { url: 'data:text/javascript,' + encodeURIComponent('export const init = async () => {}; export const RigidBodyType = { Dynamic: 0 };'), shortCircuit: true };
50
+ if (s === '../engine3d/frozenphysics.js') return { url: 'data:text/javascript,export class FrozenPhysics {}', shortCircuit: true };
51
+ }
52
+ if (c.parentURL?.endsWith('/real-time/code/client/connection.js')) {
53
+ if (s === 'castle-web-sdk') return { url: 'data:text/javascript,' + encodeURIComponent('export const Multiplayer = { join: async () => globalThis.__rateConnection };'), shortCircuit: true };
54
+ if (s === './joinOverlay.js') return { url: 'data:text/javascript,export const showLoadFailed = () => {};', shortCircuit: true };
55
+ }
44
56
  if (c.parentURL?.endsWith('/systems/multiplayer.js') && stubs[s]) {
45
57
  return { url: 'data:text/javascript,' + encodeURIComponent(stubs[s]), shortCircuit: true };
46
58
  }
@@ -51,6 +63,10 @@ register(
51
63
  if (baseline && c.parentURL === baseline && s.startsWith('../')) {
52
64
  return next(new URL(s, kits + 'multiplayer-3d/code/systems/multiplayer.js').href, c);
53
65
  }
66
+ if (s.startsWith('.') && c.parentURL?.includes('/physics-3d/')) {
67
+ const url = new URL(s, c.parentURL);
68
+ if (existsSync(fileURLToPath(url) + '.js')) return next(url.href + '.js', c);
69
+ }
54
70
  return next(s, c);
55
71
  }
56
72
  export async function load(u, c, next) {
@@ -877,6 +893,216 @@ for (const action of ['close', 'switch']) {
877
893
  frame(room);
878
894
  assert.equal(globalThis.__cover, '(no words)', 'a second return is quiet again');
879
895
  }
896
+ // A resumed transport retains joined, but its old local pose must not count
897
+ // as acknowledgement of a placement this connection has not applied yet.
898
+ const { game: reportHooks } = await import(`data:text/javascript,${encodeURIComponent(stubs['@imports/castle.real-time/code/client/gameHooks.js'])}`);
899
+ for (const event of [true, false]) for (const placement of ['world', 'self row']) {
900
+ const room = await makeRoom({ objects: { crate: [4, 1, 0, 0, 0, 0, 1] } });
901
+ deliver(room, world(room), pageMs);
902
+ run(room, pageMs + 100);
903
+ const local = room.scene.actorWith('Player');
904
+ Object.assign(local.components.Transform, { x: -1, y: 1, z: 12.844 });
905
+ room.scene.physics3d.bodyOf(local).setTranslation(local.components.Transform);
906
+ const reports = [];
907
+ room.system.net.sendMove = pose => { reports.push(pose); return true; };
908
+ let delegated = 0;
909
+ // Same delegation as hub-game's hookLayer.report for a player on foot.
910
+ reportHooks.report = (scene, actor, system) => { delegated++; system.report(scene, actor); };
911
+ try {
912
+ frame(room);
913
+ assert.equal(reports.length, 1, 'an already placed connection reports normally');
914
+ reports.length = 0;
915
+ delegated = 0;
916
+ room.socket = false;
917
+ room.state = 'reconnecting';
918
+ frame(room);
919
+ reconnect(room, { event });
920
+ room.actors.delete('crate');
921
+ frame(room);
922
+ assert.equal(room.system.joined, true, 'joined is retained across reconnect');
923
+ assert.equal(reports.length, 0, 'the old body is not reported on the new connection');
924
+ assert.equal(delegated, 0, 'the hub report override waits too');
925
+ room.system.report(room.scene, local);
926
+ assert.equal(reports.length, 0, 'direct calls through the override cannot bypass the gate');
927
+ assert.ok(!room.outbox.some(msg => msg.k === 'g'), 'gone reports wait with moves');
928
+ deliver(room, world(room, { again: 1 }), pageMs);
929
+ frame(room);
930
+ assert.equal(reports.length, 0, 'a resync WORLD does not place this connection');
931
+ const bodyOf = room.scene.physics3d.bodyOf;
932
+ room.scene.physics3d.bodyOf = () => null;
933
+ const ps = [['self', 0, 1, 9, 0]];
934
+ deliver(room, placement === 'world' ? world(room, { ps }) : { k: 's', t: simNow(), ps }, pageMs);
935
+ frame(room);
936
+ assert.equal(reports.length, 0, 'receipt alone is not enough while the body is missing');
937
+ room.scene.physics3d.bodyOf = bodyOf;
938
+ frame(room);
939
+ assert.equal(reports.length, 1, 'the frame applying placement can report');
940
+ assert.deepEqual(reports[0].slice(0, 3), [0, 1, 9], 'the first report carries the applied placement');
941
+ frame(room);
942
+ assert.ok(room.outbox.some(msg => msg.k === 'g'), 'gone reports resume after placement');
943
+ } finally { delete reportHooks.report; }
944
+ }
945
+ for (const release of ['timeout', 'endAway']) {
946
+ const room = await makeRoom({ objects: {} });
947
+ deliver(room, world(room), pageMs);
948
+ run(room, pageMs + 100);
949
+ const reports = [];
950
+ room.system.net.sendMove = pose => { reports.push(pose); return true; };
951
+ reconnect(room);
952
+ // The cover can release without a placement, but the report wait still
953
+ // has its own copy of the existing visible-time deadline.
954
+ deliver(room, world(room, { again: 1 }), pageMs);
955
+ frame(room);
956
+ assert.equal(reports.length, 0);
957
+ if (release === 'timeout') run(room, pageMs + 10100);
958
+ else { room.system.endAway(); frame(room); }
959
+ assert.ok(reports.length > 0, `${release}: reporting does not wait forever`);
960
+ }
961
+ // The report wait counts visible time only: an away after the wait started
962
+ // (hidden, or frames stopped) does not spend it, so a return cannot report the
963
+ // retained pose before this connection's placement.
964
+ for (const away of ['hidden', 'stall']) {
965
+ const room = await makeRoom({ objects: {} });
966
+ deliver(room, world(room), pageMs);
967
+ run(room, pageMs + 100);
968
+ const reports = [];
969
+ room.system.net.sendMove = pose => { reports.push(pose); return true; };
970
+ reconnect(room);
971
+ deliver(room, world(room, { again: 1 }), pageMs);
972
+ frame(room);
973
+ run(room, pageMs + 2000);
974
+ assert.equal(room.system.reportPlacement.armed, true, `${away}: still waiting for placement`);
975
+ if (away === 'hidden') { hide(room); pageMs += 30000; show(room); }
976
+ else { pageMs += 30000; }
977
+ frame(room);
978
+ assert.equal(room.system.reportPlacement.armed, true, `${away}: time away does not release the report wait`);
979
+ assert.equal(reports.length, 0, `${away}: no report of the retained pose on return`);
980
+ run(room, pageMs + 7000);
981
+ assert.equal(reports.length, 0, `${away}: still held inside the visible wait`);
982
+ run(room, pageMs + 1500);
983
+ assert.ok(reports.length > 0, `${away}: the visible wait still ends`);
984
+ }
985
+ console.log('test-resume-gate: reconnect reports wait for applied placement; WORLD, self row, body delay, hook, timeout, endAway and visible-time wait pass');
986
+
987
+ // Clamp application and reporting share one frame, before physics can sync
988
+ // the Transform again. The hub's report hook delegates to this same report.
989
+ for (const correction of ['placement', 'snap', 'ease', 'placement then ease']) {
990
+ const room = await makeRoom({ objects: {} });
991
+ deliver(room, world(room), pageMs);
992
+ run(room, pageMs + 100);
993
+ const local = room.scene.actorWith('Player');
994
+ const body = room.scene.physics3d.bodyOf(local);
995
+ const before = { x: -1, y: 1, z: 12.656 };
996
+ Object.assign(local.components.Transform, before, { rotationY: 90 });
997
+ body.setTranslation(before, true);
998
+ let expected;
999
+ if (correction === 'placement' || correction === 'placement then ease') {
1000
+ room.system.placedTo = { x: 0, y: 1, z: 9 };
1001
+ expected = { x: 0, y: 1, z: 9 };
1002
+ }
1003
+ if (correction === 'snap') {
1004
+ room.system.clampedTo = { x: 8, y: 2, z: 20 };
1005
+ expected = { x: 8, y: 2, z: 20 };
1006
+ }
1007
+ if (correction === 'ease') {
1008
+ room.system.clampedTo = { x: 0, y: 2, z: 9 };
1009
+ expected = { x: -0.75, y: 1.25, z: 11.742 };
1010
+ }
1011
+ if (correction === 'placement then ease') {
1012
+ room.system.clampedTo = { x: -1, y: 1, z: 12.656 };
1013
+ expected = { x: -0.25, y: 1, z: 9.914 };
1014
+ }
1015
+ const reports = [];
1016
+ room.system.net.sendMove = pose => { reports.push(pose); return true; };
1017
+ frame(room);
1018
+ assert.equal(reports.length, 1, `${correction}: one report in the corrected frame`);
1019
+ assert.deepEqual(reports[0].slice(0, 3), [expected.x, expected.y, expected.z], `${correction}: the report carries the applied pose`);
1020
+ for (const axis of ['x', 'y', 'z']) {
1021
+ assert.ok(Math.abs(local.components.Transform[axis] - expected[axis]) < 1e-9, `${correction}: Transform ${axis} agrees`);
1022
+ assert.ok(Math.abs(body.translation()[axis] - expected[axis]) < 1e-9, `${correction}: body ${axis} agrees`);
1023
+ }
1024
+ assert.equal(local.components.Transform.rotationY, 90, 'corrections preserve facing');
1025
+ assert.equal(reports[0][3], 1.571, 'report retains Transform facing');
1026
+ if (correction.startsWith('placement')) assert.equal(room.system.settleFrames, 1);
1027
+ }
1028
+ console.log('test-resume-gate: same-frame placement, clamp snap and clamp ease reports carry the applied position');
1029
+
1030
+ // A rate-limited correction frame can be followed by several render frames
1031
+ // before physics steps again. Use the LIVE engine's history/writeback and
1032
+ // the real MOVE_HZ transport, rather than making every send succeed.
1033
+ const { Physics3DSystem } = await import('../../physics-3d/systems/physics3d.js');
1034
+ const { connectSession: rateLimitedSession } = await import('../../real-time/code/client/connection.js');
1035
+ const { MOVE_HZ } = await import('../../real-time/code/client/messages.js');
1036
+ const fastFrameMs = 1000 / 240;
1037
+ for (const correction of ['placement', 'snap', 'ease', 'placement then ease']) {
1038
+ const room = await makeRoom({ objects: {} });
1039
+ deliver(room, world(room), pageMs);
1040
+ run(room, pageMs + 100);
1041
+ const local = room.scene.actorWith('Player');
1042
+ const body = room.scene.physics3d.bodyOf(local);
1043
+ const before = { x: 0, y: 1, z: 1 };
1044
+ Object.assign(local.components.Transform, before, { rotationY: 90 });
1045
+ local.components.Body = { lockRotations: true };
1046
+ body.setTranslation(before, true);
1047
+ body.bodyType = () => 0;
1048
+ room.scene.getActors = () => [local];
1049
+ const physics = new Physics3DSystem();
1050
+ physics.attach(room.scene);
1051
+ physics.bodies.set(local.id, { body });
1052
+ let fixedSteps = 0;
1053
+ physics.world = { step: () => fixedSteps++ };
1054
+ physics.eventQueue = { drainCollisionEvents() {} };
1055
+ physics.step(1 / 60);
1056
+ physics.writeBack(room.scene);
1057
+ assert.equal(physics.bodies.get(local.id).prev.z, before.z, 'a fixed step recorded the old pose');
1058
+
1059
+ const packets = [];
1060
+ globalThis.__rateConnection = {
1061
+ playerId: 'self', state: 'connected', isSolo: false,
1062
+ send: packet => packets.push(packet), onMessage() {}, onRoster() {}, onStateChange() {},
1063
+ };
1064
+ const transport = await rateLimitedSession();
1065
+ // The correction narrowly misses a send slot; the next frame gets it,
1066
+ // still before a single new fixed physics step has run.
1067
+ const correctionAt = pageMs;
1068
+ pageMs -= 1000 / MOVE_HZ - fastFrameMs / 2;
1069
+ assert.equal(transport.sendMove([0, 1, 1, 0], [], [], []), true);
1070
+ pageMs = correctionAt;
1071
+ packets.length = 0;
1072
+ room.system.net.sendMove = transport.sendMove;
1073
+ let expected;
1074
+ if (correction === 'placement' || correction === 'placement then ease') {
1075
+ room.system.placedTo = { x: 0, y: 1, z: 0 };
1076
+ expected = [0, 1, 0];
1077
+ }
1078
+ if (correction === 'snap') {
1079
+ room.system.clampedTo = { x: 5, y: 1, z: -5 };
1080
+ expected = [5, 1, -5];
1081
+ }
1082
+ if (correction === 'ease') {
1083
+ room.system.clampedTo = { x: 0, y: 1, z: -2 };
1084
+ expected = [0, 1, 0.25];
1085
+ }
1086
+ if (correction === 'placement then ease') {
1087
+ room.system.clampedTo = { x: 0, y: 1, z: 1 };
1088
+ expected = [0, 1, 0.25];
1089
+ }
1090
+ frame(room);
1091
+ assert.equal(packets.length, 0, `${correction}: the correction frame's report is rate-limited`);
1092
+ for (let i = 1; i <= 16; i++) {
1093
+ pageMs += fastFrameMs;
1094
+ physics.step(fastFrameMs / 1000);
1095
+ physics.writeBack(room.scene);
1096
+ if (i < 4) assert.equal(fixedSteps, 1, 'writeback runs without a new physics step');
1097
+ const t = local.components.Transform;
1098
+ assert.deepEqual([t.x, t.y, t.z], expected, `${correction}: frame ${i} never interpolates from the old pose`);
1099
+ frame(room);
1100
+ if (i === 1) assert.equal(packets.length, 1, 'the next actual send precedes the next physics step');
1101
+ for (const packet of packets) assert.deepEqual(packet.p.slice(0, 3), expected, `${correction}: outgoing reports keep the corrected position`);
1102
+ }
1103
+ assert.ok(packets.length >= 2, 'the rate limiter also sends a later report');
1104
+ }
1105
+ console.log('test-resume-gate: 240 Hz live physics writeback and rate-limited reports keep placement, snap and ease corrections');
880
1106
 
881
1107
  console.table(results);
882
1108
  console.log('test-resume-gate: current snapshots release returns; silent resyncs recover once');
@@ -61,5 +61,5 @@
61
61
  "autoUpdateWhenImported": true,
62
62
  "deckId": "JH0SclbPVP0y",
63
63
  "cardId": "eXfAaUdbSU5A",
64
- "publishedVersion": "2026-11-15T00:45:03.769Z"
64
+ "publishedVersion": "2026-11-18T00:50:50.040Z"
65
65
  }
@@ -6,7 +6,7 @@
6
6
  "restart": "castle-web restart .",
7
7
  "screenshot": "castle-web screenshot .",
8
8
  "test:wall-slide": "node scripts/test-wall-slide.mjs",
9
- "check": "eslint . && jscpd && npm run test:wall-slide && node scripts/test-rapier-gz.mjs && node scripts/test-ground-half.mjs && node scripts/test-memory-profile.mjs && node scripts/test-model-parse-cache.mjs && node scripts/test-sleeping-models.mjs && node scripts/test-static-actors.mjs && node scripts/test-frozen-statics.mjs && node scripts/test-frozen-nested.mjs && node scripts/test-frozen-statics-legacy-physics2d.mjs && node scripts/test-skip-empty-nodes.mjs && node scripts/test-view-range.mjs && node scripts/test-look-bake.mjs && node scripts/test-template-cache.mjs && node scripts/test-template-cache-minified.mjs && node scripts/test-model-cache.mjs && node scripts/test-square-first.mjs && node --input-type=module -e \"const { bundleProject } = await import('castle-web-cli/dist/bundle.js'); await bundleProject('.');\""
9
+ "check": "eslint . && jscpd && npm run test:wall-slide && node scripts/test-coaxial-escape.mjs && node scripts/test-rapier-gz.mjs && node scripts/test-ground-half.mjs && node scripts/test-memory-profile.mjs && node scripts/test-model-parse-cache.mjs && node scripts/test-sleeping-models.mjs && node scripts/test-static-actors.mjs && node scripts/test-frozen-statics.mjs && node scripts/test-frozen-nested.mjs && node scripts/test-frozen-statics-legacy-physics2d.mjs && node scripts/test-skip-empty-nodes.mjs && node scripts/test-view-range.mjs && node scripts/test-look-bake.mjs && node scripts/test-template-cache.mjs && node scripts/test-template-cache-minified.mjs && node scripts/test-model-cache.mjs && node scripts/test-square-first.mjs && node --input-type=module -e \"const { bundleProject } = await import('castle-web-cli/dist/bundle.js'); await bundleProject('.');\""
10
10
  },
11
11
  "jscpd": {
12
12
  "path": [
@@ -0,0 +1,176 @@
1
+ // Two players on exactly one spot (hub-game v1.218, Nov 17 Market check).
2
+ // Real Player + Physics3DSystem + the kit's vendored Rapier WASM, as
3
+ // test-wall-slide.mjs runs them: the local player (the hub player blueprint)
4
+ // and another player's avatar (a kinematic Solid capsule, as multiplayer-3d
5
+ // draws one) standing exactly where the local body stands.
6
+ //
7
+ // 1. Informational: while they stay coaxial the local body is wedged into
8
+ // the ground and cannot walk (the bug the server's step-off now
9
+ // prevents). Logged, not asserted: a physics change that frees a coaxial
10
+ // body is no failure.
11
+ // 2. The gap before the step-off reaches the joiner's client: its body sits
12
+ // under the other avatar for N frames, then the session's placement
13
+ // arrives, either in one step (multiplayer-3d `placedTo`) or as clamped
14
+ // rows eased a quarter of the way each (`clampedTo` under CLAMP_SNAP).
15
+ // After it the body walks at full pace.
16
+ // 3. The other side of the same gap: the first player stands still while
17
+ // the joiner's avatar is drawn on them, then slides to the stepped-off
18
+ // spot. The first player walks at full pace once it has gone.
19
+ //
20
+ // Run from any directory: node kits/physics-3d/scripts/test-coaxial-escape.mjs
21
+ import assert from 'node:assert/strict';
22
+ import { register } from 'node:module';
23
+
24
+ register('data:text/javascript,' + encodeURIComponent(`
25
+ import { existsSync, readFileSync } from 'node:fs';
26
+ import { fileURLToPath } from 'node:url';
27
+ export async function resolve(specifier, context, next) {
28
+ const parent = context.parentURL ?? '';
29
+ if (specifier.startsWith('@imports/castle.physics-2d/')) {
30
+ specifier = parent.replace(/\\/kits\\/.*/, '/kits/physics-2d/') + specifier.slice(27);
31
+ }
32
+ if ((specifier.startsWith('.') || specifier.startsWith('file:')) && parent.includes('/kits/') && !/\\.(m?js|jsx|json)$/.test(specifier)) {
33
+ const base = new URL(specifier, parent).href;
34
+ for (const ext of ['.js', '.jsx']) if (existsSync(fileURLToPath(base + ext))) return next(base + ext, context);
35
+ }
36
+ return next(specifier, context);
37
+ }
38
+ export async function load(url, context, next) {
39
+ if (url.endsWith('.jsx')) {
40
+ return { format: 'module', source: readFileSync(fileURLToPath(url), 'utf8'), shortCircuit: true };
41
+ }
42
+ return next(url, context);
43
+ }
44
+ `));
45
+ const { Player } = await import('../behaviors/Player.jsx');
46
+ const { Physics3DSystem } = await import('../systems/physics3d.js');
47
+
48
+ const DT = 1 / 60;
49
+ const SPAWN = { x: 0, z: 9 };
50
+ // The hub arrival row's step-off for the Town (face 180, spread 1.5).
51
+ const PLACED = { x: -1.5, z: 9 };
52
+ // One clamped row every other frame (a 30 Hz session), eased a quarter.
53
+ const ROW_FRAMES = 2;
54
+ const CLAMP_EASE = 0.25;
55
+ const SPEED = Player.defaultProps.speed;
56
+ const props = { ...Player.defaultProps };
57
+ const tf = (x, y, z) => ({ x, y, z, rotationX: 0, rotationY: 180, rotationZ: 0, scaleX: 1, scaleY: 1, scaleZ: 1 });
58
+ const flat = (a, b) => Math.hypot(a.x - b.x, a.z - b.z);
59
+
60
+ async function makeWorld() {
61
+ const me = { id: 'player', runtime: {}, components: {
62
+ Transform: tf(SPAWN.x, 1, SPAWN.z), Shape: { kind: 'capsule', radius: 0.35, height: 1.4 },
63
+ Body: { type: 'dynamic', lockRotations: true, friction: 0, restitution: 0, gravityScale: 2 }, Solid: {}, Player: { ...props },
64
+ } };
65
+ const system = new Physics3DSystem();
66
+ const scene = {
67
+ time: 0, keys: new Set(), persistent: { camAngle: Math.PI / 4 },
68
+ data: { ground: {}, engine: {} }, actors: [me], maxFps: 0, three: null, cameraControl: 'orbit',
69
+ getActors: () => scene.actors, getActor: (id) => scene.actors.find((a) => a.id === id),
70
+ actorsWith: () => [], forEachBehavior: () => {},
71
+ };
72
+ system.attach(scene);
73
+ const api = scene.physics3d;
74
+ for (let i = 0; i < 200 && !api.ready(); i += 1) {
75
+ await new Promise((resolve) => setTimeout(resolve, 5));
76
+ system.afterBehaviors(scene, DT);
77
+ }
78
+ assert.ok(api.ready(), 'real Rapier initialized');
79
+ const body = () => system.bodies.get(me.id).body;
80
+ const frame = (walking) => {
81
+ scene.time += DT;
82
+ scene.keys = new Set(walking ? ['KeyW'] : []);
83
+ new Player(props).update(me, scene, DT);
84
+ system.afterBehaviors(scene, DT);
85
+ return { ...body().translation() };
86
+ };
87
+ let standing;
88
+ for (let i = 0; i < 180; i += 1) standing = frame(false);
89
+ // Body.defaultProps filled in, as the engine does for a blueprint's Body.
90
+ const avatar = { id: 'avatar', runtime: {}, components: {
91
+ Transform: tf(SPAWN.x, standing.y, SPAWN.z), Shape: { kind: 'capsule', radius: 0.35, height: 1.4 },
92
+ Body: { type: 'kinematic', friction: 0.6, restitution: 0, gravityScale: 0, lockRotations: true }, Solid: {},
93
+ } };
94
+ scene.actors.push(avatar);
95
+ // multiplayer-3d acceptClamp: a placement in one step, or an eased row.
96
+ const put = (to) => {
97
+ body().setTranslation(to, true);
98
+ Object.assign(me.components.Transform, to);
99
+ };
100
+ const place = (to) => { put(to); body().setLinvel({ x: 0, y: 0, z: 0 }, true); };
101
+ const ease = (to) => {
102
+ const at = body().translation();
103
+ put({ x: at.x + (to.x - at.x) * CLAMP_EASE, y: at.y + (to.y - at.y) * CLAMP_EASE, z: at.z + (to.z - at.z) * CLAMP_EASE });
104
+ };
105
+ return { me, avatar, standing, frame, place, ease, body, close: () => system.dispose(scene) };
106
+ }
107
+
108
+ // Walk for a second; the distance covered over its last half.
109
+ function walkPace(w) {
110
+ let mid;
111
+ for (let i = 0; i < 60; i += 1) {
112
+ const p = w.frame(true);
113
+ if (i === 29) mid = p;
114
+ }
115
+ return flat(w.body().translation(), mid) / 0.5;
116
+ }
117
+
118
+ // 1. Coaxial and staying so: wedged.
119
+ {
120
+ const w = await makeWorld();
121
+ for (let i = 0; i < 30; i += 1) w.frame(false);
122
+ const from = w.body().translation();
123
+ for (let i = 0; i < 120; i += 1) w.frame(true);
124
+ const moved = flat(w.body().translation(), from);
125
+ const sunk = w.standing.y - w.body().translation().y;
126
+ w.close();
127
+ console.log(`coaxial (informational): walked ${moved.toFixed(3)} m in 2 s, sunk ${sunk.toFixed(3)} m into the ground`);
128
+ }
129
+
130
+ // 2. The joiner: N frames under the avatar (walking or not), then the step-off.
131
+ const rows = [];
132
+ for (const how of ['place', 'ease']) {
133
+ for (const frames of [1, 6, 30, 120]) {
134
+ for (const walking of [false, true]) {
135
+ const w = await makeWorld();
136
+ for (let i = 0; i < frames; i += 1) w.frame(walking);
137
+ const target = { x: PLACED.x, y: w.standing.y, z: PLACED.z };
138
+ if (how === 'place') {
139
+ w.place(target);
140
+ w.frame(false);
141
+ } else {
142
+ // Rows keep coming until the body is near the spot (the server's
143
+ // settle ends at 0.25 m); the walk is held off meanwhile.
144
+ for (let i = 0; i < 120 && flat(w.body().translation(), target) > 0.25; i += 1) {
145
+ if (i % ROW_FRAMES === 0) w.ease(target);
146
+ w.frame(false);
147
+ }
148
+ }
149
+ const off = flat(w.body().translation(), target);
150
+ const y = w.body().translation().y;
151
+ const pace = walkPace(w);
152
+ w.close();
153
+ rows.push({ how, frames, walking, off: +off.toFixed(3), y: +y.toFixed(3), pace: +pace.toFixed(2) });
154
+ assert.ok(pace > SPEED * 0.9, `${how} after ${frames} frames (walking ${walking}): walks at ${pace} m/s`);
155
+ assert.ok(Math.abs(y - w.standing.y) < 0.05, `${how} after ${frames} frames: standing height ${y}`);
156
+ }
157
+ }
158
+ }
159
+ for (const row of rows) console.log(JSON.stringify(row));
160
+
161
+ // 3. The first player: the joiner's avatar drawn on them, then sliding away.
162
+ for (const frames of [6, 60]) {
163
+ const w = await makeWorld();
164
+ for (let i = 0; i < frames; i += 1) w.frame(false);
165
+ const t = w.avatar.components.Transform;
166
+ for (let i = 0; i < 20; i += 1) {
167
+ t.x += (PLACED.x - t.x) * 0.25;
168
+ w.frame(false);
169
+ }
170
+ const pace = walkPace(w);
171
+ const y = w.body().translation().y;
172
+ w.close();
173
+ console.log(`first player: avatar on them ${frames} frames then slid off; walks ${pace.toFixed(2)} m/s, y ${y.toFixed(3)}`);
174
+ assert.ok(pace > SPEED * 0.9, `first player walks once the avatar slid off (${pace} m/s)`);
175
+ }
176
+ console.log('test-coaxial-escape: free at full pace once the step-off or the avatar arrives');
@@ -838,6 +838,14 @@ function makeApi(system, runtime) {
838
838
  }
839
839
  return bodyOf(actor);
840
840
  },
841
+ // After directly correcting a body's position, discard its pre-correction
842
+ // interpolation pose. Frames without a fixed step then draw the body
843
+ // where it was put; the next fixed step starts fresh history there.
844
+ resetInterpolation: (actor) => {
845
+ runtime.touch?.(actor);
846
+ const entry = system.bodies.get(idOf(actor));
847
+ if (entry) entry.prev = null;
848
+ },
841
849
  mass: (actor) => bodyOf(actor)?.mass() ?? 0,
842
850
  getVelocity: (actor) => {
843
851
  const v = bodyOf(actor)?.linvel();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.240",
3
+ "version": "0.4.242",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"