castle-web-cli 0.4.236 → 0.4.238

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 (218) hide show
  1. package/dist/api.d.ts +2 -0
  2. package/dist/bundle.d.ts +24 -0
  3. package/dist/bundle.js +447 -4
  4. package/dist/bundleLatin1.d.ts +6 -0
  5. package/dist/bundleLatin1.js +333 -0
  6. package/dist/castle-host/host.d.ts +10 -1
  7. package/dist/castle-host/host.js +78 -9
  8. package/dist/castleJson.d.ts +20 -0
  9. package/dist/castleJson.js +40 -0
  10. package/dist/deckExports.d.ts +35 -0
  11. package/dist/deckExports.js +365 -0
  12. package/dist/importCheckHook.d.ts +1 -0
  13. package/dist/importCheckHook.js +1 -1
  14. package/dist/index.js +5 -0
  15. package/dist/init.js +2 -1
  16. package/dist/save-deck.js +18 -13
  17. package/kits/base/castle.json +1 -1
  18. package/kits/base/sdk/README.md +47 -0
  19. package/kits/base/sdk/castle.d.ts +3 -1
  20. package/kits/base/sdk/castle.js +1 -0
  21. package/kits/base/sdk/commands.d.ts +25 -1
  22. package/kits/base/sdk/commands.js +29 -1
  23. package/kits/base/sdk/hub.d.ts +17 -0
  24. package/kits/base/sdk/hub.js +33 -9
  25. package/kits/base/sdk/localCache.d.ts +27 -0
  26. package/kits/base/sdk/localCache.js +115 -0
  27. package/kits/base/sdk/localCacheStore.d.ts +15 -0
  28. package/kits/base/sdk/localCacheStore.js +358 -0
  29. package/kits/base/sdk/transport.d.ts +1 -0
  30. package/kits/base/sdk/transport.js +4 -5
  31. package/kits/hub-game/CLAUDE.md +22 -2
  32. package/kits/hub-game/castle.json +4 -1
  33. package/kits/hub-game/code/client/act.js +66 -91
  34. package/kits/hub-game/code/client/actCore.js +134 -0
  35. package/kits/hub-game/code/client/car.js +35 -0
  36. package/kits/hub-game/code/client/chrome.js +207 -381
  37. package/kits/hub-game/code/client/crowdNames.js +2 -2
  38. package/kits/hub-game/code/client/emoteWheel.js +109 -0
  39. package/kits/hub-game/code/client/hats.js +2 -0
  40. package/kits/hub-game/code/client/hookLayer.js +99 -48
  41. package/kits/hub-game/code/client/hostGo.js +77 -0
  42. package/kits/hub-game/code/client/hubControls.js +125 -0
  43. package/kits/hub-game/code/client/hubEntry.js +187 -0
  44. package/kits/hub-game/code/client/hudSurface.js +148 -0
  45. package/kits/hub-game/code/client/hudTree.js +96 -0
  46. package/kits/hub-game/code/client/idle.js +59 -13
  47. package/kits/hub-game/code/client/invites.js +13 -4
  48. package/kits/hub-game/code/client/menuIcons.js +8 -0
  49. package/kits/hub-game/code/client/noTrips.js +38 -0
  50. package/kits/hub-game/code/client/qualityEntry.js +6 -1
  51. package/kits/hub-game/code/client/rehello.js +3 -1
  52. package/kits/hub-game/code/client/riders.js +26 -0
  53. package/kits/hub-game/code/client/role.js +79 -0
  54. package/kits/hub-game/code/client/safeLayout.js +32 -3
  55. package/kits/hub-game/code/client/sound.js +10 -3
  56. package/kits/hub-game/code/client/soundscape.js +2 -2
  57. package/kits/hub-game/code/client/soundscapeAmbience.js +38 -8
  58. package/kits/hub-game/code/client/soundscapeBaked.js +24 -5
  59. package/kits/hub-game/code/client/soundscapeCues.js +2 -1
  60. package/kits/hub-game/code/client/state.js +19 -0
  61. package/kits/hub-game/code/client/stuck.js +2 -1
  62. package/kits/hub-game/code/client/talkSurface.js +178 -0
  63. package/kits/hub-game/code/client/talkTree.js +238 -0
  64. package/kits/hub-game/code/client/tiers.js +8 -5
  65. package/kits/hub-game/code/client/uiDom.js +600 -0
  66. package/kits/hub-game/code/client/uiTree.js +359 -0
  67. package/kits/hub-game/code/client/vehicle.js +154 -0
  68. package/kits/hub-game/code/client/wear.js +27 -5
  69. package/kits/hub-game/code/client/worldLabels.js +3 -2
  70. package/kits/hub-game/code/client/yours.js +10 -3
  71. package/kits/hub-game/code/server/actors.js +4 -3
  72. package/kits/hub-game/code/server/analytics.js +56 -6
  73. package/kits/hub-game/code/server/decor.js +56 -16
  74. package/kits/hub-game/code/server/hub.js +258 -46
  75. package/kits/hub-game/code/server/idle.js +118 -5
  76. package/kits/hub-game/code/server/manifest.js +46 -4
  77. package/kits/hub-game/code/server/npcs.js +4 -2
  78. package/kits/hub-game/code/server/players.js +3 -0
  79. package/kits/hub-game/code/server/role.js +142 -0
  80. package/kits/hub-game/code/server/standing.js +6 -4
  81. package/kits/hub-game/code/server/vehicle.js +126 -0
  82. package/kits/hub-game/code/shared/car.js +52 -0
  83. package/kits/hub-game/code/shared/deckFlags.js +34 -0
  84. package/kits/hub-game/code/shared/deviceClass.js +39 -0
  85. package/kits/hub-game/code/shared/expression.js +9 -0
  86. package/kits/hub-game/code/systems/hub.js +300 -85
  87. package/kits/hub-game/docs/analytics.md +11 -2
  88. package/kits/hub-game/docs/contract.md +353 -14
  89. package/kits/hub-game/docs/vehicle-preset.md +132 -0
  90. package/kits/hub-game/models/hats/baker-cap.pxmodel +89 -0
  91. package/kits/hub-game/models/hats/chef-toque.pxmodel +60 -0
  92. package/kits/hub-game/models/hats/delivery-cap.pxmodel +105 -0
  93. package/kits/hub-game/models/hats/fire-helmet.pxmodel +87 -0
  94. package/kits/hub-game/models/hats/hard-hat.pxmodel +71 -0
  95. package/kits/hub-game/models/hats/nurse-cap.pxmodel +61 -0
  96. package/kits/hub-game/models/hats/police-cap.pxmodel +105 -0
  97. package/kits/hub-game/models/hats/teacher-beret.pxmodel +52 -0
  98. package/kits/hub-game/models/role/square/top-apron.pxmodel +109 -0
  99. package/kits/hub-game/models/role/square/top-cardigan.pxmodel +141 -0
  100. package/kits/hub-game/models/role/square/top-coat.pxmodel +157 -0
  101. package/kits/hub-game/models/role/square/top-scrubs.pxmodel +93 -0
  102. package/kits/hub-game/models/role/square/top-tabard.pxmodel +109 -0
  103. package/kits/hub-game/models/role/square/top-vest.pxmodel +109 -0
  104. package/kits/hub-game/models/role/tool-bag.pxmodel +75 -0
  105. package/kits/hub-game/models/role/tool-bell.pxmodel +71 -0
  106. package/kits/hub-game/models/role/tool-hose.pxmodel +60 -0
  107. package/kits/hub-game/models/role/tool-parcel.pxmodel +61 -0
  108. package/kits/hub-game/models/role/tool-torch.pxmodel +55 -0
  109. package/kits/hub-game/models/role/tool-tray.pxmodel +75 -0
  110. package/kits/hub-game/models/role/top-apron.pxmodel +70 -0
  111. package/kits/hub-game/models/role/top-cardigan.pxmodel +102 -0
  112. package/kits/hub-game/models/role/top-coat.pxmodel +79 -0
  113. package/kits/hub-game/models/role/top-scrubs.pxmodel +54 -0
  114. package/kits/hub-game/models/role/top-tabard.pxmodel +70 -0
  115. package/kits/hub-game/models/role/top-vest.pxmodel +70 -0
  116. package/kits/hub-game/package-lock.json +1 -1
  117. package/kits/hub-game/package.json +1 -1
  118. package/kits/hub-game/scripts/check.mjs +7 -4
  119. package/kits/hub-game/scripts/fixtures/car-vectors.json +279 -0
  120. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +2 -1
  121. package/kits/hub-game/scripts/fixtures/hud-surface.json +670 -0
  122. package/kits/hub-game/scripts/fixtures/talk-surface.json +3930 -0
  123. package/kits/hub-game/scripts/gen-hats.mjs +46 -2
  124. package/kits/hub-game/scripts/gen-role.mjs +80 -0
  125. package/kits/hub-game/scripts/test-act-core.mjs +167 -0
  126. package/kits/hub-game/scripts/test-actions-client.mjs +34 -0
  127. package/kits/hub-game/scripts/test-actors.mjs +48 -0
  128. package/kits/hub-game/scripts/test-analytics.mjs +99 -5
  129. package/kits/hub-game/scripts/test-apply-deck.mjs +122 -0
  130. package/kits/hub-game/scripts/test-back-visibility.mjs +3 -1
  131. package/kits/hub-game/scripts/test-ballot.mjs +2 -0
  132. package/kits/hub-game/scripts/test-car.mjs +43 -0
  133. package/kits/hub-game/scripts/test-decor-client.mjs +2 -1
  134. package/kits/hub-game/scripts/test-decor.mjs +77 -0
  135. package/kits/hub-game/scripts/test-device-class.mjs +83 -0
  136. package/kits/hub-game/scripts/test-emote-wheel.mjs +374 -0
  137. package/kits/hub-game/scripts/test-hats.mjs +5 -4
  138. package/kits/hub-game/scripts/test-host-go.mjs +265 -0
  139. package/kits/hub-game/scripts/test-hub-controls.mjs +108 -0
  140. package/kits/hub-game/scripts/test-hub-entry.mjs +531 -0
  141. package/kits/hub-game/scripts/test-hub-ops.mjs +75 -0
  142. package/kits/hub-game/scripts/test-hub-trip.mjs +85 -0
  143. package/kits/hub-game/scripts/test-hud-clear.mjs +12 -2
  144. package/kits/hub-game/scripts/test-hud-rate.mjs +6 -2
  145. package/kits/hub-game/scripts/test-hud-surface.mjs +272 -0
  146. package/kits/hub-game/scripts/test-idle.mjs +347 -1
  147. package/kits/hub-game/scripts/test-interest-cells.mjs +8 -1
  148. package/kits/hub-game/scripts/test-invites-client.mjs +42 -1
  149. package/kits/hub-game/scripts/test-manifest.mjs +30 -0
  150. package/kits/hub-game/scripts/test-no-trips.mjs +42 -0
  151. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  152. package/kits/hub-game/scripts/test-quality.mjs +13 -0
  153. package/kits/hub-game/scripts/test-rehello.mjs +258 -3
  154. package/kits/hub-game/scripts/test-resume-pose-server.mjs +203 -0
  155. package/kits/hub-game/scripts/test-resync.mjs +183 -0
  156. package/kits/hub-game/scripts/test-role-client.mjs +421 -0
  157. package/kits/hub-game/scripts/test-role.mjs +350 -0
  158. package/kits/hub-game/scripts/test-safe-layout.mjs +50 -1
  159. package/kits/hub-game/scripts/test-soundscape.mjs +124 -7
  160. package/kits/hub-game/scripts/test-standing.mjs +15 -1
  161. package/kits/hub-game/scripts/test-talk-surface.mjs +296 -0
  162. package/kits/hub-game/scripts/test-tiers.mjs +13 -0
  163. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +96 -0
  164. package/kits/hub-game/scripts/test-ui-tree.mjs +711 -0
  165. package/kits/hub-game/scripts/test-vehicle-client.mjs +159 -0
  166. package/kits/hub-game/scripts/test-vehicle.mjs +135 -0
  167. package/kits/hub-game/scripts/test-yours.mjs +33 -0
  168. package/kits/hub-game/tools/hubScene/export.mjs +613 -0
  169. package/kits/hub-game/tools/hubScene/hubdata.mjs +921 -0
  170. package/kits/hub-game/tools/hubScene/merge-root.mjs +39 -0
  171. package/kits/hub-game/tools/hubScene/nodeworld.mjs +227 -0
  172. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +798 -0
  173. package/kits/hub-game/tools/hubScene/test/fixture.json +637 -0
  174. package/kits/hub-game/tools/hubScene/test/paint-export.mjs +40 -0
  175. package/kits/hub-game/tools/hubScene/test/upload.test.mjs +655 -0
  176. package/kits/hub-game/tools/hubScene/upload.mjs +636 -0
  177. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +291 -0
  178. package/kits/multiplayer-3d/castle.json +4 -4
  179. package/kits/multiplayer-3d/code/client/resumeGate.js +30 -2
  180. package/kits/multiplayer-3d/code/client/steer.js +3 -1
  181. package/kits/multiplayer-3d/code/systems/multiplayer.js +30 -2
  182. package/kits/multiplayer-3d/package-lock.json +1 -1
  183. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +74 -2
  184. package/kits/physics-3d/CLAUDE.md +1 -1
  185. package/kits/physics-3d/behaviors/Player.jsx +37 -27
  186. package/kits/physics-3d/castle.json +2 -2
  187. package/kits/physics-3d/docs/engine-geometry-memory.md +23 -0
  188. package/kits/physics-3d/engine3d/memoryprofile.js +17 -0
  189. package/kits/physics-3d/engine3d/playerRun.js +6 -1
  190. package/kits/physics-3d/engine3d/pxmodel.js +6 -1
  191. package/kits/physics-3d/engine3d/world3d.js +6 -3
  192. package/kits/physics-3d/package.json +1 -1
  193. package/kits/physics-3d/play/behaviors/Player.js +40 -28
  194. package/kits/physics-3d/scripts/test-memory-profile.mjs +237 -0
  195. package/kits/physics-3d/systems/physics3d.js +5 -2
  196. package/kits/real-time/castle.json +2 -2
  197. package/kits/real-time/code/client/messages.js +5 -0
  198. package/kits/real-time/code/server/session.js +28 -1
  199. package/kits/real-time/package-lock.json +1 -1
  200. package/package.json +5 -4
  201. package/vendor/three/LICENSE +21 -0
  202. package/vendor/three/build/three.core.js +58773 -0
  203. package/vendor/three/build/three.module.js +18251 -0
  204. package/vendor/three/examples/jsm/controls/OrbitControls.js +1860 -0
  205. package/vendor/three/examples/jsm/controls/TransformControls.js +1918 -0
  206. package/vendor/three/examples/jsm/exporters/GLTFExporter.js +3595 -0
  207. package/vendor/three/examples/jsm/geometries/RoundedBoxGeometry.js +216 -0
  208. package/vendor/three/examples/jsm/math/MeshSurfaceSampler.js +315 -0
  209. package/vendor/three/examples/jsm/postprocessing/EffectComposer.js +363 -0
  210. package/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  211. package/vendor/three/examples/jsm/postprocessing/OutputPass.js +139 -0
  212. package/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  213. package/vendor/three/examples/jsm/postprocessing/RenderPass.js +183 -0
  214. package/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  215. package/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  216. package/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  217. package/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1435 -0
  218. package/vendor/three/package.json +134 -0
