castle-web-cli 0.4.230 → 0.4.232

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 (92) hide show
  1. package/dist/castle-host/host.js +81 -0
  2. package/dist/devSaveStorage.d.ts +36 -0
  3. package/dist/devSaveStorage.js +469 -0
  4. package/dist/devSessionChild.js +22 -12
  5. package/dist/devSessionServer.js +8 -2
  6. package/dist/devSessionStorage.d.ts +9 -0
  7. package/dist/devSessionStorage.js +66 -1
  8. package/dist/init.js +1 -1
  9. package/dist/serve.js +5 -1
  10. package/dist/serverBundle.js +5 -3
  11. package/kits/base/castle.json +1 -1
  12. package/kits/base/sdk/README.md +148 -1
  13. package/kits/base/sdk/castle.d.ts +4 -0
  14. package/kits/base/sdk/castle.js +2 -0
  15. package/kits/base/sdk/commands.d.ts +15 -0
  16. package/kits/base/sdk/multiplayer.js +52 -4
  17. package/kits/base/sdk/save.d.ts +197 -0
  18. package/kits/base/sdk/save.js +525 -0
  19. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  20. package/kits/base/sdk/saveCoordinator.js +252 -0
  21. package/kits/base/sdk/server/storage.d.ts +3 -2
  22. package/kits/base/sdk/server/storage.js +25 -5
  23. package/kits/base/sdk/server/wrapper.d.ts +4 -0
  24. package/kits/base/sdk/server/wrapper.js +2 -0
  25. package/kits/base/sdk/store.d.ts +3 -2
  26. package/kits/base/sdk/store.js +5 -0
  27. package/kits/hub-game/CLAUDE.md +29 -4
  28. package/kits/hub-game/code/client/avatar.js +39 -0
  29. package/kits/hub-game/code/client/chat.js +12 -0
  30. package/kits/hub-game/code/client/chrome.js +237 -13
  31. package/kits/hub-game/code/client/grab.js +166 -7
  32. package/kits/hub-game/code/client/hats.js +26 -0
  33. package/kits/hub-game/code/client/hookLayer.js +36 -3
  34. package/kits/hub-game/code/client/hudClear.js +126 -0
  35. package/kits/hub-game/code/client/state.js +35 -1
  36. package/kits/hub-game/code/client/talk.js +10 -36
  37. package/kits/hub-game/code/client/tiers.js +505 -0
  38. package/kits/hub-game/code/client/together.js +144 -4
  39. package/kits/hub-game/code/client/wear.js +96 -14
  40. package/kits/hub-game/code/server/actors.js +5 -0
  41. package/kits/hub-game/code/server/grab.js +299 -13
  42. package/kits/hub-game/code/server/hub.js +162 -7
  43. package/kits/hub-game/code/server/manifest.js +80 -8
  44. package/kits/hub-game/code/server/npcs.js +21 -33
  45. package/kits/hub-game/code/server/party.js +75 -6
  46. package/kits/hub-game/code/server/say.js +8 -2
  47. package/kits/hub-game/code/server/wear.js +116 -11
  48. package/kits/hub-game/code/systems/hub.js +386 -21
  49. package/kits/hub-game/docs/contract.md +285 -19
  50. package/kits/hub-game/package.json +1 -1
  51. package/kits/hub-game/scripts/test-chat.mjs +32 -0
  52. package/kits/hub-game/scripts/test-grab-client.mjs +511 -0
  53. package/kits/hub-game/scripts/test-grab.mjs +857 -3
  54. package/kits/hub-game/scripts/test-hats.mjs +229 -0
  55. package/kits/hub-game/scripts/test-hub-trip.mjs +721 -0
  56. package/kits/hub-game/scripts/test-hud-clear.mjs +676 -0
  57. package/kits/hub-game/scripts/test-manifest.mjs +122 -1
  58. package/kits/hub-game/scripts/test-npcs.mjs +34 -24
  59. package/kits/hub-game/scripts/test-party.mjs +108 -4
  60. package/kits/hub-game/scripts/test-say.mjs +59 -2
  61. package/kits/hub-game/scripts/test-tiers.mjs +854 -0
  62. package/kits/hub-game/scripts/test-together.mjs +33 -1
  63. package/kits/hub-game/scripts/test-try-on.mjs +940 -0
  64. package/kits/physics-2d/CLAUDE.md +2 -0
  65. package/kits/physics-2d/castle.json +2 -2
  66. package/kits/physics-2d/engine/scene.js +127 -0
  67. package/kits/physics-2d/package.json +1 -1
  68. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +298 -0
  69. package/kits/physics-3d/CLAUDE.md +531 -0
  70. package/kits/physics-3d/behaviors/Player.jsx +437 -3
  71. package/kits/physics-3d/castle.json +3 -3
  72. package/kits/physics-3d/docs/pxmodel-format.md +4 -0
  73. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -1
  74. package/kits/physics-3d/engine3d/actornode.js +253 -0
  75. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  76. package/kits/physics-3d/engine3d/optimize.js +49 -0
  77. package/kits/physics-3d/engine3d/orbitinput.js +277 -0
  78. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  79. package/kits/physics-3d/engine3d/world3d.js +525 -11
  80. package/kits/physics-3d/package.json +1 -1
  81. package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
  82. package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
  83. package/kits/physics-3d/scripts/test-camera-follow.mjs +543 -0
  84. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2105 -0
  85. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
  86. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  87. package/kits/physics-3d/scripts/test-static-actors.mjs +667 -0
  88. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  89. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  90. package/kits/physics-3d/scripts/test-steady-hover.mjs +633 -0
  91. package/kits/physics-3d/systems/physics3d.js +273 -9
  92. package/package.json +1 -1
@@ -0,0 +1,854 @@
1
+ // Tests over device tiers (code/client/tiers.js): where a device starts (its
2
+ // GPU, its memory, a slow visit remembered for a week), the frame-time judge
3
+ // (median windows, never back up, hidden pages and swaps ignored), storage that
4
+ // throws, the player's own Auto / Low / High winning, and the low picture's
5
+ // levers put on and taken off exactly on a fake physics-3d world (with the
6
+ // scene file's `"tier": "keep"` mark: an actor drawn on every tier). Last, the hub
7
+ // system with the deck's `hub.tiers` absent: nothing of the tiers is made, run
8
+ // or read. `npm run check` runs this.
9
+
10
+ import assert from 'node:assert/strict';
11
+ import fs from 'node:fs';
12
+ import { register } from 'node:module';
13
+ import {
14
+ CHECK_EVERY_MS,
15
+ FIRST_WINDOW_MS,
16
+ KEEP,
17
+ MODE_KEY,
18
+ REMEMBER_MS,
19
+ TIER_KEY,
20
+ WINDOW_MS,
21
+ classify,
22
+ hintedTier,
23
+ initialTier,
24
+ makeJudge,
25
+ makeLevers,
26
+ makeTiers,
27
+ median,
28
+ readMode,
29
+ weakGpu,
30
+ } from '../code/client/tiers.js';
31
+
32
+ let n = 0;
33
+ function test(name, fn) {
34
+ try {
35
+ fn();
36
+ } catch (err) {
37
+ console.error(`not ok: ${name}`);
38
+ throw err;
39
+ }
40
+ n += 1;
41
+ }
42
+
43
+ function memoryStorage(init = {}) {
44
+ const map = new Map(Object.entries(init));
45
+ return {
46
+ map,
47
+ getItem: (k) => (map.has(k) ? map.get(k) : null),
48
+ setItem: (k, v) => map.set(k, String(v)),
49
+ };
50
+ }
51
+ const throwing = {
52
+ getItem() {
53
+ throw new Error('SecurityError');
54
+ },
55
+ setItem() {
56
+ throw new Error('QuotaExceededError');
57
+ },
58
+ };
59
+
60
+ // Frames of `ms` each from `t` for `seconds`; returns what the judge said and
61
+ // the time after.
62
+ function run(judge, t, ms, seconds, counts = true) {
63
+ const said = [];
64
+ for (const end = t + seconds * 1000; t < end; t += ms) {
65
+ const v = judge.feed(ms, t, counts);
66
+ if (v) {
67
+ said.push(v);
68
+ }
69
+ }
70
+ return { said, t };
71
+ }
72
+
73
+ test('weak GPUs by renderer string', () => {
74
+ for (const gpu of [
75
+ 'PowerVR Rogue GE8320',
76
+ 'PowerVR Rogue GE8100',
77
+ 'Mali-G52 MC2',
78
+ 'Mali-G52 MC1',
79
+ 'Mali-G51',
80
+ 'Mali-T720',
81
+ 'Mali-T830 MP2',
82
+ 'Adreno (TM) 306',
83
+ 'Adreno (TM) 418',
84
+ 'Adreno (TM) 506',
85
+ 'ANGLE (Qualcomm, Adreno (TM) 505, OpenGL ES 3.2)',
86
+ ]) {
87
+ assert.equal(weakGpu(gpu), true, gpu);
88
+ }
89
+ for (const gpu of ['Mali-G52 MC4', 'Mali-G57 MC2', 'Mali-G610', 'Adreno (TM) 610', 'Adreno (TM) 730', 'Apple GPU', 'PowerVR Rogue GM9446', null, undefined, 42]) {
90
+ assert.equal(weakGpu(gpu), false, String(gpu));
91
+ }
92
+ });
93
+
94
+ test('hints: a weak GPU or 2 GB is low, anything else high', () => {
95
+ assert.deepEqual(hintedTier({ gpu: 'Mali-G52 MC2', deviceMemory: 4 }), { tier: 'low', reason: 'gpu' });
96
+ assert.deepEqual(hintedTier({ gpu: 'Adreno (TM) 640', deviceMemory: 2 }), { tier: 'low', reason: 'memory' });
97
+ assert.deepEqual(hintedTier({ gpu: 'Adreno (TM) 640', deviceMemory: 1 }), { tier: 'low', reason: 'memory' });
98
+ assert.deepEqual(hintedTier({ gpu: 'Adreno (TM) 640', deviceMemory: 4 }), { tier: 'high', reason: 'auto' });
99
+ assert.deepEqual(hintedTier({}), { tier: 'high', reason: 'auto' });
100
+ });
101
+
102
+ test('a slow visit is remembered for a week, then tried from high again', () => {
103
+ const now = 1_000_000_000_000;
104
+ const at = (ago) => memoryStorage({ [TIER_KEY]: JSON.stringify({ tier: 'low', at: now - ago }) });
105
+ assert.deepEqual(initialTier({ storage: at(1000), now }), { tier: 'low', reason: 'remembered' });
106
+ assert.deepEqual(initialTier({ storage: at(REMEMBER_MS - 1), now }), { tier: 'low', reason: 'remembered' });
107
+ assert.deepEqual(initialTier({ storage: at(REMEMBER_MS + 1), now }), { tier: 'high', reason: 'auto' });
108
+ assert.deepEqual(initialTier({ storage: at(-60000), now }), { tier: 'high', reason: 'auto' }, 'a time from the future is not trusted');
109
+ const junk = memoryStorage({ [TIER_KEY]: '{not json' });
110
+ assert.deepEqual(initialTier({ storage: junk, now }), { tier: 'high', reason: 'auto' });
111
+ assert.deepEqual(initialTier({ storage: at(REMEMBER_MS + 1), now, gpu: 'Mali-G51' }), { tier: 'low', reason: 'gpu' });
112
+ });
113
+
114
+ test('storage that throws reads as nothing stored and never throws', () => {
115
+ assert.equal(readMode(throwing), 'auto');
116
+ assert.deepEqual(initialTier({ storage: throwing, now: 1 }), { tier: 'high', reason: 'auto' });
117
+ assert.equal(readMode(null), 'auto');
118
+ const t = makeTiers({ storage: throwing, clock: () => 5, deviceMemory: 8 });
119
+ assert.equal(t.set('low'), true);
120
+ assert.equal(t.handle.current, 'low');
121
+ assert.equal(readMode(memoryStorage({ [MODE_KEY]: '"sideways"' })), 'auto');
122
+ });
123
+
124
+ test('median', () => {
125
+ assert.equal(median([]), 0);
126
+ assert.equal(median([3, 1, 2]), 2);
127
+ assert.equal(median([4, 1, 2, 3]), 2.5);
128
+ });
129
+
130
+ test('the judge: a slow first window is low; a fast device never is', () => {
131
+ let j = makeJudge();
132
+ let r = run(j, 0, 60, FIRST_WINDOW_MS / 1000 + 0.2);
133
+ assert.deepEqual(r.said, ['low'], 'median 60 ms over the first 5 s');
134
+ j = makeJudge();
135
+ r = run(j, 0, 16, 120);
136
+ assert.deepEqual(r.said, [], 'two minutes at 60 fps');
137
+ j = makeJudge();
138
+ r = run(j, 0, 35, 120);
139
+ assert.deepEqual(r.said, [], '35 ms frames are not slow');
140
+ });
141
+
142
+ test('the judge: big single frames do not decide (median, not mean)', () => {
143
+ const j = makeJudge();
144
+ let said = null;
145
+ for (let t = 0, i = 0; t < 60000; i += 1) {
146
+ const ms = i % 10 === 0 ? 900 : 16;
147
+ t += ms;
148
+ said = j.feed(ms, t, true) ?? said;
149
+ }
150
+ assert.equal(said, null);
151
+ });
152
+
153
+ test('the judge: after the first window, any slow 10 s window is low', () => {
154
+ const j = makeJudge();
155
+ let r = run(j, 0, 16, 30);
156
+ assert.deepEqual(r.said, []);
157
+ // Six slow seconds inside a mostly fast window are not enough.
158
+ r = run(j, r.t, 60, 6);
159
+ r = run(j, r.t, 16, 30);
160
+ assert.deepEqual(r.said, []);
161
+ r = run(j, r.t, 60, WINDOW_MS / 1000 * 2 + 0.5);
162
+ assert.deepEqual(r.said, ['low']);
163
+ });
164
+
165
+ test('the judge never moves back up, and says low once', () => {
166
+ const j = makeJudge();
167
+ let r = run(j, 0, 70, 6);
168
+ assert.deepEqual(r.said, ['low']);
169
+ r = run(j, r.t, 70, 30);
170
+ assert.deepEqual(r.said, [], 'said once');
171
+ r = run(j, r.t, 10, 60);
172
+ assert.deepEqual(r.said, []);
173
+ assert.equal(j.done, true);
174
+ });
175
+
176
+ test('the judge ignores frames that do not count, and gaps', () => {
177
+ let j = makeJudge();
178
+ // Slow frames under a swap (counts false) say nothing.
179
+ let r = run(j, 0, 80, 30, false);
180
+ assert.deepEqual(r.said, []);
181
+ // A slow stretch broken by a swap before 5 s: both halves start over.
182
+ j = makeJudge();
183
+ r = run(j, 0, 60, 4);
184
+ r = run(j, r.t, 60, 0.5, false);
185
+ r = run(j, r.t, 60, 4);
186
+ assert.deepEqual(r.said, []);
187
+ // A gap (the page hidden: no frames) splits a window as well.
188
+ j = makeJudge();
189
+ r = run(j, 0, 60, 4);
190
+ j.feed(30000, r.t + 30000, true);
191
+ r = run(j, r.t + 30000, 60, 4);
192
+ assert.deepEqual(r.said, []);
193
+ });
194
+
195
+ test('makeTiers: the judge drops a slow device to low and remembers it', () => {
196
+ const storage = memoryStorage();
197
+ const t = makeTiers({ storage, clock: () => 1234, deviceMemory: 8, levers: fakeLevers() });
198
+ const scene = { three: { renderer: {} } };
199
+ for (let now = 0; now < 7000; now += 60) {
200
+ t.frame(scene, true, now);
201
+ }
202
+ assert.equal(t.handle.current, 'low');
203
+ assert.equal(t.handle.reason, 'slow');
204
+ assert.deepEqual(JSON.parse(storage.map.get(TIER_KEY)), { tier: 'low', at: 1234 });
205
+ // A later visit starts low.
206
+ const again = makeTiers({ storage, clock: () => 1234 + 60000, deviceMemory: 8, levers: fakeLevers() });
207
+ again.frame(scene, true, 0);
208
+ assert.deepEqual([again.handle.current, again.handle.reason], ['low', 'remembered']);
209
+ });
210
+
211
+ test('makeTiers: a hidden page and frames that do not count are not judged', () => {
212
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 8, levers: fakeLevers() });
213
+ const scene = { three: { renderer: {} } };
214
+ for (let now = 0; now < 30000; now += 60) {
215
+ t.frame(scene, false, now);
216
+ }
217
+ assert.equal(t.handle.current, 'high');
218
+ globalThis.document = { hidden: true };
219
+ try {
220
+ for (let now = 30000; now < 60000; now += 60) {
221
+ t.frame(scene, true, now);
222
+ }
223
+ } finally {
224
+ delete globalThis.document;
225
+ }
226
+ assert.equal(t.handle.current, 'high');
227
+ });
228
+
229
+ test('makeTiers: the GPU string from the renderer places a weak phone low', () => {
230
+ const gl = {
231
+ RENDERER: 1,
232
+ getExtension: (name) => (name === 'WEBGL_debug_renderer_info' ? { UNMASKED_RENDERER_WEBGL: 2 } : null),
233
+ getParameter: (p) => (p === 2 ? 'Mali-G52 MC2' : 'WebKit WebGL'),
234
+ };
235
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 4, levers: fakeLevers() });
236
+ t.frame({ three: { renderer: { getContext: () => gl } } }, true, 0);
237
+ assert.deepEqual([t.handle.current, t.handle.reason], ['low', 'gpu']);
238
+ const broken = makeTiers({ storage: memoryStorage(), deviceMemory: 4, levers: fakeLevers() });
239
+ broken.frame({ three: { renderer: { getContext: () => { throw new Error('lost'); } } } }, true, 0);
240
+ assert.equal(broken.handle.current, 'high');
241
+ });
242
+
243
+ test('makeTiers: Low or High picked by hand wins over auto, and is kept', () => {
244
+ const now = 10 * REMEMBER_MS;
245
+ const storage = memoryStorage({ [TIER_KEY]: JSON.stringify({ tier: 'low', at: now - 1000 }), [MODE_KEY]: '"high"' });
246
+ const levers = fakeLevers();
247
+ const t = makeTiers({ storage, clock: () => now, deviceMemory: 8, levers });
248
+ const scene = { three: { renderer: {} } };
249
+ t.frame(scene, true, 0);
250
+ assert.deepEqual([t.handle.current, t.handle.reason, t.handle.mode], ['high', 'manual', 'high']);
251
+ assert.equal(levers.applied, 0);
252
+ // Slow frames do not move a player's High.
253
+ for (let ms = 0; ms < 30000; ms += 80) {
254
+ t.frame(scene, true, ms);
255
+ }
256
+ assert.equal(t.handle.current, 'high');
257
+ t.handle.set('auto');
258
+ assert.equal(storage.map.get(MODE_KEY), '"auto"');
259
+ t.frame(scene, true, 30100);
260
+ assert.deepEqual([t.handle.current, t.handle.reason], ['low', 'remembered']);
261
+ assert.equal(levers.applied, 1);
262
+ t.handle.set('high');
263
+ t.frame(scene, true, 30200);
264
+ assert.equal(levers.restored, 1, 'High takes the low picture off');
265
+ assert.equal(t.handle.set('ultra'), false);
266
+ assert.equal(t.handle.mode, 'high');
267
+ // A fresh page reads the pick back.
268
+ assert.equal(makeTiers({ storage, levers: fakeLevers() }).handle.mode, 'high');
269
+ });
270
+
271
+ function fakeLevers() {
272
+ const lv = { active: false, hidden: 0, applied: 0, restored: 0 };
273
+ lv.apply = () => {
274
+ lv.active = true;
275
+ lv.applied += 1;
276
+ };
277
+ lv.restore = () => {
278
+ lv.active = false;
279
+ lv.restored += 1;
280
+ };
281
+ return lv;
282
+ }
283
+
284
+ test('classify', () => {
285
+ assert.equal(classify({ Transform: {}, Model: {} }), 'decor');
286
+ assert.equal(classify({ Transform: {}, Shape: {} }), 'decor');
287
+ assert.equal(classify({ Transform: {} }), 'decor');
288
+ assert.equal(classify({ Transform: {}, Shape: {}, Solid: {} }), 'static');
289
+ assert.equal(classify({ Transform: {}, Model: {}, Lookable: {}, Shape: {}, Solid: {} }), 'static');
290
+ assert.equal(classify({ Transform: {}, Shape: {}, Solid: {}, Body: {}, HubNpc: {}, Model: {} }), 'npc');
291
+ for (const extra of ['HubDoor', 'HubPad', 'HubSeat', 'TownSign', 'TownStatue', 'Body', 'Ball', 'Player', 'Spinner']) {
292
+ assert.equal(classify({ Transform: {}, Shape: {}, [extra]: {} }), 'game', extra);
293
+ }
294
+ });
295
+
296
+ // A fake physics-3d world: nodes that can be taken out of and put back into
297
+ // the scene, a sun and a renderer that remember what was set.
298
+ class Obj {
299
+ constructor(name, at = [0, 0, 0]) {
300
+ this.name = name;
301
+ this.parent = null;
302
+ this.children = [];
303
+ this.position = { x: at[0], y: at[1], z: at[2] };
304
+ }
305
+ add(o) {
306
+ o.parent?.remove(o);
307
+ o.parent = this;
308
+ this.children.push(o);
309
+ return this;
310
+ }
311
+ remove(o) {
312
+ const i = this.children.indexOf(o);
313
+ if (i >= 0) {
314
+ this.children.splice(i, 1);
315
+ o.parent = null;
316
+ }
317
+ return this;
318
+ }
319
+ }
320
+
321
+ function fakeWorld(actors) {
322
+ const root = new Obj('scene');
323
+ const sun = Object.assign(new Obj('sun'), { isLight: true, castShadow: true });
324
+ const sky = Object.assign(new Obj('sky'), { isLight: true, castShadow: false });
325
+ root.add(sun);
326
+ root.add(sky);
327
+ // The renderer and composer record every property read of theirs: Low
328
+ // never touches either (the GPU hint's getContext is read once, by
329
+ // makeTiers, never by the levers).
330
+ const touched = [];
331
+ const watched = (name) =>
332
+ new Proxy(
333
+ {},
334
+ {
335
+ get(_, key) {
336
+ touched.push(`${name}.${String(key)}`);
337
+ return undefined;
338
+ },
339
+ set(_, key) {
340
+ touched.push(`${name}.${String(key)}=`);
341
+ return true;
342
+ },
343
+ },
344
+ );
345
+ const world = {
346
+ scene: root,
347
+ camera: { position: { x: 0, y: 2, z: 0 } },
348
+ renderer: watched('renderer'),
349
+ composer: watched('composer'),
350
+ nodes: new Map(),
351
+ scenePath: 'scenes/main.scene',
352
+ };
353
+ for (const a of actors) {
354
+ const node = new Obj(a.id, a.at ?? [0, 0, 0]);
355
+ root.add(node);
356
+ world.nodes.set(a.id, { node });
357
+ }
358
+ const byId = new Map(actors.map((a) => [a.id, a]));
359
+ const scene = {
360
+ content: null,
361
+ data: {},
362
+ scenePath: 'scenes/main.scene',
363
+ // The scene file: an actor's id and, where it has one, its `tier` mark.
364
+ readFromFile: () => ({ actors: actors.filter((a) => !a.spawned).map((a) => ('tier' in a ? { id: a.id, tier: a.tier } : { id: a.id })) }),
365
+ getActor: (id) => byId.get(id),
366
+ };
367
+ return { world, scene, sun, sky, touched, parents: () => new Map([...world.nodes].map(([id, e]) => [id, e.node.parent])) };
368
+ }
369
+
370
+ const TOWN = [
371
+ { id: 'lamp', components: { Transform: {}, Model: {} }, at: [3, 0, 3] },
372
+ { id: 'wall-near', components: { Transform: {}, Shape: {}, Solid: {} }, at: [10, 0, 0] },
373
+ { id: 'wall-far', components: { Transform: {}, Shape: {}, Solid: {} }, at: [60, 0, 0] },
374
+ { id: 'npc-near', components: { Transform: {}, Body: {}, HubNpc: {}, Model: {} }, at: [0, 0, 15] },
375
+ { id: 'npc-far', components: { Transform: {}, Body: {}, HubNpc: {}, Model: {} }, at: [0, 0, 25] },
376
+ { id: 'door', components: { Transform: {}, Shape: {}, HubDoor: {} }, at: [80, 0, 0] },
377
+ { id: 'pad', components: { Transform: {}, Shape: {}, HubPad: {} }, at: [0, 0, 1] },
378
+ // What a player wears, spawned at runtime: Transform + Shape, never hidden.
379
+ { id: 'wear:p1:0', components: { Transform: {}, Shape: {} }, at: [1, 0, 1], spawned: true },
380
+ ];
381
+ const bounds = (r) => () => ({ dx: 0, dy: 0, dz: 0, r });
382
+ const drawn = (world, id) => world.nodes.get(id).node.parent === world.scene;
383
+
384
+ test('levers: low takes out decor, far scenery and far NPCs, keeps gameplay and spawned actors', () => {
385
+ const { world, scene, sun, sky, touched } = fakeWorld(TOWN);
386
+ const lv = makeLevers({ boundsOf: bounds(0) });
387
+ lv.apply(world, scene, 0);
388
+ assert.equal(drawn(world, 'lamp'), false);
389
+ assert.equal(drawn(world, 'wall-near'), true);
390
+ assert.equal(drawn(world, 'wall-far'), false);
391
+ assert.equal(drawn(world, 'npc-near'), true);
392
+ assert.equal(drawn(world, 'npc-far'), false);
393
+ assert.equal(drawn(world, 'door'), true, 'a door is drawn at any distance');
394
+ assert.equal(drawn(world, 'pad'), true);
395
+ assert.equal(drawn(world, 'wear:p1:0'), true, 'a spawned actor is never hidden');
396
+ assert.equal(lv.hidden, 3);
397
+ assert.equal(sun.castShadow, false);
398
+ assert.equal(sky.castShadow, false);
399
+ assert.deepEqual(touched, [], 'the renderer and composer are not touched');
400
+ });
401
+
402
+ test('levers: a big building is drawn while any of it is within 30 m', () => {
403
+ const { world, scene } = fakeWorld(TOWN);
404
+ makeLevers({ boundsOf: bounds(35) }).apply(world, scene, 0);
405
+ assert.equal(drawn(world, 'wall-far'), true);
406
+ });
407
+
408
+ test('levers: distances are looked at again at a low rate, not every frame', () => {
409
+ const { world, scene } = fakeWorld(TOWN);
410
+ const lv = makeLevers({ boundsOf: bounds(0) });
411
+ lv.apply(world, scene, 0);
412
+ assert.equal(drawn(world, 'wall-far'), false);
413
+ world.camera.position = { x: 55, y: 2, z: 0 };
414
+ lv.apply(world, scene, CHECK_EVERY_MS / 2);
415
+ assert.equal(drawn(world, 'wall-far'), false, 'not before the next look');
416
+ lv.apply(world, scene, CHECK_EVERY_MS + 1);
417
+ assert.equal(drawn(world, 'wall-far'), true, 'walked up to it');
418
+ assert.equal(drawn(world, 'wall-near'), false, 'and away from the other one');
419
+ });
420
+
421
+ test('levers: what the engine puts back (a parked scene returning, a rebuild) is taken out again at once', () => {
422
+ const { world, scene } = fakeWorld(TOWN);
423
+ const lv = makeLevers({ boundsOf: bounds(0) });
424
+ lv.apply(world, scene, 0);
425
+ // world3d.js swapSceneNodes: the town parked (out of the scene, a new
426
+ // nodes map), then put back (every node added to the scene again).
427
+ const parked = world.nodes;
428
+ for (const e of parked.values()) {
429
+ world.scene.remove(e.node);
430
+ }
431
+ world.nodes = new Map();
432
+ world.scenePath = 'pack:scenes/race.scene';
433
+ lv.apply(world, scene, 10);
434
+ world.nodes = parked;
435
+ world.scenePath = 'scenes/main.scene';
436
+ for (const e of parked.values()) {
437
+ world.scene.add(e.node);
438
+ }
439
+ assert.equal(drawn(world, 'lamp'), true);
440
+ lv.apply(world, scene, 20);
441
+ assert.equal(drawn(world, 'lamp'), false, 'not waiting for the next look');
442
+ assert.equal(drawn(world, 'npc-far'), false);
443
+ // A new decor node built by the engine (an actor added) is caught too.
444
+ const node = new Obj('vase', [2, 0, 2]);
445
+ world.scene.add(node);
446
+ world.nodes.set('vase', { node });
447
+ scene.getActor = ((get) => (id) => (id === 'vase' ? { components: { Transform: {}, Model: {} } } : get(id)))(scene.getActor);
448
+ scene.data = {};
449
+ scene.readFromFile = () => ({ actors: [...TOWN.filter((a) => !a.spawned), { id: 'vase' }] });
450
+ lv.apply(world, scene, 30);
451
+ assert.equal(node.parent, null);
452
+ });
453
+
454
+ test('levers: another deck behind a door keeps only the shadow lever', () => {
455
+ const { world, scene, sun } = fakeWorld(TOWN);
456
+ const lv = makeLevers({ boundsOf: bounds(0) });
457
+ lv.apply(world, scene, 0);
458
+ assert.equal(drawn(world, 'lamp'), false);
459
+ lv.apply(world, scene, 10, { actors: false });
460
+ assert.equal(drawn(world, 'lamp'), true);
461
+ assert.equal(drawn(world, 'wall-far'), true);
462
+ assert.equal(sun.castShadow, false);
463
+ });
464
+
465
+ test('levers: high again restores node parents and lights exactly', () => {
466
+ const { world, scene, sun, sky, touched, parents } = fakeWorld(TOWN);
467
+ // One node under something other than the scene root.
468
+ const holder = new Obj('holder');
469
+ world.scene.add(holder);
470
+ holder.add(world.nodes.get('lamp').node);
471
+ const before = parents();
472
+ const order = world.scene.children.length;
473
+ const lv = makeLevers({ boundsOf: bounds(0) });
474
+ lv.apply(world, scene, 0);
475
+ // A node the engine released while it was out stays out.
476
+ const gone = world.nodes.get('npc-far').node;
477
+ world.nodes.delete('npc-far');
478
+ before.delete('npc-far');
479
+ lv.restore(world);
480
+ assert.deepEqual(parents(), before);
481
+ assert.equal(gone.parent, null);
482
+ assert.equal(world.scene.children.length, order - 1);
483
+ assert.equal(sun.castShadow, true);
484
+ assert.equal(sky.castShadow, false, 'a light that cast no shadow still casts none');
485
+ assert.deepEqual(touched, []);
486
+ assert.equal(lv.active, false);
487
+ assert.equal(lv.hidden, 0);
488
+ // And low again works the same after.
489
+ lv.apply(world, scene, 1000);
490
+ assert.equal(drawn(world, 'wall-far'), false);
491
+ assert.equal(sun.castShadow, false);
492
+ });
493
+
494
+ // Regressions from phones and review.
495
+
496
+ test('Low keeps the full render resolution: the pixel ratio is never read or set, across Low/High switches', () => {
497
+ // Measured on phones, a render scale of 1 bought 2-9% and made Low jagged
498
+ // on 2x screens, so Low leaves the renderer and composer alone. The only
499
+ // read of the renderer is the GPU hint, once.
500
+ const { world, scene, touched } = fakeWorld(TOWN);
501
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 1, levers: makeLevers({ boundsOf: bounds(0) }) });
502
+ const s = { ...scene, three: world };
503
+ let now = 0;
504
+ const frames = () => {
505
+ for (let i = 0; i < 3; i += 1) {
506
+ t.frame(s, true, (now += 16));
507
+ }
508
+ };
509
+ frames();
510
+ assert.equal(t.handle.current, 'low');
511
+ assert.equal(drawn(world, 'lamp'), false, 'Low is on');
512
+ for (let round = 0; round < 3; round += 1) {
513
+ t.handle.set('high');
514
+ frames();
515
+ assert.equal(drawn(world, 'lamp'), true, `High, round ${round + 1}`);
516
+ t.handle.set('low');
517
+ frames();
518
+ assert.equal(drawn(world, 'lamp'), false, `Low, round ${round + 1}`);
519
+ }
520
+ t.handle.set('auto');
521
+ frames();
522
+ t.handle.set('high');
523
+ frames();
524
+ assert.deepEqual(touched, ['renderer.getContext'], 'only the GPU hint, read once');
525
+ });
526
+
527
+ test('levers: a Shape that says solid blocks, so it is scenery, not decor (review P1)', () => {
528
+ assert.equal(classify({ Transform: {}, Shape: { solid: true } }), 'static');
529
+ assert.equal(classify({ Transform: {}, Shape: { solid: true }, Model: {} }), 'static');
530
+ assert.equal(classify({ Transform: {}, Shape: { solid: false } }), 'decor');
531
+ const actors = [
532
+ { id: 'wall', components: { Transform: {}, Shape: { kind: 'box', solid: true } }, at: [4, 0, 0] },
533
+ { id: 'wall-far', components: { Transform: {}, Shape: { kind: 'box', solid: true } }, at: [70, 0, 0] },
534
+ ];
535
+ const { world, scene } = fakeWorld(actors);
536
+ makeLevers({ boundsOf: bounds(0) }).apply(world, scene, 0);
537
+ assert.equal(drawn(world, 'wall'), true, 'a near wall that blocks is drawn');
538
+ assert.equal(drawn(world, 'wall-far'), false, 'far scenery is not');
539
+ });
540
+
541
+ test('the judge forgets half a window when the mode changes or a frame cannot count (review P2)', () => {
542
+ const storage = memoryStorage();
543
+ const t = makeTiers({ storage, clock: () => 1, deviceMemory: 8, levers: fakeLevers() });
544
+ const scene = { three: { renderer: {} } };
545
+ let now = 0;
546
+ const slow = (ms, counts = true) => {
547
+ for (const end = now + ms; now < end; ) {
548
+ now += 60;
549
+ t.frame(scene, counts, now);
550
+ }
551
+ };
552
+ slow(4800);
553
+ t.handle.set('high');
554
+ slow(2000);
555
+ t.handle.set('auto');
556
+ slow(120);
557
+ assert.equal(t.handle.current, 'high', 'slow frames from before High are gone');
558
+ assert.equal(storage.map.has(TIER_KEY), false, 'and nothing is remembered');
559
+ slow(4800);
560
+ slow(120, false);
561
+ slow(120);
562
+ assert.equal(t.handle.current, 'high', 'a frame that cannot count starts the window over');
563
+ slow(5200);
564
+ assert.equal(t.handle.current, 'low', 'a whole slow window still decides');
565
+ });
566
+
567
+ test('levers: a hidden node the engine rebuilds in place is taken out at once (review P2)', () => {
568
+ const { world, scene } = fakeWorld(TOWN);
569
+ const lv = makeLevers({ boundsOf: bounds(0) });
570
+ lv.apply(world, scene, 0);
571
+ assert.equal(drawn(world, 'lamp'), false);
572
+ // world3d.js ensureActorNode: the look changed, the old node released, a
573
+ // new entry in the same map under the same id, same size.
574
+ const node = new Obj('lamp', [3, 0, 3]);
575
+ world.scene.add(node);
576
+ world.nodes.set('lamp', { node });
577
+ lv.apply(world, scene, 10);
578
+ assert.equal(node.parent, null, 'not drawn for the rest of the 500 ms');
579
+ // And a hidden node simply put back is caught the same way.
580
+ world.scene.add(world.nodes.get('npc-far').node);
581
+ lv.apply(world, scene, 20);
582
+ assert.equal(drawn(world, 'npc-far'), false);
583
+ });
584
+
585
+ // `"tier": "keep"` on an actor in the scene file: drawn on every tier.
586
+
587
+ const GROUND = { Transform: {}, Shape: {}, Model: {} };
588
+ const WALL = { Transform: {}, Shape: {}, Solid: {} };
589
+ const NPC = { Transform: {}, Body: {}, HubNpc: {}, Model: {} };
590
+ const MARKED = [
591
+ { id: 'paving', components: GROUND, at: [0, 0, 0], tier: 'keep' },
592
+ { id: 'grass-far', components: GROUND, at: [90, 0, 0], tier: 'keep' },
593
+ { id: 'tower-far', components: WALL, at: [70, 0, 0], tier: 'keep' },
594
+ { id: 'guide-far', components: NPC, at: [0, 0, 40], tier: 'keep' },
595
+ // Unmarked, and marked with something that is no mark: as before.
596
+ { id: 'lamp', components: GROUND, at: [3, 0, 3] },
597
+ { id: 'wall-near', components: WALL, at: [10, 0, 0] },
598
+ { id: 'wall-far', components: WALL, at: [60, 0, 0] },
599
+ { id: 'npc-far', components: NPC, at: [0, 0, 25] },
600
+ { id: 'vase', components: GROUND, at: [2, 0, 2], tier: 'low' },
601
+ { id: 'urn', components: GROUND, at: [2, 0, 4], tier: true },
602
+ { id: 'pot', components: GROUND, at: [2, 0, 6], tier: 'Keep' },
603
+ { id: 'bush', components: GROUND, at: [2, 0, 8], tier: null },
604
+ // A spawned actor is not in the file: never hidden, mark or none.
605
+ { id: 'wear:p1:0', components: GROUND, at: [1, 0, 1], spawned: true },
606
+ ];
607
+
608
+ test('keep: a marked actor is drawn on Low whatever it is; unmarked ones and other values are as before', () => {
609
+ assert.equal(KEEP, 'keep');
610
+ const { world, scene } = fakeWorld(MARKED);
611
+ const lv = makeLevers({ boundsOf: bounds(0) });
612
+ lv.apply(world, scene, 0);
613
+ assert.equal(drawn(world, 'paving'), true, 'marked decor is drawn');
614
+ assert.equal(drawn(world, 'grass-far'), true, 'at any distance');
615
+ assert.equal(drawn(world, 'tower-far'), true, 'marked scenery past 30 m stays');
616
+ assert.equal(drawn(world, 'guide-far'), true, 'a marked NPC body past 20 m stays');
617
+ assert.equal(drawn(world, 'lamp'), false);
618
+ assert.equal(drawn(world, 'wall-near'), true);
619
+ assert.equal(drawn(world, 'wall-far'), false);
620
+ assert.equal(drawn(world, 'npc-far'), false);
621
+ for (const id of ['vase', 'urn', 'pot', 'bush']) {
622
+ assert.equal(drawn(world, id), false, `${id}: only "keep" is the mark`);
623
+ }
624
+ assert.equal(drawn(world, 'wear:p1:0'), true);
625
+ assert.equal(lv.hidden, 7);
626
+ assert.deepEqual([...lv.kept].sort(), ['grass-far', 'guide-far', 'paving', 'tower-far']);
627
+ // The next looks keep them, from wherever the camera stands.
628
+ world.camera.position = { x: -200, y: 2, z: -200 };
629
+ lv.apply(world, scene, CHECK_EVERY_MS + 1);
630
+ for (const id of ['paving', 'grass-far', 'tower-far', 'guide-far']) {
631
+ assert.equal(drawn(world, id), true, id);
632
+ }
633
+ assert.equal(drawn(world, 'wall-near'), false, 'unmarked scenery now far is not');
634
+ });
635
+
636
+ test('keep: High, Low, High leaves every node attached where it was', () => {
637
+ const { world, scene, parents } = fakeWorld(MARKED);
638
+ const before = parents();
639
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 8, levers: makeLevers({ boundsOf: bounds(0) }) });
640
+ const s = { ...scene, three: world };
641
+ let now = 0;
642
+ const frames = () => {
643
+ for (let i = 0; i < 3; i += 1) {
644
+ t.frame(s, true, (now += 16));
645
+ }
646
+ };
647
+ t.handle.set('high');
648
+ frames();
649
+ assert.deepEqual(parents(), before);
650
+ t.handle.set('low');
651
+ frames();
652
+ assert.equal(drawn(world, 'paving'), true);
653
+ assert.equal(drawn(world, 'tower-far'), true);
654
+ assert.equal(drawn(world, 'lamp'), false);
655
+ assert.equal(t.handle.hidden, 7);
656
+ t.handle.set('high');
657
+ frames();
658
+ assert.deepEqual(parents(), before, 'everything attached again');
659
+ assert.equal(t.handle.hidden, 0);
660
+ });
661
+
662
+ test('keep: a scene with no marks keeps no list and reads its file as often as before', () => {
663
+ const { world, scene } = fakeWorld(TOWN);
664
+ let reads = 0;
665
+ scene.readFromFile = ((read) => (path) => {
666
+ reads += 1;
667
+ return read(path);
668
+ })(scene.readFromFile);
669
+ const lv = makeLevers({ boundsOf: bounds(0) });
670
+ lv.apply(world, scene, 0);
671
+ assert.equal(lv.kept, null, 'no set is made');
672
+ assert.equal(lv.hidden, 3, 'what the town hid before');
673
+ for (let i = 1; i <= 5; i += 1) {
674
+ lv.apply(world, scene, i * (CHECK_EVERY_MS + 1));
675
+ }
676
+ assert.equal(reads, 1, 'the file is read once per scene, marks and ids together');
677
+ assert.equal(lv.kept, null);
678
+ // A scene whose file cannot be read hides nothing and keeps no list.
679
+ const broken = fakeWorld(MARKED);
680
+ broken.scene.readFromFile = () => {
681
+ throw new Error('scene file not found');
682
+ };
683
+ const lv2 = makeLevers({ boundsOf: bounds(0) });
684
+ lv2.apply(broken.world, broken.scene, 0);
685
+ assert.equal(lv2.hidden, 0);
686
+ assert.equal(lv2.kept, null);
687
+ });
688
+
689
+ test('keep: the marks follow the scene -- one hidden is put back when marked, another scene has its own, another world none', () => {
690
+ const actors = MARKED.map((a) => ({ ...a }));
691
+ const { world, scene } = fakeWorld(actors);
692
+ let reads = 0;
693
+ scene.readFromFile = ((read) => (path) => {
694
+ reads += 1;
695
+ return read(path);
696
+ })(scene.readFromFile);
697
+ const lv = makeLevers({ boundsOf: bounds(0) });
698
+ lv.apply(world, scene, 0);
699
+ assert.equal(drawn(world, 'lamp'), false);
700
+ assert.equal(drawn(world, 'paving'), true);
701
+ // The scene loaded again (new scene data) with the marks moved: the lamp
702
+ // gains one and is put back, the paving loses its and goes.
703
+ actors.find((a) => a.id === 'lamp').tier = 'keep';
704
+ delete actors.find((a) => a.id === 'paving').tier;
705
+ lv.apply(world, scene, CHECK_EVERY_MS + 1);
706
+ assert.equal(drawn(world, 'lamp'), false, 'the same scene data: the file is not read again');
707
+ assert.equal(reads, 1);
708
+ scene.data = {};
709
+ lv.apply(world, scene, 2 * (CHECK_EVERY_MS + 1));
710
+ assert.equal(reads, 2);
711
+ assert.equal(drawn(world, 'lamp'), true, 'hidden before, marked now: put back');
712
+ assert.equal(drawn(world, 'paving'), false, 'no longer marked: decor again');
713
+ assert.equal(drawn(world, 'tower-far'), true);
714
+ // Another scene with no marks at all: the list is dropped.
715
+ for (const a of actors) {
716
+ delete a.tier;
717
+ }
718
+ scene.data = {};
719
+ world.scenePath = 'scenes/other.scene';
720
+ lv.apply(world, scene, 3 * (CHECK_EVERY_MS + 1));
721
+ assert.equal(lv.kept, null);
722
+ assert.equal(drawn(world, 'lamp'), false);
723
+ assert.equal(drawn(world, 'tower-far'), false);
724
+ assert.equal(drawn(world, 'guide-far'), false);
725
+ // A game through a door (another deck's content) hides nothing either way.
726
+ lv.apply(world, scene, 4 * (CHECK_EVERY_MS + 1), { actors: false });
727
+ assert.equal(lv.hidden, 0);
728
+ // Another world starts with no marks remembered.
729
+ const other = fakeWorld(TOWN);
730
+ lv.kept = new Set(['lamp']);
731
+ lv.apply(other.world, other.scene, 5 * (CHECK_EVERY_MS + 1));
732
+ assert.equal(lv.kept, null);
733
+ assert.equal(drawn(other.world, 'lamp'), false);
734
+ });
735
+
736
+ test('keep: a reload that adds the mark puts the node back on the very next frame, not at the next look (review P2)', () => {
737
+ const actors = MARKED.map((a) => ({ ...a }));
738
+ const { world, scene } = fakeWorld(actors);
739
+ const lv = makeLevers({ boundsOf: bounds(0) });
740
+ lv.apply(world, scene, 0);
741
+ assert.equal(drawn(world, 'lamp'), false);
742
+ assert.equal(drawn(world, 'paving'), true);
743
+ const nodes = world.nodes;
744
+ const size = nodes.size;
745
+ // The same scene loaded again: the same path, the same nodes map and
746
+ // nodes, new scene data, and the file now marks the lamp and not the paving.
747
+ actors.find((a) => a.id === 'lamp').tier = 'keep';
748
+ delete actors.find((a) => a.id === 'paving').tier;
749
+ scene.data = {};
750
+ lv.apply(world, scene, 16);
751
+ assert.equal(world.nodes, nodes);
752
+ assert.equal(world.nodes.size, size);
753
+ assert.equal(drawn(world, 'lamp'), true, 'back 16 ms later, well inside the 500 ms');
754
+ assert.equal(drawn(world, 'paving'), false, 'and the one no longer marked is out');
755
+ // With the scene data unchanged the next frames wait for the look as before.
756
+ let reads = 0;
757
+ scene.readFromFile = ((read) => (path) => {
758
+ reads += 1;
759
+ return read(path);
760
+ })(scene.readFromFile);
761
+ world.camera.position = { x: 60, y: 2, z: 0 };
762
+ lv.apply(world, scene, 32);
763
+ lv.apply(world, scene, 48);
764
+ assert.equal(drawn(world, 'wall-far'), false, 'no look between looks');
765
+ assert.equal(reads, 0);
766
+ lv.apply(world, scene, 16 + CHECK_EVERY_MS + 1);
767
+ assert.equal(drawn(world, 'wall-far'), true);
768
+ });
769
+
770
+ // The hub system with `hub.tiers` absent: never a call into tiers.js, never a
771
+ // storage read, no harness handle. tiers.js is stubbed for hub.js so any call
772
+ // is counted.
773
+ const sdkStub = 'export const Hub = undefined;';
774
+ const packStub = 'export const loadPack = () => Promise.reject(new Error("no")); export const cachedPacks = () => []; export const matchesOwn = () => false; export const resolveDeckDoor = () => Promise.reject(new Error("no"));';
775
+ const mediaStub = 'export const initialMedia = {}; export const playMedia = () => {}; export const stopMedia = () => {};';
776
+ const tiersStub = `
777
+ export function makeTiers() {
778
+ globalThis.__tiersMade = (globalThis.__tiersMade ?? 0) + 1;
779
+ return { mode: 'auto', set() {}, frame() { globalThis.__tiersFrames = (globalThis.__tiersFrames ?? 0) + 1; }, handle: { stub: true } };
780
+ }`;
781
+ const url = (src) => 'data:text/javascript,' + encodeURIComponent(src);
782
+ register(
783
+ url(`
784
+ export async function resolve(specifier, context, next) {
785
+ if (specifier === 'castle-web-sdk') return { url: ${JSON.stringify(url(sdkStub))}, shortCircuit: true };
786
+ if (specifier.startsWith('@imports/castle.physics-2d/engine/')) return { url: ${JSON.stringify(url(mediaStub))}, shortCircuit: true };
787
+ if (specifier === '../client/pack.js') return { url: ${JSON.stringify(url(packStub))}, shortCircuit: true };
788
+ if (specifier === '../client/tiers.js' && context.parentURL?.endsWith('/code/systems/hub.js')) return { url: ${JSON.stringify(url(tiersStub))}, shortCircuit: true };
789
+ return next(specifier, context);
790
+ }`),
791
+ );
792
+ const { installSystem } = await import('../code/systems/hub.js');
793
+ const { deck } = await import('../code/client/state.js');
794
+
795
+ {
796
+ let storageReads = 0;
797
+ Object.defineProperty(globalThis, 'localStorage', {
798
+ configurable: true,
799
+ get() {
800
+ storageReads += 1;
801
+ throw new Error('storage must not be read');
802
+ },
803
+ });
804
+ let system;
805
+ installSystem({ registerSystem: (s) => (system = s) });
806
+ let graphics = 0;
807
+ system.chrome = { setGraphics: () => (graphics += 1) };
808
+ const scene = { three: { renderer: {} }, content: null };
809
+ const mp = { placed: () => true };
810
+ globalThis.__hub = {};
811
+ test('hub.tiers absent: no tiers system is registered, nothing made, run or read', () => {
812
+ assert.equal(deck.tiers, false, 'off unless castle.json says so');
813
+ const late = [];
814
+ system.registerLate({ registerSystem: (s) => late.push(s) });
815
+ assert.equal(late.length, 1, 'only the late system the hub always had');
816
+ assert.equal(globalThis.__tiersMade, undefined);
817
+ assert.equal(globalThis.__tiersFrames, undefined);
818
+ assert.equal(system.tiers, undefined);
819
+ assert.equal(graphics, 0, 'no Graphics row');
820
+ assert.equal(storageReads, 0);
821
+ assert.equal('tier' in globalThis.__hub, false);
822
+ // deviceTier itself is guarded as well.
823
+ system.deviceTier(scene, mp, 0);
824
+ assert.equal(globalThis.__tiersMade, undefined);
825
+ });
826
+ test('hub.tiers true: a system of its own, made once, run each frame, a harness handle', () => {
827
+ deck.tiers = true;
828
+ const late = [];
829
+ system.registerLate({ registerSystem: (s) => late.push(s) });
830
+ assert.equal(late.length, 2);
831
+ late[1].afterBehaviors({ ...scene, multiplayer: mp });
832
+ late[1].afterBehaviors({ ...scene, multiplayer: mp });
833
+ assert.equal(globalThis.__tiersMade, 1);
834
+ assert.equal(globalThis.__tiersFrames, 2);
835
+ assert.equal(graphics, 1);
836
+ assert.deepEqual(globalThis.__hub.tier, { stub: true });
837
+ deck.tiers = false;
838
+ });
839
+ delete globalThis.localStorage;
840
+ }
841
+
842
+ test('hub.js reaches the tiers only through a system registered behind the opt-in', () => {
843
+ const src = fs.readFileSync(new URL('../code/systems/hub.js', import.meta.url), 'utf8');
844
+ assert.equal(src.match(/makeTiers\(/g)?.length, 1);
845
+ assert.equal(src.match(/this\.deviceTier\(/g)?.length, 1);
846
+ assert.match(src, /\n {4}if \(Hub\.deck\.tiers\) \{\n {6}scene\.registerSystem\(\{ afterBehaviors: \(s\) => this\.deviceTier\(/);
847
+ const afterBehaviors = src.slice(src.indexOf(' afterBehaviors(scene) {'), src.indexOf('\n }\n', src.indexOf(' afterBehaviors(scene) {')));
848
+ assert.doesNotMatch(afterBehaviors, /deviceTier|tiers/i, 'the per-frame update is the one it was');
849
+ const body = src.slice(src.indexOf(' deviceTier(scene, mp, now) {'));
850
+ assert.match(body, /^ {2}deviceTier\(scene, mp, now\) \{\n {4}if \(!Hub\.deck\.tiers\) \{\n {6}return;\n {4}\}/);
851
+ assert.equal(src.match(/this\.tiers\b/g)?.length, body.slice(0, body.indexOf('\n }\n')).match(/this\.tiers\b/g)?.length, 'this.tiers only inside deviceTier');
852
+ });
853
+
854
+ console.log(`test-tiers: ${n} passed`);