@@ -0,0 +1,183 @@
1
+ // A returning client whose socket stayed up while the host dropped its frames
2
+ // (a backpressured phone in the background) asks for a resync (`k: 'r'`). Only
3
+ // a deck whose hooks offer `resync` answers, with a WORLD marked `again`; the
4
+ // hub layer grants it and replays an arrived player's Act prompts, since a
5
+ // dropped frame may have carried those too. Any other deck is unchanged.
6
+ // `npm run check` runs it; it needs nothing installed.
7
+ import assert from 'node:assert/strict';
8
+ import { register } from 'node:module';
9
+
10
+ const sceneStub = 'export const readScene = () => globalThis.__hubTestActors ?? [];';
11
+ register(
12
+ `data:text/javascript,${encodeURIComponent(`
13
+ const stubs = {
14
+ '@imports/castle.multiplayer-3d/code/server/sceneBodies.js': 'data:text/javascript,${encodeURIComponent(sceneStub)}',
15
+ 'castle-web-sdk': ${JSON.stringify(new URL('./fixtures/sdk-stub.mjs', import.meta.url).href)},
16
+ };
17
+ export async function resolve(specifier, context, next) {
18
+ if (stubs[specifier]) {
19
+ return { url: stubs[specifier], shortCircuit: true };
20
+ }
21
+ if (context.parentURL?.includes('/kits/base/sdk/') && specifier.startsWith('.') && !specifier.endsWith('.js')) return next(specifier + '.js', context);
22
+ return next(specifier, context);
23
+ }
24
+ `)}`,
25
+ );
26
+ const { layer } = await import('../code/server/hub.js');
27
+ const { makeSession } = await import('../../real-time/code/server/session.js');
28
+ const Rehello = await import('../code/client/rehello.js');
29
+
30
+ // The real-time session, with a kinematic NPC the place walks.
31
+ const npc = { at: [2.45, 1, 9.53] };
32
+ const world = {
33
+ async createSimulation() {
34
+ return { players: new Map(), objects: new Map(), timeMs: 0 };
35
+ },
36
+ step(sim) {
37
+ sim.timeMs += 33;
38
+ },
39
+ objectPoses: () => [['greeter', ...npc.at, 0, 0, 0, 1, 0]],
40
+ restorePoses: () => 0,
41
+ };
42
+ const players = {
43
+ addPlayer(sim, id) {
44
+ sim.players.set(id, { at: { x: 0, y: 0, z: 0 } });
45
+ },
46
+ removePlayer(sim, id) {
47
+ sim.players.delete(id);
48
+ },
49
+ setPose() {},
50
+ playerPoses: (sim) => [...sim.players].map(([id, p]) => [id, p.at.x, p.at.y, p.at.z, 0, 0]),
51
+ };
52
+ const ownership = { claim() {}, release() {}, setObjectPoses() {}, sweepOwners() {}, ownerships: () => [] };
53
+ const poses = { PLAYER_GEOMETRY: 4, epsilonAt: () => 0.001 };
54
+
55
+ // Each client's view: a WORLD replaces it, a STATE changes what it names.
56
+ // `dropping` stands for the host throwing away that client's frames.
57
+ async function room(game) {
58
+ const views = new Map(), dropping = new Set(), worlds = [], passed = [];
59
+ const apply = (to, msg) => {
60
+ if (dropping.has(to) || (msg.k !== 'w' && msg.k !== 's')) {return;}
61
+ if (msg.k === 'w') {views.set(to, new Map()); worlds.push({ to, msg });}
62
+ for (const [id, ...pose] of msg.os ?? []) {views.get(to)?.set(id, pose.slice(0, 3));}
63
+ };
64
+ const session = {
65
+ sessionId: 'dev:test',
66
+ players: [{ playerId: 'a', userId: null }, { playerId: 'b', userId: null }],
67
+ hub: null,
68
+ send: (to, msg) => apply(to, msg),
69
+ broadcast: (msg) => session.players.forEach(({ playerId }) => apply(playerId, msg)),
70
+ };
71
+ const server = makeSession({ label: 'test', poses, world, players, ownership,
72
+ game: { persist: false, ...game, message: (s, p, data) => passed.push(data) } });
73
+ server.onTick(session);
74
+ await new Promise((resolve) => setTimeout(resolve, 10));
75
+ const tick = (n = 1) => {for (let i = 0; i < n; i += 1) {server.onTick(session);}};
76
+ tick();
77
+ return { views, dropping, worlds, passed, tick, ask: (id) => server.onMessage(session, { playerId: id }, { k: 'r' }) };
78
+ }
79
+
80
+ // The NPC walks off and stops while only `a`'s frames are dropped.
81
+ async function strand(game) {
82
+ npc.at = [2.45, 1, 9.53];
83
+ const r = await room(game);
84
+ assert.deepEqual(r.views.get('a').get('greeter'), [2.45, 1, 9.53]);
85
+ r.dropping.add('a');
86
+ npc.at = [14, 1, 22];
87
+ r.tick(3);
88
+ r.dropping.delete('a');
89
+ r.tick(3);
90
+ assert.deepEqual(r.views.get('a').get('greeter'), [2.45, 1, 9.53], 'later broadcasts never name a stopped NPC');
91
+ r.worlds.length = 0;
92
+ return r;
93
+ }
94
+
95
+ {
96
+ // An opted-in deck answers the ask with one WORLD, to that client alone.
97
+ const asked = [];
98
+ const r = await strand({ resync: (session, player) => {asked.push(player.playerId); return true;} });
99
+ r.ask('a');
100
+ r.tick();
101
+ assert.deepEqual(asked, ['a']);
102
+ assert.deepEqual(r.worlds.map(({ to, msg }) => [to, msg.again, msg.rs]), [['a', 1, 1]]);
103
+ assert.deepEqual(r.views.get('a').get('greeter'), [14, 1, 22], 'the resync carries where the NPC is now');
104
+ assert.deepEqual(r.passed, [], 'the ask is the session\'s, not the deck\'s');
105
+ r.tick(3);
106
+ assert.equal(r.worlds.length, 1, 'once');
107
+ }
108
+
109
+ {
110
+ // The hook can refuse: no WORLD.
111
+ const r = await strand({ resync: () => false });
112
+ r.ask('a');
113
+ r.tick();
114
+ assert.deepEqual(r.worlds, []);
115
+ }
116
+
117
+ {
118
+ // A deck without the hook: no `rs` on its WORLD, the ask reaches its own
119
+ // message hook as any message always has, and nothing is resent.
120
+ npc.at = [2.45, 1, 9.53];
121
+ const r = await room({});
122
+ assert.ok(r.worlds.length > 0 && r.worlds.every(({ msg }) => msg.rs === undefined && msg.again === undefined));
123
+ r.worlds.length = 0;
124
+ r.ask('a');
125
+ r.tick();
126
+ assert.deepEqual(r.worlds, []);
127
+ assert.deepEqual(r.passed, [{ k: 'r' }]);
128
+ }
129
+
130
+ // The hub layer always grants it (its client waits behind the cover for the
131
+ // WORLD), and replays an arrived player's prompts.
132
+ {
133
+ globalThis.__hubTestActors = [
134
+ { id: 'spawn', components: { Player: {}, Transform: { x: 0, y: 1, z: 0 } } },
135
+ { id: 'rowan', components: { Transform: { x: 1, y: 1, z: 0 }, HubNpc: { name: 'Rowan' } } },
136
+ ];
137
+ const sent = [];
138
+ const session = { sessionId: 'test', players: [{ playerId: 'p1', userId: '101', username: 'Ada', isAnonymous: false }],
139
+ send: (id, msg) => sent.push([id, structuredClone(msg)]), broadcast: (msg) => sent.push(['all', structuredClone(msg)]) };
140
+ const sim = { timeMs: 0, scenePath: 'scenes/main.scene', objects: new Map(), bodies: new Map(),
141
+ players: new Map([['p1', { at: { x: 0, y: 1, z: 0 }, facing: 0, body: { setTranslation() {} } }]]) };
142
+ const server = layer({ server: { maxPlayers: 8 }, hub: { contract: 1, title: 'Town', resumePose: true, act: true } }, {}, {}, () => true);
143
+ assert.equal(typeof server.resync, 'function');
144
+ server.sceneFor(session);
145
+ server.ready(sim);
146
+ const step = (ms = 50) => {sim.timeMs += ms; server.place(sim); server.step(sim, []);};
147
+ const prompts = () => sent.filter(([id, m]) => id === 'p1' && m.k === 'hub-prompts');
148
+ assert.equal(server.resync(session, { playerId: 'p1' }), true);
149
+ assert.deepEqual(prompts(), [], 'no prompts before arrival');
150
+ server.message(session, { playerId: 'p1' }, { k: 'hub-hello', avatar: 0, party: 1 });
151
+ step(2000);
152
+ step(300);
153
+ const before = prompts().length;
154
+ assert.ok(before > 0);
155
+ assert.deepEqual(prompts().at(-1)[1].items.map((i) => i.id), ['rowan']);
156
+ assert.equal(server.resync(session, { playerId: 'p1' }), true);
157
+ assert.equal(prompts().length, before + 1, 'the prompts are replayed');
158
+ assert.deepEqual(prompts().at(-1)[1].items.map((i) => i.id), ['rowan']);
159
+ const after = prompts().length;
160
+ assert.equal(server.resync(session, { playerId: 'nobody' }), true);
161
+ assert.equal(prompts().length, after, 'nothing for a player the place does not have');
162
+ }
163
+
164
+ // The client side: a resync's WORLD re-admits nobody, so no resume hello (and
165
+ // none of the private state it clears and replays) follows it. A WORLD
166
+ // without `again` (a kept body's reconnect) still counts.
167
+ {
168
+ const queue = [];
169
+ const net = { selfId: () => 'p1', drain: () => queue.splice(0) };
170
+ const mp = { joined: false };
171
+ const at = Rehello.mark(mp, net);
172
+ queue.push({ k: 'w', rs: 1 });
173
+ net.drain();
174
+ assert.equal(Rehello.resumed(mp, net, at), null, 'the join\'s own WORLD');
175
+ queue.push({ k: 'w', rs: 1, again: 1 });
176
+ net.drain();
177
+ assert.equal(Rehello.resumed(mp, net, at), null, 'a resync is not a re-admission');
178
+ queue.push({ k: 'w', rs: 1 });
179
+ net.drain();
180
+ assert.equal(Rehello.resumed(mp, net, at), 'world', 'a re-admission still is');
181
+ }
182
+
183
+ console.log('test-resync: ok');
@@ -0,0 +1,421 @@
1
+ // Roles (contract §11, v1.157): state, precedence, fitted drawing and chips.
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import { register } from 'node:module';
5
+
6
+ const hooks = `
7
+ import { readFile } from 'node:fs/promises';
8
+ import { existsSync } from 'node:fs';
9
+ import { fileURLToPath } from 'node:url';
10
+ const SDK = ${JSON.stringify(new URL('./fixtures/sdk-stub.mjs', import.meta.url).href)};
11
+ const KITS = ${JSON.stringify(new URL('../../', import.meta.url).href)};
12
+ export async function resolve(specifier, context, next) {
13
+ if (specifier === '@imports/castle.multiplayer-3d/code/client/avatars.js') return { url: 'data:text/javascript,export function dropMissing() {}', shortCircuit: true };
14
+ if (specifier === 'castle-web-sdk') {
15
+ return { url: SDK, shortCircuit: true };
16
+ }
17
+ for (const kit of ['physics-2d', 'physics-3d']) {
18
+ if (specifier.startsWith('@imports/castle.' + kit + '/')) {
19
+ specifier = KITS + kit + '/' + specifier.slice(('@imports/castle.' + kit + '/').length);
20
+ }
21
+ }
22
+ const parent = context.parentURL ?? '';
23
+ if ((specifier.startsWith('.') || specifier.startsWith('file:')) && parent.includes('/kits/') && !/\\.(m?js|jsx|json)$/.test(specifier)) {
24
+ const base = new URL(specifier, parent).href;
25
+ for (const ext of ['.js', '.jsx']) if (existsSync(fileURLToPath(base + ext))) return next(base + ext, context);
26
+ }
27
+ return next(specifier, context);
28
+ }
29
+ export async function load(url, context, next) {
30
+ if (url.endsWith('/code/client/hookLayer.js')) return { format: 'module', source: (await readFile(fileURLToPath(url), 'utf8')).replaceAll('import.meta.glob(', '(() => ({}))('), shortCircuit: true };
31
+ return next(url, context);
32
+ }`;
33
+ register(`data:text/javascript,${encodeURIComponent(hooks)}`);
34
+
35
+ const THREE = await import('three');
36
+ const Avatar = await import('../code/client/avatar.js');
37
+ const Role = await import('../code/client/role.js');
38
+ const State = await import('../code/client/state.js');
39
+ const hooksLayer = (await import('../code/client/hookLayer.js')).default;
40
+ const { makeWear, makeEarned, makeRole } = await import('../code/client/wear.js');
41
+ const { buildModelNode, parseModel, visibleBounds } = await import('../../physics-3d/engine3d/pxmodel.js');
42
+ const Gen = await import('./gen-role.mjs');
43
+ const Hats = await import('./gen-hats.mjs');
44
+ const { makeChrome } = await import('../code/client/chrome.js');
45
+ const { fakeDom } = await import('./fixtures/fake-dom.mjs');
46
+ const { crowdNamesFor, layoutCrowdNames, makeCrowdNames, readableSpriteBox, spriteBox } = await import('../code/client/crowdNames.js');
47
+ const { placeLabels } = await import('../code/client/padOccupancy.js');
48
+ const police = { id: 'police', label: 'Police', color: '#22335a', hat: 'police-cap', top: 'vest', tool: 'torch' };
49
+ const doctor = { id: 'doctor', label: 'Doctor', color: '#42a6c0', hat: 'nurse-cap', top: 'scrubs', tool: 'bag' };
50
+ let n = 0;
51
+ function test(name, fn) { fn(); n += 1; console.log(`ok: ${name}`); }
52
+ const read = (file) => fs.readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
53
+
54
+ function sceneOf() {
55
+ const local = { id: 'me-body', components: { Transform: { x: 0, y: 1, z: 0 } } };
56
+ const other = { id: 'body-p2', components: { Transform: { x: 2, y: 1, z: 0 } } };
57
+ const nodes = new Map([local, other].map(({ id }) => [id, { node: new THREE.Group() }]));
58
+ const files = {};
59
+ for (const [kind, ids] of [['top', Role.ROLE_TOPS], ['tool', Role.ROLE_TOOLS]]) {
60
+ for (const id of ids) {
61
+ for (const square of kind === 'top' ? [false, true] : [false]) {
62
+ const file = Role.roleFile(kind, id, square); files[`imports/castle.hub-game/${file}`] = read(file);
63
+ }
64
+ }
65
+ }
66
+ for (const file of ['models/hats/cap.pxmodel', 'models/hats/police-cap.pxmodel', 'models/earned/belt-plain.pxmodel', 'models/earned/sash-plain.pxmodel', 'models/earned/held-lantern.pxmodel', 'models/earned/pin-round.pxmodel']) {
67
+ files[`imports/castle.hub-game/${file}`] = read(file);
68
+ }
69
+ return { local, files, three: { nodes }, multiplayer: { net: { selfId: () => 'me' }, avatars: { actors: new Map([['p2', other.id]]) } }, getActor: (id) => id === local.id ? local : id === other.id ? other : null };
70
+ }
71
+
72
+ test('effective role overlays shared, clears on snapshot and travel, private block survives snapshot', () => {
73
+ State.clear(); const scene = {};
74
+ hooksLayer.state(scene, { hubRole: { me: police, p2: police } });
75
+ State.hub.roleMe.set('me', null);
76
+ assert.deepEqual(State.rolesNow().get('me'), police, 'nullish private value falls back to shared');
77
+ hooksLayer.message(scene, { k: 'hub-role', hubRole: { p2: doctor } });
78
+ assert.deepEqual(State.hub.roles.get('p2'), doctor);
79
+ hooksLayer.state(scene, { hubPlace: {} });
80
+ assert.equal(State.hub.roleAll.size, 0); assert.deepEqual(State.hub.roles.get('p2'), doctor);
81
+ hooksLayer.message(scene, { k: 'hub-role', hubRole: {} }); assert.equal(State.hub.roles.size, 0);
82
+ hooksLayer.state(scene, { hubRole: { me: police } });
83
+ hooksLayer.state(scene, { hubRole: {} }); assert.equal(State.hub.roles.size, 0);
84
+ hooksLayer.message(scene, { k: 'hub-role', hubRole: { me: doctor } }); State.clear();
85
+ assert.equal(State.hub.roleAll.size + State.hub.roleMe.size + State.hub.roles.size, 0);
86
+ });
87
+
88
+ test('role hat > try-on > owned Look; no role hat preserves Look; earned conflicts only', () => {
89
+ State.clear();
90
+ const owned = { kind: 'halo', color: '#ffffff', rarity: 0 }, tried = { kind: 'hat-cap', color: '#ffaaaa', rarity: 0 };
91
+ State.hub.wearAll.set('me', owned); State.hub.tryAll.set('me', tried);
92
+ const roles = new Map([['me', police]]);
93
+ assert.equal(Role.roleWearing(State.wearingNow(), roles).get('me').kind, 'hat-police-cap');
94
+ roles.set('me', { ...police, hat: undefined }); assert.deepEqual(Role.roleWearing(State.wearingNow(), roles).get('me'), tried);
95
+ State.hub.tryAll.clear(); assert.deepEqual(Role.roleWearing(State.wearingNow(), roles).get('me'), owned);
96
+ for (const cls of ['belt', 'sash', 'held', 'badge', 'pin']) {
97
+ const earned = new Map([['me', { class: cls }], ['p2', { class: cls }]]);
98
+ roles.set('me', police);
99
+ assert.equal(Role.roleEarned(earned, roles).has('me'), ['badge', 'pin'].includes(cls));
100
+ assert.equal(Role.roleEarned(earned, roles).has('p2'), true);
101
+ roles.set('me', { id: 'resident', label: 'Resident', color: '#abcdef' });
102
+ assert.equal(Role.roleEarned(earned, roles).has('me'), true);
103
+ }
104
+ });
105
+
106
+ test('generated role models and role hats fit triangle/draw-call budgets, MAIN tint preserves trims', () => {
107
+ const files = [];
108
+ for (const [kind, ids] of [['top', Role.ROLE_TOPS], ['tool', Role.ROLE_TOOLS]]) {
109
+ for (const id of ids) {
110
+ for (const square of kind === 'top' ? [false, true] : [false]) {
111
+ files.push([Role.roleFile(kind, id, square), Gen.roleModel(kind, id, square)]);
112
+ }
113
+ }
114
+ }
115
+ for (const id of ['police-cap', 'nurse-cap', 'fire-helmet', 'chef-toque', 'delivery-cap', 'teacher-beret', 'hard-hat', 'baker-cap']) {
116
+ files.push([`models/hats/${id}.pxmodel`, Hats.hatModel(id)]);
117
+ }
118
+ for (const [file, generated] of files) {
119
+ const text = read(file); assert.equal(text, `${JSON.stringify(generated, null, 1)}\n`);
120
+ const model = parseModel(text); assert.ok(model.look.outline > 0);
121
+ const root = buildModelNode(model, null, { [file]: text }, file, [file], { optimize: true });
122
+ let triangles = 0, calls = 0;
123
+ root.traverse((o) => {
124
+ if (!o.isMesh) { return; }
125
+ calls += Array.isArray(o.material) ? o.geometry.groups.length || o.material.length : 1;
126
+ if (!o.userData.lookOutline) { triangles += (o.geometry.index?.count ?? o.geometry.attributes.position.count) / 3; }
127
+ });
128
+ assert.ok(triangles <= 900, `${file}: ${triangles} triangles`);
129
+ assert.ok(calls <= 4, `${file}: ${calls} draw calls`);
130
+ if (file.includes('/role/')) {
131
+ assert.ok(model.parts.some((p) => p.color === Role.ROLE_MAIN));
132
+ const tinted = JSON.parse(text.split(`"${Role.ROLE_MAIN}"`).join('"#abcdef"'));
133
+ assert.ok(tinted.parts.some((p) => p.color === '#abcdef'));
134
+ model.parts.forEach((p, i) => { if (p.color !== Role.ROLE_MAIN) { assert.equal(tinted.parts[i].color, p.color); } });
135
+ }
136
+ }
137
+ });
138
+
139
+ test('every top/tool fits every drawn avatar and set at waist/hand, square bodies get square tops', () => {
140
+ for (const style of Avatar.STYLES) {
141
+ for (let i = 0; i < Avatar.AVATARS; i += 1) {
142
+ const f = Avatar.earnedFit(i, style);
143
+ for (const kind of ['top', 'tool']) {
144
+ for (const id of kind === 'top' ? Role.ROLE_TOPS : Role.ROLE_TOOLS) {
145
+ const look = Role.roleLook({ class: kind, shape: id, color: '#ABCDEF' }, f);
146
+ assert.equal(look.color, '#abcdef');
147
+ if (kind === 'tool') { assert.deepEqual(look.position, [f.hand[0], Math.round((f.hand[1] - 0.7) * 1000) / 1000, f.hand[2]]); }
148
+ else {
149
+ assert.equal(look.file.includes('/square/'), f.square === true);
150
+ const file = look.file, text = read(file);
151
+ const root = buildModelNode(parseModel(text), null, { [file]: text }, file, [file], { optimize: true });
152
+ root.scale.set(...look.scale); root.position.set(...look.position); root.updateMatrixWorld(true);
153
+ const box = visibleBounds(root);
154
+ assert.ok(box.max.y <= f.chest[1] - 0.7 + 0.001, `${style}/${i} ${id}: below chest`);
155
+ assert.ok(box.max.x >= f.waist[1] && box.max.z >= f.waist[2], `${style}/${i} ${id}: wraps torso`);
156
+ }
157
+ }
158
+ }
159
+ }
160
+ }
161
+ });
162
+
163
+ test('role pieces attach to local and remote avatar nodes, refit, hide and dispose like earned items', () => {
164
+ const scene = sceneOf(), mine = scene.three.nodes.get('me-body').node, theirs = scene.three.nodes.get('body-p2').node;
165
+ const renderer = makeRole(), roles = new Map([['me', police], ['p2', doctor]]), fit = Avatar.earnedFit(1, 'toon');
166
+ renderer.frame(scene, scene.local, roles, () => fit);
167
+ assert.deepEqual(mine.children.map((c) => c.name), ['role:top-vest', 'role:tool-torch']);
168
+ assert.deepEqual(theirs.children.map((c) => c.name), ['role:top-scrubs', 'role:tool-bag']);
169
+ assert.ok(mine.children[0].userData.hatKey.includes('"#22335a"'));
170
+ const first = mine.children[0]; renderer.frame(scene, scene.local, roles, () => fit); assert.equal(mine.children[0], first);
171
+ renderer.frame(scene, scene.local, roles, () => Avatar.earnedFit(1, 'blocky'));
172
+ assert.ok(mine.children[0].userData.hatKey.includes('/square/top-vest.pxmodel'));
173
+ const replacement = new THREE.Group(); scene.three.nodes.set('me-body', { node: replacement });
174
+ renderer.frame(scene, scene.local, roles, () => fit); assert.equal(replacement.children.length, 2);
175
+ let freed = 0; replacement.traverse((o) => o.geometry?.addEventListener('dispose', () => { freed += 1; }));
176
+ roles.clear(); renderer.frame(scene, scene.local, roles, () => fit);
177
+ assert.equal(replacement.children.length + theirs.children.length, 0); assert.ok(freed > 0);
178
+ renderer.frame(new Proxy({}, { get() { throw new Error('unused'); } }), null, roles);
179
+ renderer.clear(); renderer.forget();
180
+ });
181
+
182
+ test('system uses drawn-avatar fit and masks the live earned renderer, restoring pieces when role clears', () => {
183
+ const source = fs.readFileSync(new URL('../code/systems/hub.js', import.meta.url), 'utf8');
184
+ const method = source.slice(source.indexOf(' applyWear(scene, local) {') + 2, source.indexOf(" // The place's tuning", source.indexOf(' applyWear(scene, local) {')));
185
+ const Hub = { hub: State.hub };
186
+ const apply = new Function('Hub', 'Avatar', 'AvatarCap', 'roleWearing', 'roleEarned', `return ({${method}}).applyWear`)(Hub, { ...Avatar, style: () => 'toon', current: () => 1 }, { shown: () => 2 }, Role.roleWearing, Role.roleEarned);
187
+ const scene = sceneOf(); const draw = { wear: makeWear(), earned: makeEarned(), roles: makeRole() };
188
+ for (const [cls, shape] of [['belt', 'belt-plain'], ['sash', 'sash-plain'], ['held', 'held-lantern'], ['pin', 'pin-round']]) {
189
+ State.clear(); State.hub.earned.set('me', { class: cls, shape, color: '#abcdef' }); State.hub.roles.set('me', police);
190
+ apply.call(draw, scene, scene.local);
191
+ assert.equal(scene.three.nodes.get('me-body').node.children.some((c) => c.name === `earned:${shape}`), cls === 'pin');
192
+ State.hub.roles.clear(); apply.call(draw, scene, scene.local);
193
+ assert.ok(scene.three.nodes.get('me-body').node.children.some((c) => c.name === `earned:${shape}`));
194
+ }
195
+ draw.wear.clear(); draw.earned.clear(); draw.roles.clear();
196
+ });
197
+
198
+ test('chips sit below name baseline on local and remote bodies and disappear with missing or hidden avatars', () => {
199
+ const scene = sceneOf(), roles = new Map([['me', police], ['p2', doctor], ['absent', police]]);
200
+ const projected = [];
201
+ const project = (cam, x, y, z) => { projected.push([x, y, z]); return { x: 100 + x, y: 200 }; };
202
+ const items = Role.roleItems(scene, scene.local, {}, {}, roles, project);
203
+ assert.deepEqual(items.map((i) => [i.id, i.text, i.color, i.y]), [['role:me', 'Police', police.color, 249], ['role:p2', 'Doctor', doctor.color, 249]]);
204
+ assert.ok(projected.every((p) => p[1] === 2.25));
205
+ scene.three.nodes.get('body-p2').node.visible = false;
206
+ assert.deepEqual(Role.roleItems(scene, scene.local, {}, {}, roles, project).map((i) => i.id), ['role:me']);
207
+ scene.three.nodes.get('me-body').node.visible = false;
208
+ assert.deepEqual(Role.roleItems(scene, scene.local, {}, {}, roles, project), []);
209
+ const system = read('code/systems/hub.js'), chrome = read('code/client/chrome.js');
210
+ assert.ok(system.includes('labels.push(...roleItems(scene, local, cam, view, Hub.hub.roles, project))'));
211
+ assert.ok(chrome.includes('node.style.color = readableOn(item.color)'));
212
+ });
213
+ test('role chip uses final name height and remote name visibility while keeping the local role', () => {
214
+ const scene = sceneOf(), roles = new Map([['me', police], ['p2', doctor]]);
215
+ const makeTag = (visible) => ({ sprite: { visible, material: { opacity: 1 }, scale: { y: 0.4 } } });
216
+ scene.multiplayer.avatars.tags = new Map([['self', makeTag(false)], ['p2', makeTag(true)]]);
217
+ const cam = { matrixWorld: { elements: [1, 0, 0, 0, 0, 1, 0] } };
218
+ const project = (camera, x, y) => ({ x, y: -y * 100 });
219
+ const items = Role.roleItems(scene, scene.local, cam, {}, roles, project);
220
+ assert.equal(items.length, 2);
221
+ assert.ok(Math.abs(items[0].y - (-205 + 34)) < 1e-9, 'pill starts below the projected tag bottom');
222
+ scene.multiplayer.avatars.tags.get('p2').sprite.visible = false;
223
+ assert.deepEqual(Role.roleItems(scene, scene.local, cam, {}, roles, project).map((item) => item.id), ['role:me']);
224
+ // The late crowd pass updates only existing role chips after deciding tags.
225
+ const chrome = read('code/client/chrome.js');
226
+ const method = chrome.slice(chrome.indexOf(' syncRoleLabels('), chrome.indexOf(' crowdNameLabelBoxes() {'));
227
+ const nodes = new Map([['role:me', { style: {} }], ['role:p2', { style: {} }], ['mark:p2', { style: {} }]]);
228
+ const sync = new Function('labelNodes', 'hudClear', 'hudText', `return ({${method}}).syncRoleLabels`)(nodes, false, { style: { display: 'none' } });
229
+ sync([items[0]]);
230
+ assert.equal(nodes.get('role:p2').style.visibility, 'hidden');
231
+ assert.equal(nodes.get('role:me').style.top, `${items[0].y}px`);
232
+ assert.deepEqual(nodes.get('mark:p2').style, {});
233
+ });
234
+
235
+ test('role chips may overlap the viewer body but still clear HUD and controls; ordinary labels yield', () => {
236
+ for (const focused of [true, false]) {
237
+ const dom = fakeDom({ viewW: 574, viewH: 246 });
238
+ const chrome = makeChrome({ onBack() {}, onAvatar() {}, avatarCount: 2 });
239
+ chrome.setWorldLabelFocus(focused);
240
+ const scene = sceneOf(), roles = new Map([['me', police], ['p2', doctor]]);
241
+ const items = () => Role.roleItems(scene, scene.local, {}, {}, roles, (cam, x) => ({ x: 287 + x * 50, y: 72 }));
242
+ const sign = { id: 'sign', x: 287, y: 121, text: 'Sign' };
243
+ chrome.setLabels([...items(), sign]);
244
+ const own = dom.made.find((node) => node.textContent === 'Police');
245
+ const remote = dom.made.find((node) => node.textContent === 'Doctor');
246
+ const ordinary = dom.made.find((node) => node.textContent === 'Sign');
247
+ for (const node of [own, remote, ordinary]) {
248
+ Object.defineProperty(node, 'rect', { get: () => {
249
+ const x = parseFloat(node.style.left), y = parseFloat(node.style.top);
250
+ return { left: x - 40, right: x + 40, top: y - 24, bottom: y };
251
+ } });
252
+ }
253
+ chrome.setWorldAvatar({ left: 240, right: 434, top: 80, bottom: 220 });
254
+ chrome.flushWorldLabels();
255
+ assert.notEqual(own.style.visibility, 'hidden', 'own role belongs over the local body');
256
+ assert.notEqual(remote.style.visibility, 'hidden', 'remote role may overlap the viewer body');
257
+ assert.equal(ordinary.style.visibility, 'hidden');
258
+ roles.delete('me');
259
+ chrome.setLabels([...items(), sign]); chrome.flushWorldLabels();
260
+ assert.notEqual(remote.style.visibility, 'hidden', 'remote role may overlap the viewer body without the own chip');
261
+ assert.equal(ordinary.style.visibility, 'hidden', 'ordinary label still avoids the body');
262
+ const remoteControl = document.createElement('div');
263
+ remoteControl.rect = remote.rect;
264
+ chrome.safeSurface('remote-role-obstacle', remoteControl, 'control'); chrome.flushWorldLabels();
265
+ assert.equal(remote.style.visibility, 'hidden', 'remote role still yields to controls');
266
+ chrome.safeSurface('remote-role-obstacle', null); chrome.flushWorldLabels();
267
+ assert.notEqual(remote.style.visibility, 'hidden', 'remote role restores after the control leaves');
268
+ roles.set('me', police);
269
+ chrome.setLabels(items());
270
+ const chip = dom.made.findLast((node) => node.textContent === 'Police');
271
+ Object.defineProperty(chip, 'rect', { get: () => {
272
+ const x = parseFloat(chip.style.left), y = parseFloat(chip.style.top);
273
+ return { left: x - 40, right: x + 40, top: y - 24, bottom: y };
274
+ } });
275
+ const hud = dom.made.find((node) => node.styles.textShadow?.includes('rgba(0,0,0,0.95)'));
276
+ hud.rect = { left: 100, right: 400, top: 60, bottom: 130 };
277
+ chrome.setHudClear(true);
278
+ chrome.setHud({ title: 'Town', big: 'Roles' }, null);
279
+ chrome.setLabels(items()); chrome.flushHudClear(); chrome.flushWorldLabels();
280
+ assert.ok(chip.rect.top > hud.rect.bottom, 'own chip still moves clear of the HUD');
281
+ assert.notEqual(chip.style.visibility, 'hidden', 'HUD-cleared own chip may still overlap its body');
282
+ const control = document.createElement('div');
283
+ control.rect = chip.rect;
284
+ chrome.safeSurface('role-obstacle', control, 'control'); chrome.flushWorldLabels();
285
+ assert.equal(chip.style.visibility, 'hidden', 'own chip still yields to controls');
286
+ chrome.safeSurface('role-obstacle', null); chrome.flushWorldLabels();
287
+ assert.notEqual(chip.style.visibility, 'hidden', 'own chip restores after the control leaves');
288
+ scene.three.nodes.get(scene.local.id).node.visible = false;
289
+ chrome.setLabels(items()); chrome.flushWorldLabels();
290
+ assert.ok(!chip.parent.children.includes(chip), 'hidden body removes its own chip');
291
+ chrome.dispose();
292
+ }
293
+ });
294
+
295
+ test('late role sync preserves HUD clearance and world-layout visibility', () => {
296
+ const dom = fakeDom({ viewW: 400, viewH: 800 });
297
+ const chrome = makeChrome({ onBack() {}, onAvatar() {}, avatarCount: 2 });
298
+ const hud = dom.made.find((node) => node.styles.textShadow?.includes('rgba(0,0,0,0.95)'));
299
+ hud.rect = { left: 100, right: 300, top: 60, bottom: 160 };
300
+ chrome.setHudClear(true);
301
+ chrome.setHud({ title: 'Town', big: 'Roles' }, null);
302
+ const item = { id: 'role:p2', x: 200, y: 120, text: 'Doctor', color: doctor.color };
303
+ chrome.setLabels([item]);
304
+ const chip = dom.made.find((node) => node.textContent === 'Doctor');
305
+ Object.defineProperty(chip, 'rect', { get: () => {
306
+ const x = parseFloat(chip.style.left), y = parseFloat(chip.style.top);
307
+ return { left: x - 40, right: x + 40, top: y - 24, bottom: y };
308
+ } });
309
+ chrome.flushHudClear();
310
+ const clearedTop = chip.style.top;
311
+ assert.ok(parseFloat(clearedTop) > item.y);
312
+ chrome.syncRoleLabels([item]);
313
+ assert.equal(chip.style.top, clearedTop, 'repositioning runs clearance on the final anchor');
314
+ chrome.syncRoleLabels([item], null, false);
315
+ assert.equal(chip.style.top, clearedTop, 'the visibility pass never restores projected coordinates');
316
+ chrome.setWorldLabelFocus(true);
317
+ chrome.flushWorldLabels();
318
+ assert.notEqual(chip.style.visibility, 'hidden', 'cleared chip survives world layout');
319
+ chip.style.visibility = 'hidden';
320
+ chrome.syncRoleLabels([item], null, false);
321
+ assert.equal(chip.style.visibility, 'hidden', 'late sync respects an existing hide');
322
+ chrome.setHudClear(false);
323
+ chrome.setHud({ text: 'Choose a role' }, null);
324
+ const prompt = dom.made.find((node) => node.dataset.hub === 'hud-prompt');
325
+ prompt.rect = { left: 100, right: 300, top: 600, bottom: 626 };
326
+ const overPrompt = { ...item, y: 620 };
327
+ chrome.setLabels([overPrompt, { id: 'sign', x: 200, y: 620, text: 'Sign' }]);
328
+ const sign = dom.made.find((node) => node.textContent === 'Sign');
329
+ chrome.syncRoleLabels([overPrompt]);
330
+ assert.ok(parseFloat(chip.style.top) < overPrompt.y, 'reanchored roles still clear the bottom prompt');
331
+ assert.ok(parseFloat(sign.style.top) < overPrompt.y, 'role clearance preserves pending ordinary label clearance');
332
+ chrome.dispose();
333
+ });
334
+
335
+ test('crowd selection reanchors roles after name resizing and excludes only their own chips', () => {
336
+ State.clear();
337
+ const dom = fakeDom({ viewW: 400, viewH: 800 });
338
+ const chrome = makeChrome({ onBack() {}, onAvatar() {}, avatarCount: 2 });
339
+ const scene = sceneOf(), view = { w: 400, h: 800 };
340
+ const camera = { matrixWorld: { elements: [1, 0, 0, 0, 0, 1, 0] } };
341
+ const project = (cam, x, y) => ({ x: 200 + x * 10, y: 300 - y * 10 });
342
+ const sprite = new THREE.Sprite(new THREE.SpriteMaterial());
343
+ sprite.position.set(2, 2.25, 0); sprite.scale.set(0.8, 0.4, 1);
344
+ scene.multiplayer.avatars.tags = new Map([['p2', { sprite }]]);
345
+ scene.multiplayer.net.others = () => new Map([['p2', {}]]);
346
+ scene.three.camera = camera; scene.data = {};
347
+ scene.actorWith = () => scene.local;
348
+ State.hub.roles.set('p2', doctor);
349
+ chrome.setLabels(Role.roleItems(scene, scene.local, camera, view, State.hub.roles, project));
350
+ const chip = dom.made.find((node) => node.textContent === 'Doctor');
351
+ Object.defineProperty(chip, 'rect', { get: () => {
352
+ const x = parseFloat(chip.style.left), y = parseFloat(chip.style.top);
353
+ return { left: x - 40, right: x + 40, top: y - 24, bottom: y };
354
+ } });
355
+ const oldTop = chip.style.top;
356
+ const source = read('code/systems/hub.js');
357
+ const start = source.indexOf(' layoutCrowdNames(scene, now) {');
358
+ const method = source.slice(start, source.indexOf('\n }\n', start) + 4);
359
+ const deps = { Hub: { hub: State.hub }, AvatarCap: { shown: () => 1 }, roleItems: Role.roleItems,
360
+ project, crowdNamesFor, layoutCrowdNames, readableSpriteBox, spriteBox, placeLabels, sceneKeyOf: () => 'main' };
361
+ const layout = new Function(...Object.keys(deps), `return ({${method}}).layoutCrowdNames`)(...Object.values(deps));
362
+ const system = { chrome, crowdNamesReady: () => true, friendsAll: null,
363
+ crowdFrame: { view, controls: [], local: scene.local.components.Transform } };
364
+ const labelBoxes = chrome.crowdNameLabelBoxes.bind(chrome);
365
+ chrome.crowdNameLabelBoxes = () => {
366
+ assert.notEqual(chip.style.top, oldTop, 'chips follow resized tags before obstacles are sampled');
367
+ return labelBoxes();
368
+ };
369
+ layout.call(system, scene, 0);
370
+ assert.ok(sprite.scale.y > 0.4, 'the small tag was enlarged');
371
+ assert.equal(sprite.visible, true, 'role chip never suppresses its name');
372
+ assert.notEqual(chip.style.visibility, 'hidden');
373
+ const ownBox = labelBoxes()[0];
374
+ assert.equal(ownBox.rolePlayerId, 'p2');
375
+ const candidate = { id: 'p2', distance: 1, at: { x: 2, z: 0 }, box: ownBox };
376
+ const state = makeCrowdNames();
377
+ const run = (now, rolePlayerId) => layoutCrowdNames(state, [candidate], { now, view, obstacles: [{ ...ownBox, rolePlayerId }] });
378
+ assert.ok(run(0, 'p2').visible.has('p2'), 'own chip is exempt even when clearance overlaps its name');
379
+ assert.equal(run(1, 'other').visible.size, 0, 'other players chips remain obstacles');
380
+ assert.equal(run(2, 'p2').visible.size, 0);
381
+ assert.ok(run(252, 'p2').visible.has('p2'), 'own chip cannot prevent hysteresis restoration');
382
+ chrome.dispose(); State.clear();
383
+ });
384
+ test('a chip whose name the crowd pass rejects stays hidden after the summary flush', () => {
385
+ State.clear();
386
+ const dom = fakeDom({ viewW: 400, viewH: 800 });
387
+ const chrome = makeChrome({ onBack() {}, onAvatar() {}, avatarCount: 2 });
388
+ const scene = sceneOf(), view = { w: 400, h: 800 };
389
+ const camera = { matrixWorld: { elements: [1, 0, 0, 0, 0, 1, 0] } };
390
+ const project = (cam, x, y) => ({ x: 200 + x * 10, y: 300 - y * 10 });
391
+ const sprite = new THREE.Sprite(new THREE.SpriteMaterial());
392
+ sprite.position.set(2, 2.25, 0); sprite.scale.set(0.8, 0.4, 1);
393
+ scene.multiplayer.avatars.tags = new Map([['p2', { sprite }]]);
394
+ scene.multiplayer.net.others = () => new Map([['p2', {}]]);
395
+ scene.three.camera = camera; scene.data = {};
396
+ scene.actorWith = () => scene.local;
397
+ State.hub.roles.set('p2', doctor);
398
+ chrome.setLabels(Role.roleItems(scene, scene.local, camera, view, State.hub.roles, project));
399
+ const chip = dom.made.find((node) => node.textContent === 'Doctor');
400
+ const source = read('code/systems/hub.js');
401
+ const start = source.indexOf(' layoutCrowdNames(scene, now) {');
402
+ const method = source.slice(start, source.indexOf('\n }\n', start) + 4);
403
+ const deps = { Hub: { hub: State.hub }, AvatarCap: { shown: () => 1 }, roleItems: Role.roleItems,
404
+ project, crowdNamesFor, layoutCrowdNames, readableSpriteBox, spriteBox, placeLabels, sceneKeyOf: () => 'main' };
405
+ const layout = new Function(...Object.keys(deps), `return ({${method}}).layoutCrowdNames`)(...Object.values(deps));
406
+ // A control over the whole view rejects every name.
407
+ const system = { chrome, crowdNamesReady: () => true, friendsAll: null,
408
+ crowdFrame: { view, controls: [{ left: 0, right: 400, top: 0, bottom: 800 }], local: scene.local.components.Transform } };
409
+ // The summary's world-layout flush restores labels layout hid, so the
410
+ // late role pass (position false) must come after it.
411
+ const order = [];
412
+ const summary = chrome.setCrowdNameSummary.bind(chrome), sync = chrome.syncRoleLabels.bind(chrome);
413
+ chrome.setCrowdNameSummary = (...args) => { order.push('summary'); return summary(...args); };
414
+ chrome.syncRoleLabels = (items, keep, position = true) => { order.push(position ? 'roles' : 'roles-late'); return sync(items, keep, position); };
415
+ layout.call(system, scene, 0);
416
+ assert.equal(sprite.visible, false, 'the name was rejected');
417
+ assert.deepEqual(order, ['roles', 'summary', 'roles-late']);
418
+ assert.equal(chip.style.visibility, 'hidden', 'its role chip is hidden with it, after the summary flush');
419
+ chrome.dispose(); State.clear();
420
+ });
421
+ console.log(`test-role-client: ${n} passed`);