castle-web-cli 0.4.231 → 0.4.233

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 (368) hide show
  1. package/dist/agent-failures.d.ts +8 -0
  2. package/dist/agent-failures.js +19 -2
  3. package/dist/agent-prompts.d.ts +1 -1
  4. package/dist/agent-prompts.js +10 -3
  5. package/dist/agent.d.ts +64 -3
  6. package/dist/agent.js +170 -81
  7. package/dist/castle-host/host.d.ts +1 -0
  8. package/dist/castle-host/host.js +51 -3
  9. package/dist/castleJson.d.ts +4 -2
  10. package/dist/castleJson.js +2 -0
  11. package/dist/check.d.ts +3 -1
  12. package/dist/check.js +11 -1
  13. package/dist/devSessionStorage.js +47 -1
  14. package/dist/importPinMismatch.d.ts +22 -0
  15. package/dist/importPinMismatch.js +77 -0
  16. package/dist/importRegression.js +3 -15
  17. package/dist/imports.d.ts +10 -3
  18. package/dist/imports.js +88 -20
  19. package/dist/index.js +5 -4
  20. package/dist/init.js +1 -1
  21. package/dist/platformDoc.js +22 -0
  22. package/dist/routerFences.d.ts +5 -0
  23. package/dist/routerFences.js +12 -2
  24. package/dist/save-deck.d.ts +5 -0
  25. package/dist/save-deck.js +37 -4
  26. package/dist/serve.js +3 -0
  27. package/dist/serverBundle.js +5 -3
  28. package/dist/shell/assets/{index-D2tWM896.js → index-BjOxR-lW.js} +4 -4
  29. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  30. package/dist/shell/index.html +2 -2
  31. package/dist/taskSteer.d.ts +13 -0
  32. package/dist/taskSteer.js +22 -2
  33. package/kits/base/castle.json +1 -1
  34. package/kits/base/package-lock.json +1 -1
  35. package/kits/base/sdk/README.md +79 -2
  36. package/kits/base/sdk/avatar.d.ts +6 -2
  37. package/kits/base/sdk/avatar.js +12 -4
  38. package/kits/base/sdk/castle.d.ts +1 -1
  39. package/kits/base/sdk/commands.d.ts +14 -0
  40. package/kits/base/sdk/hub.d.ts +6 -2
  41. package/kits/base/sdk/hub.js +13 -0
  42. package/kits/base/sdk/multiplayer.js +17 -1
  43. package/kits/base/sdk/save.js +2 -1
  44. package/kits/base/sdk/server/hub.d.ts +87 -0
  45. package/kits/base/sdk/server/hub.js +70 -0
  46. package/kits/base/sdk/server/platformHandle.d.ts +31 -1
  47. package/kits/base/sdk/server/storage.d.ts +13 -0
  48. package/kits/base/sdk/server/storage.js +46 -0
  49. package/kits/base/sdk/server/wrapper.d.ts +36 -5
  50. package/kits/base/sdk/server/wrapper.js +83 -8
  51. package/kits/hub-game/CLAUDE.md +352 -12
  52. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  53. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  54. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  55. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  56. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  57. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  58. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  59. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  60. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  61. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  62. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  63. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  64. package/kits/hub-game/code/client/actorBudget.js +47 -0
  65. package/kits/hub-game/code/client/attention.js +11 -2
  66. package/kits/hub-game/code/client/avatar.js +345 -32
  67. package/kits/hub-game/code/client/avatarCap.js +228 -0
  68. package/kits/hub-game/code/client/avatarColors.js +70 -0
  69. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  70. package/kits/hub-game/code/client/avatarShare.js +251 -0
  71. package/kits/hub-game/code/client/ballot.js +467 -0
  72. package/kits/hub-game/code/client/build.js +22 -0
  73. package/kits/hub-game/code/client/chat.js +12 -0
  74. package/kits/hub-game/code/client/chrome.js +1334 -50
  75. package/kits/hub-game/code/client/companion.js +716 -0
  76. package/kits/hub-game/code/client/companionDress.js +99 -0
  77. package/kits/hub-game/code/client/decor.js +509 -0
  78. package/kits/hub-game/code/client/earned.js +131 -0
  79. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  80. package/kits/hub-game/code/client/grab.js +363 -20
  81. package/kits/hub-game/code/client/hats.js +26 -0
  82. package/kits/hub-game/code/client/hookLayer.js +328 -15
  83. package/kits/hub-game/code/client/hudClear.js +126 -0
  84. package/kits/hub-game/code/client/idle.js +163 -22
  85. package/kits/hub-game/code/client/interestCap.js +81 -0
  86. package/kits/hub-game/code/client/keys.js +36 -0
  87. package/kits/hub-game/code/client/labelsNear.js +205 -0
  88. package/kits/hub-game/code/client/menuIcons.js +34 -0
  89. package/kits/hub-game/code/client/pack.js +6 -2
  90. package/kits/hub-game/code/client/packFormat.js +3 -3
  91. package/kits/hub-game/code/client/rehello.js +167 -0
  92. package/kits/hub-game/code/client/shot.js +92 -0
  93. package/kits/hub-game/code/client/sound.js +63 -8
  94. package/kits/hub-game/code/client/soundscape.js +1151 -0
  95. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  96. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  97. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  98. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  99. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  100. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  101. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  102. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  103. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  104. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  105. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  106. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  107. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  108. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  109. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  110. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  111. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  112. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  113. package/kits/hub-game/code/client/spin.js +101 -0
  114. package/kits/hub-game/code/client/state.js +131 -1
  115. package/kits/hub-game/code/client/stuck.js +259 -0
  116. package/kits/hub-game/code/client/talk.js +538 -47
  117. package/kits/hub-game/code/client/tiers.js +541 -27
  118. package/kits/hub-game/code/client/toastBand.js +37 -0
  119. package/kits/hub-game/code/client/together.js +98 -1
  120. package/kits/hub-game/code/client/visibility.js +43 -0
  121. package/kits/hub-game/code/client/wear.js +470 -97
  122. package/kits/hub-game/code/client/yours.js +199 -0
  123. package/kits/hub-game/code/companionSpec.js +45 -0
  124. package/kits/hub-game/code/privateText.js +7 -0
  125. package/kits/hub-game/code/server/actions.js +133 -0
  126. package/kits/hub-game/code/server/actors.js +14 -1
  127. package/kits/hub-game/code/server/ask.js +155 -0
  128. package/kits/hub-game/code/server/ballot.js +539 -0
  129. package/kits/hub-game/code/server/cells.js +100 -0
  130. package/kits/hub-game/code/server/companion.js +82 -0
  131. package/kits/hub-game/code/server/cues.js +70 -0
  132. package/kits/hub-game/code/server/decor.js +269 -0
  133. package/kits/hub-game/code/server/earned.js +461 -0
  134. package/kits/hub-game/code/server/friendBests.js +166 -0
  135. package/kits/hub-game/code/server/friendsAmong.js +232 -0
  136. package/kits/hub-game/code/server/grab.js +296 -11
  137. package/kits/hub-game/code/server/history.js +5 -0
  138. package/kits/hub-game/code/server/hub.js +1317 -52
  139. package/kits/hub-game/code/server/idle.js +30 -11
  140. package/kits/hub-game/code/server/index.js +2 -2
  141. package/kits/hub-game/code/server/labels.js +28 -2
  142. package/kits/hub-game/code/server/manifest.js +424 -8
  143. package/kits/hub-game/code/server/menu.js +133 -0
  144. package/kits/hub-game/code/server/npcs.js +830 -80
  145. package/kits/hub-game/code/server/party.js +13 -2
  146. package/kits/hub-game/code/server/players.js +22 -0
  147. package/kits/hub-game/code/server/say.js +8 -2
  148. package/kits/hub-game/code/server/shot.js +110 -0
  149. package/kits/hub-game/code/server/standing.js +124 -0
  150. package/kits/hub-game/code/server/vis.js +113 -0
  151. package/kits/hub-game/code/server/wear.js +128 -11
  152. package/kits/hub-game/code/server/yours.js +59 -0
  153. package/kits/hub-game/code/shared/cues.js +9 -0
  154. package/kits/hub-game/code/shared/decor.js +41 -0
  155. package/kits/hub-game/code/shared/shot.js +19 -0
  156. package/kits/hub-game/code/shared/spin.js +57 -0
  157. package/kits/hub-game/code/systems/hub.js +1083 -85
  158. package/kits/hub-game/docs/content-pack.md +1 -1
  159. package/kits/hub-game/docs/contract.md +2440 -61
  160. package/kits/hub-game/docs/home-pieces.md +64 -0
  161. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  162. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  163. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  164. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  165. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  166. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  167. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  168. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  169. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  170. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  171. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  172. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  173. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  174. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  175. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  176. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  177. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  178. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  179. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  180. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  181. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  182. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  183. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  184. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  185. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  186. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  187. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  188. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  189. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  190. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  191. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  192. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  193. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  194. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  195. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  196. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  197. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  198. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  199. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  200. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  201. package/kits/hub-game/package-lock.json +2 -0
  202. package/kits/hub-game/package.json +2 -1
  203. package/kits/hub-game/scripts/check.mjs +78 -11
  204. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  205. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +121 -0
  206. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  207. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +23 -0
  208. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +107 -0
  209. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  210. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  211. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  212. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  213. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  214. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  215. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  216. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  217. package/kits/hub-game/scripts/test-actions-client.mjs +488 -0
  218. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  219. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  220. package/kits/hub-game/scripts/test-actors.mjs +19 -17
  221. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  222. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  223. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  224. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  225. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  226. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  227. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  228. package/kits/hub-game/scripts/test-avatar-wire.mjs +753 -0
  229. package/kits/hub-game/scripts/test-avatar.mjs +540 -7
  230. package/kits/hub-game/scripts/test-ballot.mjs +1001 -0
  231. package/kits/hub-game/scripts/test-build.mjs +31 -0
  232. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  233. package/kits/hub-game/scripts/test-chat.mjs +694 -0
  234. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  235. package/kits/hub-game/scripts/test-companion-chat.mjs +198 -0
  236. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  237. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  238. package/kits/hub-game/scripts/test-decor-client.mjs +303 -0
  239. package/kits/hub-game/scripts/test-decor.mjs +457 -0
  240. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  241. package/kits/hub-game/scripts/test-earned.mjs +1194 -0
  242. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  243. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  244. package/kits/hub-game/scripts/test-grab-client.mjs +186 -3
  245. package/kits/hub-game/scripts/test-grab-orbit.mjs +918 -0
  246. package/kits/hub-game/scripts/test-grab.mjs +864 -3
  247. package/kits/hub-game/scripts/test-hats.mjs +483 -0
  248. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  249. package/kits/hub-game/scripts/test-hub-ops.mjs +439 -2
  250. package/kits/hub-game/scripts/test-hub-trip.mjs +1228 -1
  251. package/kits/hub-game/scripts/test-hud-clear.mjs +1000 -0
  252. package/kits/hub-game/scripts/test-idle.mjs +361 -1
  253. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  254. package/kits/hub-game/scripts/test-interest-cells.mjs +493 -0
  255. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  256. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  257. package/kits/hub-game/scripts/test-labels.mjs +596 -0
  258. package/kits/hub-game/scripts/test-manifest.mjs +282 -0
  259. package/kits/hub-game/scripts/test-menu-client.mjs +480 -0
  260. package/kits/hub-game/scripts/test-menu.mjs +296 -0
  261. package/kits/hub-game/scripts/test-npcs.mjs +1718 -12
  262. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  263. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  264. package/kits/hub-game/scripts/test-party.mjs +22 -1
  265. package/kits/hub-game/scripts/test-picker.mjs +314 -0
  266. package/kits/hub-game/scripts/test-rehello.mjs +1039 -0
  267. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  268. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  269. package/kits/hub-game/scripts/test-say.mjs +59 -2
  270. package/kits/hub-game/scripts/test-shot.mjs +756 -0
  271. package/kits/hub-game/scripts/test-soundscape.mjs +5432 -0
  272. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  273. package/kits/hub-game/scripts/test-standing.mjs +416 -0
  274. package/kits/hub-game/scripts/test-stuck.mjs +1903 -0
  275. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  276. package/kits/hub-game/scripts/test-tiers-render.mjs +339 -0
  277. package/kits/hub-game/scripts/test-tiers.mjs +666 -3
  278. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  279. package/kits/hub-game/scripts/test-try-on.mjs +940 -0
  280. package/kits/hub-game/scripts/test-vis.mjs +343 -0
  281. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  282. package/kits/hub-game/scripts/test-yours-chrome.mjs +166 -0
  283. package/kits/hub-game/scripts/test-yours.mjs +372 -0
  284. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  285. package/kits/multiplayer-3d/castle.json +5 -5
  286. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  287. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  288. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  289. package/kits/multiplayer-3d/code/options.js +5 -0
  290. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  291. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  292. package/kits/multiplayer-3d/code/server/world.js +7 -0
  293. package/kits/multiplayer-3d/code/systems/multiplayer.js +74 -4
  294. package/kits/multiplayer-3d/package.json +2 -1
  295. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  296. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  297. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  298. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  299. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  300. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  301. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  302. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  303. package/kits/physics-2d/CLAUDE.md +9 -0
  304. package/kits/physics-2d/castle.json +2 -2
  305. package/kits/physics-2d/engine/scene.js +288 -1
  306. package/kits/physics-2d/engine/skyKey.js +129 -0
  307. package/kits/physics-2d/engine/stillClock.js +106 -0
  308. package/kits/physics-2d/engine/updateBudget.js +21 -0
  309. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +370 -1
  310. package/kits/physics-3d/CLAUDE.md +1391 -0
  311. package/kits/physics-3d/behaviors/Player.jsx +921 -3
  312. package/kits/physics-3d/castle.json +3 -3
  313. package/kits/physics-3d/docs/pxmodel-format.md +12 -0
  314. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +98 -10
  315. package/kits/physics-3d/engine3d/actornode.js +86 -0
  316. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  317. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  318. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  319. package/kits/physics-3d/engine3d/framecap.js +96 -0
  320. package/kits/physics-3d/engine3d/gait.js +118 -0
  321. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  322. package/kits/physics-3d/engine3d/look.js +507 -48
  323. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  324. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  325. package/kits/physics-3d/engine3d/motion.js +39 -10
  326. package/kits/physics-3d/engine3d/nearshadows.js +37 -19
  327. package/kits/physics-3d/engine3d/optimize.js +58 -5
  328. package/kits/physics-3d/engine3d/orbitinput.js +755 -0
  329. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  330. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  331. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  332. package/kits/physics-3d/engine3d/shadowfade.js +882 -0
  333. package/kits/physics-3d/engine3d/sky.js +547 -0
  334. package/kits/physics-3d/engine3d/skylife.js +306 -0
  335. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  336. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  337. package/kits/physics-3d/engine3d/world3d.js +870 -87
  338. package/kits/physics-3d/main.jsx +5 -0
  339. package/kits/physics-3d/package.json +1 -1
  340. package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
  341. package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
  342. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  343. package/kits/physics-3d/scripts/test-camera-follow.mjs +12 -2
  344. package/kits/physics-3d/scripts/test-camera-orbit.mjs +4588 -0
  345. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
  346. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +435 -0
  347. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  348. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  349. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  350. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  351. package/kits/physics-3d/scripts/test-near-shadows.mjs +3 -0
  352. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1920 -0
  353. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +545 -0
  354. package/kits/physics-3d/scripts/test-orbit-shot.mjs +583 -0
  355. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  356. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  357. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  358. package/kits/physics-3d/scripts/test-static-actors.mjs +13 -1
  359. package/kits/physics-3d/scripts/test-static-passes.mjs +1 -1
  360. package/kits/physics-3d/scripts/test-static-scenery.mjs +2171 -0
  361. package/kits/physics-3d/scripts/test-steady-hover.mjs +635 -0
  362. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  363. package/kits/physics-3d/systems/physics3d.js +474 -12
  364. package/kits/real-time/castle.json +2 -2
  365. package/kits/real-time/code/server/gameHooks.js +7 -0
  366. package/kits/real-time/code/server/session.js +97 -19
  367. package/package.json +2 -2
  368. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -10,24 +10,43 @@
10
10
  // `worldCharacters`: the session callbacks a place's NPCs answer in a world
11
11
  // that carries shared characters (`npcs.js`).
12
12
 
13
- import { readScene } from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
13
+ import * as Scene from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
14
+ import * as Cells from './cells.js';
14
15
  import * as Actors from './actors.js';
15
16
  import * as History from './history.js';
17
+ import * as Friends from './friendsAmong.js';
18
+ import { friendBests } from './friendBests.js';
16
19
  import * as Blocks from './blocks.js';
17
20
  import * as Cabinets from './cabinets.js';
18
21
  import * as Grab from './grab.js';
19
22
  import * as Idle from './idle.js';
23
+ import * as Decor from './decor.js';
24
+ import * as Actions from './actions.js';
25
+ import * as Companion from './companion.js';
26
+ import * as Ask from './ask.js';
27
+ import * as Menu from './menu.js';
28
+ import * as Cues from './cues.js';
29
+ import * as Shot from './shot.js';
30
+ import * as Vis from './vis.js';
31
+ import * as Yours from './yours.js';
20
32
  import * as Manifest from './manifest.js';
21
33
  import { setLabel, wireLabel } from './labels.js';
22
34
  import { makeNpcs } from './npcs.js';
23
35
  import * as Party from './party.js';
36
+ import { standingY } from './standing.js';
24
37
  import * as Place from './place.js';
25
38
  import * as Say from './say.js';
39
+ import * as Ballot from './ballot.js';
26
40
  import * as Wear from './wear.js';
41
+ import * as Earned from './earned.js';
27
42
  import { doorPoint } from '../client/doorFrame.js';
28
43
 
29
44
  // How many avatars the kit offers (`blueprints/avatar-<n>.scene`); contract §11.
30
- export const AVATARS = 4;
45
+ // Sixteen since v1.51: a place on an older kit takes 0-3 and draws anyone
46
+ // wearing another as 0.
47
+ export const AVATARS = 16;
48
+ // The avatars every client can draw, a town's saved before v1.51 included.
49
+ const OLD_AVATARS = 4;
31
50
 
32
51
  // Players sent together by one `hub.go` arrive together: the first arrival of a
33
52
  // group waits this long for the rest before the group is placed.
@@ -50,7 +69,11 @@ const BOARD_EVERY_MS = 60000;
50
69
  // The newest result of the game a player came back from counts as this trip's
51
70
  // for this long: the longest visit (maxDurationSec 1800) and some slack.
52
71
  const RESULT_FRESH_MS = 35 * 60 * 1000;
53
- const MAX_BOARD_DOORS = 16;
72
+ // Ghost refuses more than 16 doors per read (ghost-server
73
+ // src/utils/cauldronHubResults.ts: HUB_READ_MAX_DOORS). A door board has at
74
+ // most 10 top rows and 3 last-event winners (a few KB), so 16 stay well
75
+ // below the host channel's roughly 384 KB frame.
76
+ const BOARD_DOORS_PER_READ = 16;
54
77
  // Cabinet boards in one read: each may be 44 KB, and a read answers in one
55
78
  // frame of the host's channel (about 384 KB).
56
79
  const CABINET_BOARDS_PER_READ = 6;
@@ -60,6 +83,9 @@ const CABINET_BOARDS_PER_READ = 6;
60
83
  const JUMP_OUT = 7;
61
84
  const JUMP_SPREAD = 2;
62
85
  const JUMP_EVERY_MS = 1000;
86
+ // "Stuck?" (v1.33, a deck with `hub.stuck`): how often one player may be put
87
+ // back at the arrival for the asking.
88
+ const UNSTICK_EVERY_MS = 5000;
63
89
  // A player a client already sees counts as this much nearer when the nearest
64
90
  // are picked, so two players at about the same distance do not swap in and
65
91
  // out of its set every tick.
@@ -87,6 +113,10 @@ const USER_ID = /^\d{1,20}$/;
87
113
  // names no `fallY`: above the world's floor (-30), below any pit worth having.
88
114
  const NO_GROUND_FALL_Y = -20;
89
115
 
116
+ function hasHook(deckHooks, placeHooks, name) {
117
+ return typeof deckHooks?.[name] === 'function' || Object.values(placeHooks ?? {}).some((hooks) => typeof hooks?.[name] === 'function');
118
+ }
119
+
90
120
  // `engine` is multiplayer-3d's world (`createBody`, `removeActor`), which
91
121
  // builds and drops the bodies of actors a game spawns (`hub.spawn`).
92
122
  export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGround = () => null, devDecks = null, engine = null) {
@@ -101,12 +131,20 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
101
131
  return { persist: false, sceneFor: () => undefined, worldCharacters: {} };
102
132
  }
103
133
  const h = newState(manifest);
134
+ // v1.53: the deck's own earned items and id, for an unlock kept in this
135
+ // session only (a guest, the dev serve).
136
+ h.unlocks = manifest.unlocks ?? null;
137
+ h.deckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : 'local';
104
138
  h.devDecks = devDecks && typeof devDecks === 'object' ? devDecks : null;
105
139
  h.engine = engine;
106
140
  const tickRate = Number.isFinite(castleJson?.server?.tickRate) && castleJson.server.tickRate > 0 ? castleJson.server.tickRate : 20;
107
141
  const poseEvery = Math.max(1, Math.round(tickRate / POSE_HZ));
108
142
 
109
143
  return {
144
+ // Decor places own their actors on the server. Keyless decks add no hook.
145
+ ...(Object.values(manifest.places).some((place) => place.decor)
146
+ ? { allowClientGone: () => !h.place?.decor }
147
+ : {}),
110
148
  persist: false,
111
149
  poseEvery,
112
150
  poseIntervalMs: Math.round((poseEvery * 1000) / tickRate),
@@ -117,15 +155,72 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
117
155
  h.placeId = id;
118
156
  h.place = manifest.places[id];
119
157
  h.hooks = placeHooks[id] ?? deckHooks;
158
+ if (typeof h.hooks.resume === 'function') {
159
+ h.resumeDeparting ??= new Set();
160
+ }
161
+ if (h.place.resumeKeep === true) {
162
+ h.resumeKept ??= new Map();
163
+ h.resumeDeparting ??= new Set();
164
+ }
165
+ if (h.place.decor) {
166
+ h.ctx.decor = Decor.api(h);
167
+ } else {
168
+ delete h.ctx.decor;
169
+ }
170
+ if (h.place.actions === true) {
171
+ h.ctx.actions = (playerId, items) => Actions.set(h, playerId, items);
172
+ } else {
173
+ delete h.ctx.actions;
174
+ }
175
+ if (h.place.companion === true) {
176
+ h.ctx.companion = (playerId, spec) => Companion.set(h, playerId, spec);
177
+ h.ctx.companionDress = true;
178
+ h.ctx.companionPose = true;
179
+ } else {
180
+ delete h.ctx.companion;
181
+ delete h.ctx.companionDress;
182
+ delete h.ctx.companionPose;
183
+ }
184
+ if (h.place.ask === true) {
185
+ h.ctx.ask = (playerId, spec) => Ask.set(h, playerId, spec);
186
+ } else {
187
+ delete h.ctx.ask;
188
+ }
189
+ if (h.place.menu === true) {
190
+ h.ctx.menu = (playerId, spec) => Menu.set(h, playerId, spec);
191
+ } else {
192
+ delete h.ctx.menu;
193
+ }
120
194
  h.noGround = sceneGround(h.place.scene)?.none === true;
121
195
  h.fallY = h.place.fallY ?? (h.noGround ? NO_GROUND_FALL_Y : null);
122
196
  console.log(`[hub] place ${id} (${source}): ${h.place.scene}`);
123
197
  return h.place.scene;
124
198
  },
125
199
 
200
+ // ready runs before real-time's admit -> addPlayer, including the first
201
+ // tick of a fresh session. Until then no actor-based height is provable.
202
+ standingY(sim, at) {
203
+ return h.sim === sim && h.place ? standingY(h, at) : at.y;
204
+ },
205
+
126
206
  ready(sim) {
127
207
  h.sim = sim;
128
- h.actors = readScene(sim.scenePath);
208
+ h.actors = Scene.readScene(sim.scenePath);
209
+ if (h.place.interest === 'cells') {
210
+ let result;
211
+ try {
212
+ result = Cells.readCells({ cells: Scene.sceneCells?.(sim.scenePath) });
213
+ } catch {
214
+ result = { table: null, reason: 'could not be read' };
215
+ }
216
+ h.cells = result.table;
217
+ if (!h.cells) {
218
+ console.warn(`[hub] interest: cells table ${result.reason}`);
219
+ h.place = { ...h.place, nearestPlayers: h.place.nearestPlayersFallback };
220
+ delete h.place.interest;
221
+ delete h.place.nearestPlayersFallback;
222
+ }
223
+ }
129
224
  h.npcs.ready();
130
225
  h.hooks.ready?.(h.ctx);
131
226
  },
@@ -134,6 +229,34 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
134
229
  // read when the player gets a body.
135
230
  message(session, player, data) {
136
231
  h.session ??= session;
232
+ if (data?.k === 'hub-cap' && h.cells) {
233
+ if (Number.isInteger(data.n)) {
234
+ const now = Date.now();
235
+ const recent = (h.capAt.get(player.playerId) ?? []).filter((at) => now - at < 1000);
236
+ if (recent.length < 4) {
237
+ h.capAt.set(player.playerId, [...recent, now]);
238
+ h.caps.set(player.playerId, Math.max(1, Math.min(h.place.nearestPlayers, data.n)));
239
+ }
240
+ }
241
+ return;
242
+ }
243
+ // v1.91: opt-in, authenticated sender only. Client time is metadata,
244
+ // never a server clock or a way to name another player.
245
+ if (h.place?.visibility === true && data?.k === 'hub-visibility') {
246
+ const entry = h.players.get(player?.playerId);
247
+ if (!entry ||
248
+ !session.players.some((p) => p.playerId === player.playerId) ||
249
+ typeof data.visible !== 'boolean' || !Number.isFinite(data.at) || data.at < 0) {
250
+ return;
251
+ }
252
+ if (entry.visibility && (data.at < entry.visibility.at || data.visible === entry.visibility.visible)) {
253
+ return;
254
+ }
255
+ entry.visibility = { visible: data.visible, at: data.at };
256
+ entry.visibilityPending = true;
257
+ notifyVisibility(h, player.playerId);
258
+ return;
259
+ }
137
260
  if (data?.k === 'hub-hello') {
138
261
  hello(h, player, data);
139
262
  return;
@@ -150,18 +273,30 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
150
273
  whereAsk(h, player, data);
151
274
  return;
152
275
  }
276
+ // v1.33: only a deck with `hub.stuck` knows the message; in any other
277
+ // it goes on to the place's own hooks, as it always did.
278
+ if (h.manifest.stuck && data?.k === 'hub-unstick') {
279
+ (data.ask === true ? unstickAsk : unstick)(h, player);
280
+ return;
281
+ }
153
282
  if (data?.k === 'hub-goto') {
154
283
  goTo(h, player, data);
155
284
  return;
156
285
  }
157
286
  if (data?.k === 'hub-say') {
158
- Say.message({ h, blockedPairs, jumpDoors: doors }, player, data);
287
+ Say.message(sayDeps(h), player, data);
159
288
  return;
160
289
  }
161
290
  if (data?.k === 'hub-party') {
162
291
  Party.message(partyDeps(h), player, data);
163
292
  return;
164
293
  }
294
+ // v1.68: only a place that declares `ballot` knows the message; in any
295
+ // other it goes on to the place's own hooks, as it always did.
296
+ if (h.place?.ballot && data?.k === 'hub-ballot') {
297
+ Ballot.message(h, player, data, h.place.ballot.lines);
298
+ return;
299
+ }
165
300
  if (data?.k === 'hub-dev-classic') {
166
301
  // The dev serve's stand-in for ghost's classic boards (`cabinets.js`).
167
302
  if (h.sim && isDevSession(h)) {
@@ -169,6 +304,22 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
169
304
  }
170
305
  return;
171
306
  }
307
+ if (h.place.decor && data?.k === 'decor') {
308
+ Decor.message(h, player?.playerId, data);
309
+ return;
310
+ }
311
+ if (h.place.actions === true && data?.k === 'hub-action') {
312
+ Actions.message(h, player?.playerId, data);
313
+ return;
314
+ }
315
+ if (h.place.ask === true && data?.k === 'hub-answer') {
316
+ Ask.message(h, player?.playerId, data);
317
+ return;
318
+ }
319
+ if (h.place.menu === true && data?.k === 'hub-menu-pick') {
320
+ Menu.message(h, player?.playerId, data);
321
+ return;
322
+ }
172
323
  if (data?.k === 'hub-grab') {
173
324
  Grab.message(h, player?.playerId, data);
174
325
  return;
@@ -198,8 +349,18 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
198
349
  const dt = h.lastPlaceAt === null ? 0 : Math.min(0.25, (sim.timeMs - h.lastPlaceAt) / 1000);
199
350
  h.lastPlaceAt = sim.timeMs;
200
351
  reconcile(h);
352
+ Friends.tick(h, userIdOf);
353
+ // v1.28: a try-on on a player who went before saying hello goes too.
354
+ if (Wear.tryOnUsed(h)) {
355
+ Wear.pruneTries(h);
356
+ }
357
+ // v1.53, v1.70: likewise wearable or home ownership before a hello.
358
+ if (Earned.needsPrune(h)) {
359
+ Earned.prune(h);
360
+ }
201
361
  readResults(h);
202
362
  arrivals(h);
363
+ if (h.place.visibility === true) {notifyVisibility(h);}
203
364
  enforceHolds(h);
204
365
  enforceSettle(h);
205
366
  Idle.tick(h);
@@ -216,15 +377,35 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
216
377
  const dt = h.lastStepAt === null ? 0 : (sim.timeMs - h.lastStepAt) / 1000;
217
378
  h.lastStepAt = sim.timeMs;
218
379
  h.hooks.step?.(h.ctx, dt);
380
+ rememberResumePoses(h);
381
+ // v1.61: no renewal callback exists unless a player holds a shot.
382
+ h.renewShots?.();
219
383
  Actors.flushTints(h);
220
384
  sendHudOverrides(h);
385
+ // v1.68: nothing in a place that has never shown a choice card.
386
+ if (h.ballotState) {
387
+ Ballot.send(h, ballotDeps(h));
388
+ }
221
389
  Actors.applyTunes(h, h.engine?.maxSpeed?.() ?? 12);
222
390
  sendLabelOverrides(h);
391
+ Vis.send(h);
223
392
  sendAvatarOverrides(h);
393
+ if (h.manifest.yourGames) {
394
+ Yours.send(h, listedDoors(h), membersOf);
395
+ }
224
396
  Party.tick(partyDeps(h));
225
397
  Wear.sendOverrides(h, blockedPairs(h));
398
+ // v1.53 earned items: nothing in a place where nobody shows one.
399
+ if (Earned.used(h)) {
400
+ Earned.sendOverrides(h, blockedPairs(h));
401
+ }
402
+ // v1.28 `hub.tryOn`: nothing in a place that never calls it.
403
+ if (Wear.tryOnUsed(h)) {
404
+ Wear.sendTryOverrides(h, blockedPairs(h));
405
+ }
226
406
  // Cabinet cards (v1.7): nothing in a place with no classic door.
227
407
  Cabinets.send(h, (playerId) => namesOf(h, blockedPairs(h)?.get(playerId) ?? []));
408
+ notifyResumes(h);
228
409
  Actors.flushHandovers(h, handovers);
229
410
  },
230
411
 
@@ -237,9 +418,36 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
237
418
  interest(sim, known) {
238
419
  const pairs = blockedPairs(h);
239
420
  const hidden = pairs ? (viewer, other) => Boolean(pairs.get(viewer)?.has(other)) : null;
421
+ if (h.cells) {
422
+ return Blocks.withoutHidden(cellPlayers(h, sim, known, hidden), pairs);
423
+ }
240
424
  return Blocks.withoutHidden(nearestPlayers(sim, known, h.place.nearestPlayers, hidden), pairs);
241
425
  },
242
426
 
427
+ ...(manifest.places[Manifest.MAIN_PLACE].interest === 'cells' ? {
428
+ objectInterest(sim) {
429
+ if (!h.cells) {
430
+ return null;
431
+ }
432
+ const views = playerCells(h, sim);
433
+ const located = new Map();
434
+ for (const [id, object] of sim.objects) {
435
+ const at = object.body?.translation?.() ?? object.at;
436
+ const cell = Cells.cellAt(h.cells, at?.x, at?.z, h.objectCells.get(id));
437
+ h.objectCells.set(id, cell);
438
+ located.set(id, cell);
439
+ }
440
+ for (const id of h.objectCells.keys()) {
441
+ if (!sim.objects.has(id)) {
442
+ h.objectCells.delete(id);
443
+ }
444
+ }
445
+ return new Map([...views].map(([viewer, { visible }]) => [viewer, new Set([...located].filter(([id, cell]) =>
446
+ visible === null || cell === null || visible.has(cell) || sim.objects.get(id).owner === viewer || h.grabs.get(viewer) === id,
447
+ ).map(([id]) => id))]));
448
+ },
449
+ } : {}),
450
+
243
451
  shutdown: () => shutdown(h),
244
452
 
245
453
  join() {
@@ -248,7 +456,13 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
248
456
  // under it rather than past the world's floor, where no pose is read.
249
457
  hubPlace: { ...Manifest.publicPlace(h.placeId, h.place), fallY: h.fallY },
250
458
  hubAv: avatars(h, blockedPairs(h)),
459
+ // v1.51, only while someone here wears one of the twelve after the first four.
460
+ ...avatars2ForJoin(h),
461
+ ...avatarColorsForJoin(h),
251
462
  ...wearingForJoin(h),
463
+ ...(h.place.companion === true && h.companionUsed ? { hubGlow: Companion.glowOf(h) } : {}),
464
+ // v1.53, only once someone here shows an earned item.
465
+ ...(h.earned.size > 0 ? earnedForJoin(h) : {}),
252
466
  hud: hudForAll(h),
253
467
  hidden: [...h.hidden],
254
468
  held: [...h.held.keys()],
@@ -260,13 +474,28 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
260
474
  spawnTemplates: Actors.templatesOf(h),
261
475
  // v1.6, only in a place that turns idle play on.
262
476
  ...Idle.fields(h),
477
+ // v1.27, only once the place keeps an object for a player.
478
+ ...(h.keptFor.size > 0 ? { hubKept: Grab.keptOf(h) } : {}),
479
+ // v1.28, only while the place shows a try-on on someone.
480
+ ...(h.trying.size > 0 ? tryingForJoin(h) : {}),
481
+ // v1.33, only a town of a deck with `hub.stuck`.
482
+ ...(stuckHere(h) ? { hubStuck: { to: arrivalName(h), ...(hasUnstick(h) ? { hook: true } : {}) } } : {}),
263
483
  };
264
484
  },
265
485
 
266
486
  delta() {
267
487
  const out = {};
268
488
  latch(h, 'hubAv', avatars(h, blockedPairs(h)), out);
489
+ latchAvatars2(h, out);
490
+ latchAvatarColors(h, out);
269
491
  latchWearing(h, out);
492
+ if (h.place.companion === true && h.companionUsed) {
493
+ latch(h, 'hubGlow', Companion.glowOf(h), out);
494
+ }
495
+ // v1.53: nothing until someone shows an earned item, then each change.
496
+ if (h.earned.size > 0 || h.sent.has('hubEarned')) {
497
+ latchEarned(h, out);
498
+ }
270
499
  latch(h, 'hud', hudForAll(h), out);
271
500
  latch(h, 'hidden', [...h.hidden], out);
272
501
  latch(h, 'held', [...h.held.keys()], out);
@@ -279,6 +508,14 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
279
508
  for (const [field, value] of Object.entries(Idle.fields(h))) {
280
509
  latch(h, field, value, out);
281
510
  }
511
+ // v1.27 `hub.keepFor`: nothing until something is kept, then each change.
512
+ if (h.keptFor.size > 0 || h.sent.has('hubKept')) {
513
+ latch(h, 'hubKept', Grab.keptOf(h), out);
514
+ }
515
+ // v1.28 `hub.tryOn`: nothing until someone tries something on, then each change.
516
+ if (h.trying.size > 0 || h.sent.has('hubTry')) {
517
+ latchTrying(h, out);
518
+ }
282
519
  return Object.keys(out).length ? out : null;
283
520
  },
284
521
 
@@ -306,6 +543,18 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
306
543
  }
307
544
  await h.npcs.onRead(request);
308
545
  },
546
+ // v1.66: only a deck with an `npcTool` hook listens for lookups.
547
+ ...(hasHook(deckHooks, placeHooks, 'npcTool')
548
+ ? {
549
+ async onWorldCharacterTool(request, session) {
550
+ h.session ??= session;
551
+ if (!h.sim) {
552
+ return { error: 'not ready' };
553
+ }
554
+ return await h.npcs.onTool(request);
555
+ },
556
+ }
557
+ : {}),
309
558
  },
310
559
  };
311
560
  }
@@ -385,6 +634,14 @@ function logStats(h) {
385
634
  function newState(manifest) {
386
635
  const h = {
387
636
  manifest,
637
+ cells: null,
638
+ cellTick: null,
639
+ cellViews: null,
640
+ playerCells: new Map(),
641
+ objectCells: new Map(),
642
+ caps: new Map(),
643
+ capAt: new Map(),
644
+ sentMaps: new Map(),
388
645
  placeId: Manifest.MAIN_PLACE,
389
646
  place: manifest.places[Manifest.MAIN_PLACE],
390
647
  hooks: {},
@@ -417,12 +674,15 @@ function newState(manifest) {
417
674
  // `${actorId}|${doorId}` -> the door's object `doors()` hands out
418
675
  doorObjects: new Map(),
419
676
  boardsAt: 0,
677
+ boardsReading: false,
420
678
  // `${op}:${code}` refusals already logged
421
679
  refusals: new Set(),
422
680
  hud: null,
423
681
  // playerId -> spec, and what was last sent of each
424
682
  hudMe: new Map(),
425
683
  sentHudMe: new Map(),
684
+ // v1.52: private leaving lines, never part of a snapshot.
685
+ leaving: new Map(),
426
686
  hidden: new Set(),
427
687
  // playerId -> { at, facing }
428
688
  held: new Map(),
@@ -444,6 +704,8 @@ function newState(manifest) {
444
704
  ...Grab.newGrabState(),
445
705
  // what players wear on their avatars (`wear.js`, v1.4)
446
706
  ...Wear.newWearState(),
707
+ // earned items players show (`earned.js`, v1.53)
708
+ ...Earned.newEarnedState(),
447
709
  // emotes, seats and sounds (`idle.js`, v1.6)
448
710
  ...Idle.newIdleState(),
449
711
  // arcade cabinets' cards (`cabinets.js`, v1.7)
@@ -454,6 +716,10 @@ function newState(manifest) {
454
716
  ...Say.newSayState(),
455
717
  };
456
718
  h.ctx = makeContext(h);
719
+ // v1.68: `hub.ballot` only in a deck that declares the card in some place.
720
+ if (manifest.ballot) {
721
+ h.ctx.ballot = (playerIds, spec) => Ballot.ballot(h, playerIds, spec);
722
+ }
457
723
  h.npcLabel = (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, true);
458
724
  h.blockedPairs = () => blockedPairs(h);
459
725
  h.npcs = makeNpcs(h);
@@ -469,6 +735,13 @@ function makeContext(h) {
469
735
  get sim() {
470
736
  return h.sim;
471
737
  },
738
+ get owner() {
739
+ const owner = h.session?.hub?.owner;
740
+ if (typeof owner === 'string' && owner.length > 0) {
741
+ return owner;
742
+ }
743
+ return !platformHub(h) && isDevSession(h) && h.manifest.house?.devOwner === 'first' ? h.devOwner ?? null : null;
744
+ },
472
745
  get place() {
473
746
  return { id: h.placeId, title: h.place.title, scene: h.place.scene, manifest: h.place };
474
747
  },
@@ -501,6 +774,7 @@ function makeContext(h) {
501
774
  const point = at ? { ...at } : { ...body.at };
502
775
  const facing = facingDeg === undefined ? body.facing : facingDeg * DEG;
503
776
  h.held.set(playerId, { at: point, facing });
777
+ Grab.stilled(h, playerId);
504
778
  placeAt(h, playerId, point, facing);
505
779
  },
506
780
  release(playerId) {
@@ -516,14 +790,27 @@ function makeContext(h) {
516
790
  h.hudMe.delete(playerId);
517
791
  }
518
792
  },
519
- hide(actorId) {
520
- if (!isSceneActor(h, actorId) || h.hidden.has(actorId)) {
793
+ hide(actorId, options) {
794
+ if (options !== undefined) {
795
+ return Vis.set(h, actorId, options, true);
796
+ }
797
+ if (!isSceneActor(h, actorId)) {
798
+ return;
799
+ }
800
+ if (h.hidden.has(actorId)) {
801
+ // Hidden already, and kept since (`keepFor` takes a hidden object): hiding it again still ends that.
802
+ Grab.unkeep(h, actorId);
521
803
  return;
522
804
  }
523
805
  h.hidden.add(actorId);
806
+ Grab.taken(h, actorId);
807
+ Grab.unkeep(h, actorId);
524
808
  h.sim?.bodies.get(actorId)?.setEnabled(false);
525
809
  },
526
- show(actorId) {
810
+ show(actorId, options) {
811
+ if (options !== undefined) {
812
+ return Vis.set(h, actorId, options, false);
813
+ }
527
814
  if (!h.hidden.delete(actorId)) {
528
815
  return;
529
816
  }
@@ -532,8 +819,17 @@ function makeContext(h) {
532
819
  move: (actorId, to, options) => Actors.move(h, actorId, to, options),
533
820
  tint: (actorId, color) => Actors.tint(h, actorId, color),
534
821
  mark: (playerId, spec) => Actors.mark(h, playerId, spec),
822
+ leaving: (playerId, text) => leaving(h, playerId, text),
535
823
  results: (playerId) => History.results(h, playerId),
824
+ friendsAmong: (playerId, userIds) => Friends.friendsAmong(h, playerId, userIds, userIdOf),
825
+ friendBests: (key, options) => friendBests(h, key, options, userIdOf),
536
826
  wear: (playerId, spec) => wear(h, playerId, spec),
827
+ tryOn: (playerId, spec) => Wear.tryOn(h, playerId, spec),
828
+ wearing: (playerId) => Wear.wearing(h, playerId),
829
+ unlock: (playerId, itemId) => Earned.unlock(h, playerId, itemId, earnedDeps(h, playerId, 'unlock')),
830
+ wearEarned: (playerId, choice) => Earned.wearEarned(h, playerId, choice, earnedDeps(h, playerId, 'wearEarned')),
831
+ unlocksOf: (userIds) => Earned.unlocksOf(platformHub(h), userIds, (err) => refused(h, 'unlocks', err), h),
832
+ earned: (playerId) => Earned.earnedOf(h, playerId),
537
833
  tune: (playerId, spec) => Actors.tune(h, playerId, spec),
538
834
  spawn: (fromActorId, at) => Actors.spawn(h, fromActorId, at, h.engine),
539
835
  pose: (actorId) => Actors.pose(h, actorId),
@@ -544,12 +840,16 @@ function makeContext(h) {
544
840
  label: (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, false),
545
841
  npc: (actorId) => h.npcs.handle(actorId),
546
842
  npcs: () => h.npcs.list(),
843
+ preferNpc: (playerId, npcId) => h.npcs.prefer(playerId, npcId),
547
844
  result: (playerId, value) => report(h, playerId, value),
548
845
  drop: (playerId) => Grab.drop(h, playerId),
549
846
  emote: (playerId, id) => Idle.emote(h, playerId, id),
550
847
  seat: (playerId) => Idle.seat(h, playerId),
551
848
  sound: (actorId, file, options) => Idle.sound(h, actorId, file, options),
849
+ cue: (target, name) => Cues.cue(h, target, name),
850
+ shot: (playerId, value) => Shot.shot(h, playerId, value),
552
851
  holding: (playerId) => Grab.holding(h, playerId),
852
+ keepFor: (actorId, playerId) => Grab.keepFor(h, actorId, playerId),
553
853
  end(playerIds) {
554
854
  const ids = playerIds ?? [...(h.sim?.players.keys() ?? [])];
555
855
  for (const playerId of ids) {
@@ -577,31 +877,123 @@ function platformHub(h) {
577
877
  // A client's hello: the avatar it wears, the door it came through, how many
578
878
  // came with it, and what it carries back from a game (a town reads that). Where
579
879
  // the host has hub ops, the door is ghost's arrival and the result and avatar
580
- // are read from ghost (`readResults`); the client's word is not used for them.
581
- function hello(h, player, data) {
880
+ // are read from ghost (`readResults`). The hello's avatar and colour are
881
+ // provisional until that read; colours also work with the manifest opt-in.
882
+ function hello(h, player, data, synthetic = false) {
883
+ prepareResume(h, player.playerId, false);
582
884
  const clientAvatar = Number.isInteger(data.avatar) && data.avatar >= 0 && data.avatar < AVATARS ? data.avatar : 0;
885
+ const clientColor = (h.manifest.avatarColors === true || platformHub(h)) ? cleanAvatarColor(data.color) : 0;
583
886
  const party = Number.isInteger(data.party) && data.party >= 1 && data.party <= 24 ? data.party : 1;
584
887
  const known = h.players.get(player.playerId);
888
+ // A player this place let go whose connection came back still holding what
889
+ // it was sent (`greetLate`): the client's own resume hello or the place's
890
+ // late greet for it, whichever comes first, arrives them once and marks that
891
+ // stale. A game keeps the old way, so it takes no resume hello (its round
892
+ // and result belong to the visit that left), unless its place says
893
+ // `resume: true` (v1.72): then it is arrived again like any place, and the
894
+ // visit goes on. A plain hello is a fresh client (a reload), which holds
895
+ // nothing.
896
+ //
897
+ // v1.72 resume invariants, every one only in a place with `resume: true`
898
+ // (`resumes`; without the key none of this runs and nothing is stored):
899
+ // I1 one result per visit, whatever the order of leave, report and
900
+ // resume: `forget` keeps the result after the leave hook ran (which
901
+ // may report it), and the re-arrived entry gets it back;
902
+ // I2 the visit's deadline is set once, at its first arrival (`visitAt`),
903
+ // and kept across resumes, so drops never extend a visit;
904
+ // I3 restored state with a packet is sent again on resume: the end
905
+ // (`hub-end` with `again`), and the HUD, shot and the rest (`staleSent`
906
+ // and the place's own arrive);
907
+ // I4 provenance (`from`, `fromDeckId`) is written once per visit.
908
+ const back = !known && data.resume === true && Boolean(h.forgotten?.has(player.playerId));
909
+ const resumes = h.place?.result ? h.place.resume === true : false;
910
+ if (back && h.place?.result && !resumes) {
911
+ return;
912
+ }
913
+ // v1.72: what a resume place's forgotten record kept of the visit that left.
914
+ const last = back && resumes ? h.forgotten.get(player.playerId) : null;
915
+ h.forgotten?.delete(player.playerId);
916
+ h.noHelloSince?.delete(player.playerId);
917
+ if (back) {
918
+ staleSent(h, player.playerId);
919
+ } else if (resumes && known?.hello && data.resume === true) {
920
+ // v1.72: a game that resumes, still holding the player: the drop may have
921
+ // lost what it sent them, so it all goes again (the leaving line is
922
+ // re-sent by joinedAfresh below).
923
+ staleSent(h, player.playerId, false);
924
+ }
585
925
  const hub = platformHub(h);
586
926
  const arrival = hub ? hub.arrival(player.playerId) : null;
587
- const from = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
927
+ // A resume place's re-arrived player keeps the door they first came by
928
+ // when the platform no longer says one (its arrival goes with the leave).
929
+ const said = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
930
+ // I4: a resume place keeps the visit's first door, whatever a later hello says.
931
+ // A saved none is kept too: only a key never saved takes what is said now.
932
+ const keep = (key, now) => {
933
+ if (!resumes) {
934
+ return now;
935
+ }
936
+ const was = known ?? last;
937
+ return was && Object.hasOwn(was, key) ? was[key] ?? null : now;
938
+ };
939
+ const from = keep('from', said);
940
+ const fromDeckId = keep('fromDeckId', arrival?.fromDeckId ?? null);
588
941
  // A later hello with the same choice keeps the platform avatar a read found;
589
942
  // a new choice wins, and outdates any read in flight (`avatarRev`).
590
943
  const same = known?.hello && known.clientAvatar === clientAvatar;
944
+ const sameColor = same && known.clientColor === clientColor;
945
+ // A stale ballot card still waiting to be cleared survives a repeated
946
+ // resume hello, whose joinedAfresh below would otherwise drop the mark.
947
+ const ballotStale = back || h.ballotState?.sent.get(player.playerId) === STALE;
591
948
  // A hello that is not an avatar change is a client that joined afresh: it
592
949
  // holds none of the cabinet cards it was sent (v1.7).
593
950
  if (data.again !== true) {
951
+ replaySent(h, player.playerId, data.resume === true);
952
+ h.npcs.replayPreferred(player.playerId, data.resume === true);
953
+ Shot.joinedAfresh(h, player.playerId);
954
+ Vis.joinedAfresh(h, player.playerId);
955
+ Decor.joinedAfresh(h, player.playerId);
956
+ if (h.place.actions === true) {
957
+ Actions.joinedAfresh(h, player.playerId);
958
+ }
959
+ if (h.place.companion === true) {
960
+ Companion.joinedAfresh(h, player.playerId);
961
+ }
962
+ if (h.place.ask === true) {
963
+ Ask.joinedAfresh(h, player.playerId);
964
+ }
965
+ if (h.place.menu === true) {
966
+ Menu.joinedAfresh(h, player.playerId);
967
+ }
968
+ if (h.ballotState) {
969
+ Ballot.joinedAfresh(h, player.playerId);
970
+ }
594
971
  Cabinets.forget(h, player.playerId);
972
+ Friends.resend(h, player.playerId);
973
+ // v1.28: nothing in a place that never sent a try-on to one player alone.
974
+ Wear.joinedAfresh(h, player.playerId);
975
+ // v1.53: likewise its earned items alone, only where someone has one.
976
+ if (Earned.used(h)) {
977
+ Earned.joinedAfresh(h, player.playerId);
978
+ }
979
+ // A fresh client with a retained id has none of its private leaving line.
980
+ if (h.leaving.has(player.playerId)) {
981
+ h.session?.send(player.playerId, { k: 'hub-leaving', text: h.leaving.get(player.playerId) });
982
+ }
595
983
  }
596
984
  h.players.set(player.playerId, {
597
985
  // Who this is, kept for `leave`: by then the session has forgotten them.
986
+ ...(h.place.visibility === true && known?.visibility ? { visibility: known.visibility, visibilityPending: known.visibilityPending } : {}),
598
987
  userId: userIdOf(h, player.playerId) ?? known?.userId ?? null,
599
988
  username: usernameOf(h, player.playerId),
600
989
  avatar: same ? known.avatar : clientAvatar,
601
990
  clientAvatar,
991
+ color: sameColor ? known.color : clientColor,
992
+ clientColor,
993
+ colorRev: sameColor ? known.colorRev : (known?.colorRev ?? 0) + 1,
602
994
  avatarRev: same ? known.avatarRev : (known?.avatarRev ?? 0) + 1,
603
995
  from,
604
- fromDeckId: arrival?.fromDeckId ?? null,
996
+ fromDeckId,
605
997
  // A jump to a friend says whom (the client's word: it decides only where
606
998
  // the player appears, beside someone already in this session).
607
999
  near: typeof data.near === 'string' && USER_ID.test(data.near) ? data.near : (known?.near ?? null),
@@ -614,12 +1006,43 @@ function hello(h, player, data) {
614
1006
  helloAt: known?.hello ? known.helloAt : Date.now(),
615
1007
  arrived: known?.arrived ?? false,
616
1008
  arrivedAt: known?.arrivedAt ?? null,
617
- result: known?.result ?? null,
1009
+ result: known?.result ?? (last ? last.result ?? null : null),
618
1010
  // ghost's results of this player for `hub.results`, kept across hellos
619
1011
  history: known?.history ?? null,
620
1012
  historyFrom: known?.historyFrom ?? null,
621
- ended: known?.ended ?? false,
1013
+ ...(h.manifest.yourGames ? { hearts: known?.hearts ?? [], yoursKey: data.again === true ? known?.yoursKey : null } : {}),
1014
+ ended: known?.ended ?? (last ? last.ended === true : false),
1015
+ // v1.72 (I2, I3): only in a resume place, and only once known.
1016
+ ...(resumes && (known?.visitAt ?? last?.visitAt) !== undefined ? { visitAt: known?.visitAt ?? last.visitAt } : {}),
1017
+ ...(resumes && (known?.endWhy ?? last?.endWhy) !== undefined ? { endWhy: known?.endWhy ?? last.endWhy } : {}),
1018
+ ...(last?.ended === true || known?.endAgain === true ? { endAgain: true } : {}),
622
1019
  });
1020
+ // v1.89: hook presence opts in. Wait until the private replay was sent;
1021
+ // the entry identity also prevents a queued hello from crossing a leave.
1022
+ if (known?.arrived && !h.resumeDeparting?.has(player.playerId) && typeof h.hooks.resume === 'function') {
1023
+ const kept = h.resumeKept?.get(player.playerId);
1024
+ const body = h.sim?.players.get(player.playerId);
1025
+ const companionHello = !synthetic && data.resume === true && Boolean(body && kept?.pendingClientHello === body);
1026
+ if (companionHello) {
1027
+ delete kept.pendingClientHello;
1028
+ }
1029
+ if (synthetic && kept) {
1030
+ kept.pendingClientHello = body;
1031
+ }
1032
+ if ((data.again !== true && !companionHello) || h.resumePending?.has(player.playerId)) {
1033
+ (h.resumePending ??= new Map()).set(player.playerId, h.players.get(player.playerId));
1034
+ }
1035
+ }
1036
+ // I3: one still here whose visit ended hears the end again (a drop may
1037
+ // have lost it); one back is told once arrived (`arrivals`).
1038
+ if (resumes && known?.arrived && known.ended && data.resume === true) {
1039
+ endAgain(h, player.playerId);
1040
+ }
1041
+ Friends.prime(h, player.playerId, userIdOf);
1042
+ // After joinedAfresh above, which resets this cache.
1043
+ if (ballotStale && h.ballotState) {
1044
+ h.ballotState.sent.set(player.playerId, STALE);
1045
+ }
623
1046
  }
624
1047
 
625
1048
  // What a returning client says it brings back: the result its game sent it.
@@ -651,15 +1074,260 @@ function outcomeOrNone(outcome) {
651
1074
  // result for the visit (the host takes one for a player who has just left)
652
1075
  // and save their progress under the user id it is handed (v1.2).
653
1076
  function reconcile(h) {
1077
+ for (const playerId of h.resumeKept?.keys() ?? []) {
1078
+ prepareResume(h, playerId);
1079
+ }
1080
+ for (const id of h.playerCells.keys()) {
1081
+ if (!h.sim.players.has(id)) {
1082
+ h.playerCells.delete(id);
1083
+ h.caps.delete(id);
1084
+ h.capAt.delete(id);
1085
+ }
1086
+ }
1087
+ // A connection that sent hub-cap and left before it had a body.
1088
+ for (const id of h.caps.keys()) {
1089
+ if (!h.sim.players.has(id) && !h.session?.players.some((p) => p.playerId === id)) {
1090
+ h.caps.delete(id);
1091
+ h.capAt.delete(id);
1092
+ }
1093
+ }
1094
+ Vis.prune(h);
1095
+ Decor.prune(h);
1096
+ if (h.place.actions === true) {
1097
+ Actions.prune(h);
1098
+ }
1099
+ if (h.place.companion === true) {
1100
+ Companion.prune(h);
1101
+ }
1102
+ if (h.place.ask === true) {
1103
+ Ask.prune(h);
1104
+ }
1105
+ if (h.place.menu === true) {
1106
+ Menu.prune(h);
1107
+ }
1108
+ // A call may precede this player's first hello, as hub.wear may.
1109
+ for (const playerId of h.leaving.keys()) {
1110
+ if (!h.sim.players.has(playerId) && !h.session?.players.some((p) => p.playerId === playerId)) {
1111
+ h.leaving.delete(playerId);
1112
+ }
1113
+ }
654
1114
  for (const playerId of [...h.players.keys()]) {
655
1115
  const inSession = h.session?.players.some((p) => p.playerId === playerId);
656
1116
  if (!h.sim.players.has(playerId) && !inSession) {
657
- forget(h, playerId);
1117
+ if (!h.resumeKept?.has(playerId)) {
1118
+ forget(h, playerId);
1119
+ }
1120
+ }
1121
+ }
1122
+ greetLate(h);
1123
+ }
1124
+
1125
+ // v1.89 opt-in retention: the transport supplies no close reason. An absent
1126
+ // body is held for at most 60 wall-clock seconds; shutdown and explicit kit
1127
+ // travel still finalize the visit. Pose copies are taken after the deck's step,
1128
+ // before real-time removes a dropped body on its next roster reconciliation.
1129
+ const RESUME_KEEP_MS = 60000;
1130
+ function rememberResumePoses(h) {
1131
+ if (!h.resumeKept) {
1132
+ return;
1133
+ }
1134
+ for (const [id, entry] of h.players) {
1135
+ const body = h.sim.players.get(id);
1136
+ if (!entry.arrived || !body) {
1137
+ continue;
1138
+ }
1139
+ h.resumeKept.set(id, {
1140
+ body,
1141
+ at: { ...body.at },
1142
+ facing: body.facing,
1143
+ seenAt: Date.now(),
1144
+ ...(h.resumeKept.get(id)?.pendingClientHello ? { pendingClientHello: h.resumeKept.get(id).pendingClientHello } : {}),
1145
+ });
1146
+ }
1147
+ }
1148
+
1149
+ function prepareResume(h, playerId, greet = true) {
1150
+ const kept = h.resumeKept?.get(playerId);
1151
+ if (!kept) {
1152
+ return;
1153
+ }
1154
+ const body = h.sim?.players.get(playerId);
1155
+ const present = body && h.session?.players.some((p) => p.playerId === playerId);
1156
+ const returning = present && (kept.awayAt !== undefined || body !== kept.body);
1157
+ if (!present) {
1158
+ kept.awayAt ??= Date.now();
1159
+ }
1160
+ // A replacement body can arrive before an absent tick was observed. In that
1161
+ // case the last tick that saw the old body bounds its reconnect window.
1162
+ const since = kept.awayAt ?? kept.seenAt;
1163
+ if ((!present || returning) && (h.resumeDeparting.has(playerId) || Date.now() - since >= RESUME_KEEP_MS)) {
1164
+ forget(h, playerId);
1165
+ return;
1166
+ }
1167
+ if (!returning) {
1168
+ return;
1169
+ }
1170
+ moveBody(h, playerId, kept.at, kept.facing);
1171
+ settle(h, playerId);
1172
+ kept.body = body;
1173
+ delete kept.awayAt;
1174
+ // The silent same-id case has no fresh arrive hook. Reuse the existing hello
1175
+ // replay to restore private channels, including a cleared channel it missed.
1176
+ if (greet) {
1177
+ const entry = h.players.get(playerId);
1178
+ hello(
1179
+ h,
1180
+ { playerId },
1181
+ {
1182
+ k: 'hub-hello',
1183
+ avatar: entry.clientAvatar,
1184
+ color: entry.clientColor,
1185
+ party: 1,
1186
+ resume: true,
1187
+ },
1188
+ true,
1189
+ );
1190
+ }
1191
+ }
1192
+
1193
+ // Reconnect re-hello (a bug fix for every place, no contract version): a
1194
+ // connection that comes back inside the host's reconnect window after the place
1195
+ // let its player go (an app switch on a phone) has a body and no hello, and its
1196
+ // client, still on the same connection, never greets again (it greets a new
1197
+ // connection only), so the player would be a ghost: no HUD, no shots, no door.
1198
+ // Only a player this place let go in the last 10 minutes is greeted for, after
1199
+ // 3 s without a hello, with the avatar it last chose here (the platform's
1200
+ // avatar read still applies): a newcomer's own first hello carries its party
1201
+ // and arrival, so it is always waited for. Nothing changes until a reconnect.
1202
+ // Not in a game (a place with `result`): its round and result belong to the
1203
+ // visit that left, so it keeps the old way (a fresh join once the window ends),
1204
+ // unless its place says `resume: true` (v1.72), when it is greeted like any.
1205
+ // The client still holds what it was last sent privately (HUD, labels, tune,
1206
+ // avatars, visibility, party, ballot card, leaving line) while the place forgot
1207
+ // it, so those are marked stale and sent again, clearing what the place no
1208
+ // longer says.
1209
+ const HELLO_LATE_MS = 3000;
1210
+ // Matches no JSON a channel sends, so its next send goes out whatever it holds.
1211
+ const STALE = '\u0000stale';
1212
+ const FORGOTTEN_MS = 10 * 60 * 1000;
1213
+ function greetLate(h) {
1214
+ const now = h.sim.timeMs;
1215
+ if (!Number.isFinite(now)) {
1216
+ return;
1217
+ }
1218
+ const since = (h.noHelloSince ??= new Map());
1219
+ for (const id of [...since.keys()]) {
1220
+ if (!h.session?.players.some((p) => p.playerId === id) || h.players.get(id)?.hello) {
1221
+ since.delete(id);
1222
+ }
1223
+ }
1224
+ for (const [id, last] of h.forgotten ?? []) {
1225
+ if (now - last.at > FORGOTTEN_MS) {
1226
+ h.forgotten.delete(id);
1227
+ }
1228
+ }
1229
+ if (h.place?.result && h.place.resume !== true) {
1230
+ return;
1231
+ }
1232
+ for (const { playerId } of h.session?.players ?? []) {
1233
+ if (!h.forgotten?.has(playerId) || !h.sim.players.has(playerId) || h.players.get(playerId)?.hello) {
1234
+ continue;
1235
+ }
1236
+ const first = since.get(playerId);
1237
+ if (first === undefined) {
1238
+ since.set(playerId, now);
1239
+ continue;
1240
+ }
1241
+ if (now - first < HELLO_LATE_MS) {
1242
+ continue;
1243
+ }
1244
+ since.delete(playerId);
1245
+ hello(h, { playerId }, { k: 'hub-hello', avatar: h.forgotten.get(playerId).clientAvatar, ...(h.forgotten.get(playerId).clientColor ? { color: h.forgotten.get(playerId).clientColor } : {}), party: 1, resume: true });
1246
+ }
1247
+ }
1248
+
1249
+ // What a returning player's client still holds from before the place let it
1250
+ // go: each private channel is marked stale so its next send goes out, clearing
1251
+ // what the place no longer says. Run by `hello` for a player it let go,
1252
+ // whichever hello (the late greet's or the client's own) comes first.
1253
+ // `forgotten` false (v1.72, a resume place's player it still holds): the
1254
+ // leaving line is left to `hello`, which re-sends one that is set.
1255
+ function staleSent(h, playerId, forgotten = true) {
1256
+ for (const sent of [h.sentHudMe, h.sentLabelsMe, h.sentTunes, h.sentAvMe]) {
1257
+ sent?.set(playerId, STALE);
1258
+ }
1259
+ (h.sentVisMe ??= new Map()).set(playerId, STALE);
1260
+ h.party?.sent.set(playerId, STALE);
1261
+ if (!forgotten) {
1262
+ return;
1263
+ }
1264
+ // The leaving line has no cache: it goes out only when set, so clear it here.
1265
+ try {
1266
+ h.session?.send(playerId, { k: 'hub-leaving', text: null });
1267
+ } catch {
1268
+ // A connection that went meanwhile holds nothing.
1269
+ }
1270
+ }
1271
+
1272
+ // A fresh client holds none of its private channels. Only a non-empty last
1273
+ // send needs replaying; an unused or already empty channel stays quiet.
1274
+ // `held` (a resume hello): the client kept what it held and may have missed a
1275
+ // clear while away, so every channel ever sent goes again, empty ones too.
1276
+ function replaySent(h, playerId, held = false) {
1277
+ for (const [sent, empty] of [
1278
+ [h.sentHudMe, 'null'],
1279
+ [h.sentLabelsMe, '{}'],
1280
+ [h.sentTunes, 'null'],
1281
+ [h.sentAvMe, '{}'],
1282
+ ]) {
1283
+ if (sent?.has(playerId) && (held || sent.get(playerId) !== empty)) {
1284
+ sent.set(playerId, STALE);
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // Initial visibility can arrive after hello but before the player's body or
1290
+ // deck arrive hook. Keep its latest state and deliver only after arrival.
1291
+ function notifyVisibility(h, only = null) {
1292
+ for (const [playerId, entry] of only ? [[only, h.players.get(only)]] : h.players) {
1293
+ if (!entry?.visibilityPending || !entry.arrived || !h.sim?.players.has(playerId)) {continue;}
1294
+ entry.visibilityPending = false;
1295
+ try {
1296
+ const result = h.hooks.visibility?.(h.ctx, { playerId, ...entry.visibility });
1297
+ result?.catch?.(() => console.warn('[hub] visibility hook failed'));
1298
+ } catch {
1299
+ console.warn('[hub] visibility hook failed');
1300
+ }
1301
+ }
1302
+ }
1303
+
1304
+ // Dispatch after this step's private channels, once per id per step. A hook
1305
+ // may queue another hello; that belongs to the next step, not this drain.
1306
+ function notifyResumes(h) {
1307
+ if (!h.resumePending?.size) {
1308
+ return;
1309
+ }
1310
+ const pending = [...h.resumePending];
1311
+ h.resumePending.clear();
1312
+ for (const [playerId, entry] of pending) {
1313
+ if (h.players.get(playerId) !== entry || !entry.arrived || !h.sim.players.has(playerId) || !h.session?.players.some((p) => p.playerId === playerId)) {
1314
+ continue;
1315
+ }
1316
+ try {
1317
+ const result = h.hooks.resume(h.ctx, { playerId });
1318
+ if (result && typeof result.catch === 'function') {
1319
+ result.catch(() => console.warn('[hub] resume hook failed'));
1320
+ }
1321
+ } catch {
1322
+ console.warn('[hub] resume hook failed');
658
1323
  }
659
1324
  }
660
1325
  }
661
1326
 
662
1327
  function forget(h, playerId) {
1328
+ h.resumePending?.delete(playerId);
1329
+ h.resumeKept?.delete(playerId);
1330
+ h.resumeDeparting?.delete(playerId);
663
1331
  const entry = h.players.get(playerId);
664
1332
  if (entry?.arrived) {
665
1333
  // A place's hook that throws still lets the player go, once.
@@ -669,12 +1337,38 @@ function forget(h, playerId) {
669
1337
  console.warn(`[hub] leave hook failed: ${err?.message ?? err}`);
670
1338
  }
671
1339
  }
1340
+ // After the leave hook, which may have reported the visit's result.
1341
+ if (entry?.hello) {
1342
+ const kept = { clientAvatar: entry.clientAvatar, clientColor: entry.clientColor, at: h.sim.timeMs };
1343
+ // v1.72: a game that resumes keeps what its re-arrival must not lose (the
1344
+ // invariants at `hello`): the result (I1), the deadline (I2), the end
1345
+ // (I3) and the door (I4).
1346
+ if (h.place?.result && h.place.resume === true && h.place.resumeKeep !== true) {
1347
+ Object.assign(kept, {
1348
+ result: entry.result ?? null,
1349
+ ended: entry.ended === true,
1350
+ endWhy: entry.endWhy,
1351
+ visitAt: entry.visitAt,
1352
+ from: entry.from ?? null,
1353
+ fromDeckId: entry.fromDeckId ?? null,
1354
+ });
1355
+ }
1356
+ (h.forgotten ??= new Map()).set(playerId, kept);
1357
+ }
672
1358
  Party.forget(h, playerId);
673
1359
  Say.forget(h, playerId);
1360
+ if (h.ballotState) {
1361
+ Ballot.forget(h, playerId);
1362
+ }
1363
+ Friends.forget(h, playerId);
1364
+ h.caps.delete(playerId);
1365
+ h.capAt.delete(playerId);
1366
+ h.playerCells.delete(playerId);
674
1367
  h.players.delete(playerId);
675
1368
  h.held.delete(playerId);
676
1369
  h.hudMe.delete(playerId);
677
1370
  h.sentHudMe.delete(playerId);
1371
+ h.leaving.delete(playerId);
678
1372
  h.tunes.delete(playerId);
679
1373
  h.sentTunes.delete(playerId);
680
1374
  h.labelsMe.delete(playerId);
@@ -682,12 +1376,33 @@ function forget(h, playerId) {
682
1376
  h.sentAvMe.delete(playerId);
683
1377
  h.marks.delete(playerId);
684
1378
  Wear.forget(h, playerId);
1379
+ Earned.forget(h, playerId);
685
1380
  h.shut.delete(playerId);
686
1381
  h.jumpAt.delete(playerId);
687
1382
  h.whereAt.delete(playerId);
1383
+ h.unstuckAt?.delete(playerId);
1384
+ h.unstuckAskAt?.delete(playerId);
688
1385
  h.settling.delete(playerId);
689
1386
  Grab.forget(h, playerId);
690
1387
  Idle.forget(h, playerId);
1388
+ Decor.forget(h, playerId);
1389
+ if (h.place.actions === true) {
1390
+ Actions.forget(h, playerId);
1391
+ }
1392
+ if (h.place.companion === true) {
1393
+ Companion.forget(h, playerId);
1394
+ }
1395
+ if (h.place.ask === true) {
1396
+ Ask.forget(h, playerId);
1397
+ }
1398
+ if (h.place.menu === true) {
1399
+ Menu.forget(h, playerId);
1400
+ }
1401
+ if (h.cueBudgets) {
1402
+ h.cueBudgets.delete(`player:${playerId}`);
1403
+ }
1404
+ Shot.forgetPlayer(h, playerId);
1405
+ Vis.forget(h, playerId);
691
1406
  Cabinets.forget(h, playerId);
692
1407
  h.npcs.leave(playerId);
693
1408
  }
@@ -706,10 +1421,16 @@ async function shutdown(h) {
706
1421
  for (const playerId of [...h.players.keys()]) {
707
1422
  forget(h, playerId);
708
1423
  }
1424
+ if (Wear.tryOnUsed(h)) {
1425
+ Wear.endTries(h);
1426
+ }
709
1427
  let timer = null;
710
1428
  await Promise.race([
711
1429
  Promise.resolve()
712
- .then(() => h.hooks.shutdown?.(h.ctx))
1430
+ .then(async () => {
1431
+ await h.hooks.shutdown?.(h.ctx);
1432
+ await Promise.all([...(h.friendBestHelpers?.values() ?? [])].map((helper) => helper.drain()));
1433
+ })
713
1434
  .catch((err) => console.warn(`[hub] shutdown hook failed: ${err?.message ?? err}`)),
714
1435
  new Promise((resolve) => {
715
1436
  timer = setTimeout(resolve, SHUTDOWN_DRAIN_MS);
@@ -750,6 +1471,10 @@ function arrivals(h) {
750
1471
  const group = waiting.map(([playerId, entry]) => {
751
1472
  entry.arrived = true;
752
1473
  entry.arrivedAt = h.sim.timeMs;
1474
+ // v1.72 (I2): a resume place's visit has one deadline, from its first arrival.
1475
+ if (h.place.resume === true && h.place.result) {
1476
+ entry.visitAt ??= entry.arrivedAt;
1477
+ }
753
1478
  if (h.held.get(playerId)?.waiting) {
754
1479
  h.held.delete(playerId);
755
1480
  }
@@ -766,24 +1491,65 @@ function arrivals(h) {
766
1491
  party: entry.party ?? 1,
767
1492
  };
768
1493
  });
1494
+ const waitedAt = new Map(group.map((g) => [g.playerId, { ...h.sim.players.get(g.playerId)?.at }]));
769
1495
  placeGroup(h, group.map((g) => g.playerId));
770
1496
  placeNearFriends(h, group);
1497
+ // v1.67: a dev house keeps its first arrival as owner for this session.
1498
+ if (!platformHub(h) && isDevSession(h) && h.manifest.house?.devOwner === 'first' && !h.devOwnerChosen) {
1499
+ h.devOwnerChosen = true;
1500
+ h.devOwner = group[0]?.userId ?? null;
1501
+ }
771
1502
  h.hooks.arrive?.(h.ctx, group);
772
1503
  for (const { playerId } of group) {
773
1504
  const body = h.sim.players.get(playerId);
774
1505
  if (body) {
1506
+ // v1.40: kept where the arrival put them, like a jump. A player waits
1507
+ // for their group at the scene's spawn, where their client agrees they
1508
+ // are; placed, that client's reports still on their way name the spawn
1509
+ // and each pulled the body a step back toward it: four back from Tag
1510
+ // were dragged 2 to 3 m off the spots the town gave them, two onto the
1511
+ // next door's pad, and were taken into its game. Only one the arrival
1512
+ // moved: a player placed where they waited has no stale report to be
1513
+ // pulled by. (A place's hold is its own spot and is left alone.)
1514
+ const was = waitedAt.get(playerId);
1515
+ if (Math.hypot(body.at.x - was.x, body.at.z - was.z) > HOLD_SLACK) {
1516
+ settle(h, playerId);
1517
+ }
775
1518
  h.session?.send(playerId, { k: 'hub-arrived', facing: body.facing });
776
1519
  }
1520
+ if (h.players.get(playerId)?.endAgain) {
1521
+ delete h.players.get(playerId).endAgain;
1522
+ endAgain(h, playerId);
1523
+ }
777
1524
  }
778
1525
  }
779
1526
 
780
- // A row at the arrival actor, facing the way the manifest says.
781
- function placeGroup(h, playerIds) {
1527
+ // v1.72 (I3): the end of a resume place's visit, again, to a client a drop
1528
+ // may have kept it from (`again`: a client already ending keeps its pause).
1529
+ function endAgain(h, playerId) {
1530
+ const entry = h.players.get(playerId);
1531
+ if (!entry?.ended) {
1532
+ return;
1533
+ }
1534
+ h.held.delete(playerId);
1535
+ Shot.stopHolding(h, playerId);
1536
+ h.session?.send(playerId, { k: 'hub-end', why: entry.endWhy ?? 'end', again: true });
1537
+ }
1538
+
1539
+ // Where the place's players arrive: the arrival actor's Transform, else the
1540
+ // scene's spawn.
1541
+ function arrivalPoint(h) {
782
1542
  const arrival = h.place.arrival;
783
1543
  const actor = arrival.actor
784
1544
  ? h.actors.find((a) => a.id === arrival.actor)
785
1545
  : h.actors.find((a) => a.components.Player);
786
- const t = actor?.components.Transform ?? h.sim.spawn ?? { x: 0, y: 1, z: 0 };
1546
+ return actor?.components.Transform ?? h.sim?.spawn ?? { x: 0, y: 1, z: 0 };
1547
+ }
1548
+
1549
+ // A row at the arrival actor, facing the way the manifest says.
1550
+ function placeGroup(h, playerIds) {
1551
+ const arrival = h.place.arrival;
1552
+ const t = arrivalPoint(h);
787
1553
  let facing;
788
1554
  if (typeof arrival.face === 'number') {
789
1555
  facing = arrival.face * DEG;
@@ -797,7 +1563,8 @@ function placeGroup(h, playerIds) {
797
1563
  const n = playerIds.length;
798
1564
  playerIds.forEach((playerId, i) => {
799
1565
  const offset = (i - (n - 1) / 2) * arrival.spread;
800
- placeAt(h, playerId, { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset }, facing);
1566
+ const at = { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset };
1567
+ placeAt(h, playerId, { ...at, y: standingY(h, at) }, facing);
801
1568
  });
802
1569
  }
803
1570
 
@@ -917,6 +1684,14 @@ function footprintHas(shape, t, at, pad) {
917
1684
  // Move a body. One placed before the joiner's WORLD snapshot is where that
918
1685
  // snapshot starts them; a later one reaches the client as a clamp.
919
1686
  function placeAt(h, playerId, at, facing) {
1687
+ // A new placement is where the player is now: whatever was keeping them at
1688
+ // an earlier one (v1.40: an arrival's) lets go, so a place that puts a
1689
+ // player somewhere just after they arrive is not undone.
1690
+ h.settling.delete(playerId);
1691
+ moveBody(h, playerId, at, facing);
1692
+ }
1693
+
1694
+ function moveBody(h, playerId, at, facing) {
920
1695
  const body = h.sim?.players.get(playerId);
921
1696
  if (!body || !at || ![at.x, at.y, at.z].every(Number.isFinite)) {
922
1697
  return;
@@ -929,8 +1704,8 @@ function placeAt(h, playerId, at, facing) {
929
1704
  body.body.setTranslation(body.at, true);
930
1705
  }
931
1706
 
932
- // After a jump (to a door's pad, beside a player) the body is kept where it
933
- // was put for a moment. The client's move reports already on their way still
1707
+ // After a jump (to a door's pad, beside a player) or an arrival (v1.40) the
1708
+ // body is kept where it was put for a moment. The client's move reports already on their way still
934
1709
  // name the spot it left, and the server's movement clamp lets each one pull
935
1710
  // the body a step back toward it: on a slow phone that dragged a player a
936
1711
  // metre or two off the pad they had just been put on, and the pad never
@@ -956,7 +1731,7 @@ function enforceSettle(h) {
956
1731
  continue;
957
1732
  }
958
1733
  if (Math.hypot(body.at.x - spot.at.x, body.at.z - spot.at.z) > HOLD_SLACK) {
959
- placeAt(h, playerId, spot.at, spot.facing);
1734
+ moveBody(h, playerId, spot.at, spot.facing);
960
1735
  }
961
1736
  }
962
1737
  }
@@ -1005,7 +1780,7 @@ function enforceDuration(h) {
1005
1780
  }
1006
1781
  const limit = h.place.maxDurationSec * 1000;
1007
1782
  for (const [playerId, entry] of h.players) {
1008
- if (entry.arrived && !entry.ended && h.sim.timeMs - entry.arrivedAt >= limit) {
1783
+ if (entry.arrived && !entry.ended && h.sim.timeMs - (entry.visitAt ?? entry.arrivedAt) >= limit) {
1009
1784
  console.log(`[hub] ${usernameOf(h, playerId)} reached maxDurationSec`);
1010
1785
  end(h, playerId, 'time');
1011
1786
  }
@@ -1056,8 +1831,13 @@ function end(h, playerId, why) {
1056
1831
  const entry = h.players.get(playerId);
1057
1832
  if (entry) {
1058
1833
  entry.ended = true;
1834
+ // v1.72 (I3): kept to say it again on resume.
1835
+ if (h.place.resume === true && h.place.result) {
1836
+ entry.endWhy = why;
1837
+ }
1059
1838
  }
1060
1839
  h.held.delete(playerId);
1840
+ Shot.stopHolding(h, playerId);
1061
1841
  h.session?.send(playerId, { k: 'hub-end', why });
1062
1842
  }
1063
1843
 
@@ -1079,13 +1859,17 @@ function jumpDoors(h) {
1079
1859
  // The Doors list's rows. An event gate leads to a game another door already
1080
1860
  // leads to, so it is listed only while its event is open, and as the event
1081
1861
  // (two rows reading "King of the Hill" was one too many).
1862
+ function listedDoors(h) {
1863
+ return jumpDoors(h).filter((door) => {
1864
+ const event = h.boards.get(door.id)?.event;
1865
+ return !event || event.open;
1866
+ });
1867
+ }
1868
+
1082
1869
  function doorList(h) {
1083
1870
  const out = [];
1084
- for (const door of jumpDoors(h)) {
1871
+ for (const door of listedDoors(h)) {
1085
1872
  const event = h.boards.get(door.id)?.event;
1086
- if (event && !event.open) {
1087
- continue;
1088
- }
1089
1873
  const row = { id: door.id, title: event ? `Event · ${door.title}`.slice(0, 48) : door.title };
1090
1874
  // What a player picking a door wants to know: today's featured door (it
1091
1875
  // is listed first), one that takes a single player, how many it needs.
@@ -1126,17 +1910,232 @@ function doorJump(h, player, data) {
1126
1910
  // two who jump there do not land in one spot; else in front of the door.
1127
1911
  const at = Party.padPoint(h, door, Math.floor(Math.random() * 6), player.playerId) ?? frontOf(door);
1128
1912
  const facing = ((door.t.rotationY ?? 0) + 180) * DEG;
1129
- placeAt(h, player.playerId, { x: at.x, y: 1.2, z: at.z }, facing);
1913
+ placeAt(h, player.playerId, { x: at.x, y: standingY(h, { ...at, y: 1.2 }), z: at.z }, facing);
1130
1914
  settle(h, player.playerId);
1131
1915
  h.session?.send(player.playerId, { k: 'hub-jumped', facing });
1132
1916
  }
1133
1917
 
1918
+ // "Stuck?" (v1.33): whether this place puts a player back at its arrival for
1919
+ // the asking. A deck with `hub.stuck`, and a town only: in a game (a place
1920
+ // with a `result`) the way to the start is the game's to give or keep -- a
1921
+ // free one would be a way out of a trap, a tag or a lost position.
1922
+ function stuckHere(h) {
1923
+ return h.manifest.stuck === true && !h.place.result;
1924
+ }
1925
+
1926
+ // What the chip calls the arrival ("the square"), or null for none: the
1927
+ // place's own `where` words for the spot (§5: "in the square", "on Race Row",
1928
+ // "at the Arcade") without their first word. Words of another shape are not
1929
+ // guessed at.
1930
+ // Whether what a place's hook returned is an answer for later (a promise, or
1931
+ // anything with a callable `then`) rather than one given at once: the hooks
1932
+ // "Stuck?" asks are synchronous, and such a result is no answer. Its `then`
1933
+ // is never called -- that is running the place's code a second time, and an
1934
+ // `async then` that throws hands back a rejection of its own. A native
1935
+ // promise is the one thing that can reject with nobody having called
1936
+ // anything, so it alone is given a handler, by the built-in `then` (not the
1937
+ // object's own, which a place may have replaced); what that returns cannot
1938
+ // reject. Called inside the caller's catch: reading `then` may throw.
1939
+ function answersLater(result) {
1940
+ if (result === null || (typeof result !== 'object' && typeof result !== 'function')) {
1941
+ return false;
1942
+ }
1943
+ if (result instanceof Promise) {
1944
+ Promise.prototype.then.call(result, undefined, () => {});
1945
+ return true;
1946
+ }
1947
+ return typeof result.then === 'function';
1948
+ }
1949
+
1950
+ function arrivalName(h) {
1951
+ // The place's part is inside one catch, as `unstickSpot`'s is: this is said
1952
+ // in the answer to a tap, which nothing of the place's may stop. A promise
1953
+ // is no words (`answersLater`).
1954
+ try {
1955
+ const t = arrivalPoint(h);
1956
+ const words = h.hooks.where?.(h.ctx, { x: t.x, y: t.y ?? 1, z: t.z });
1957
+ if (answersLater(words)) {
1958
+ return null;
1959
+ }
1960
+ const name = typeof words === 'string' ? /^(?:in|on|at) (\S.*)$/.exec(words.trim())?.[1] : null;
1961
+ return name ? name.slice(0, WHERE_TEXT_MAX) : null;
1962
+ } catch (err) {
1963
+ try {
1964
+ console.warn(`[hub] where hook failed: ${err?.message ?? err}`);
1965
+ } catch {
1966
+ console.warn('[hub] where hook failed');
1967
+ }
1968
+ return null;
1969
+ }
1970
+ }
1971
+
1972
+ // Whether the place has the `unstick` hook (v1.39). Read behind a catch like
1973
+ // everything else of the place's: a hooks object may be anything.
1974
+ function hasUnstick(h) {
1975
+ try {
1976
+ return typeof h.hooks.unstick === 'function';
1977
+ } catch {
1978
+ return false;
1979
+ }
1980
+ }
1981
+
1982
+ // v1.39: where the place itself would put a player stuck where this one is
1983
+ // (its `unstick` hook, asked with the body's own position), as `{ at,
1984
+ // facing, to }`, or null for the arrival.
1985
+ //
1986
+ // The invariant: nothing the place returns or throws can stop a tap from
1987
+ // landing somewhere valid and answering. So the whole of the place's part --
1988
+ // the call, and every read of what it returned -- is inside one catch, and
1989
+ // what leaves it is either null or a spot made here of plain numbers and a
1990
+ // plain string, which nothing after it can make throw. Null is: no hook; a
1991
+ // hook that throws, or answers null; an answer whose fields cannot be read
1992
+ // (a getter that throws); a promise or any other thenable -- the hook is
1993
+ // synchronous (`answersLater`: a native promise is silenced so that its
1994
+ // rejection is not left unhandled to end the session's process, and nothing
1995
+ // else's `then` is ever called); and an answer that is
1996
+ // not a spot: `x` and `z` finite and inside the world box, `y` (default standing
1997
+ // height when proved clear and no higher, else 1.2, as an arrival's; v1.48)
1998
+ // and `facing` (degrees; default: as the body faces) finite where given.
1999
+ // `to` is the place's name for the spot, a string of up to 40 characters, or none.
2000
+ function unstickSpot(h, playerId) {
2001
+ const body = h.sim?.players.get(playerId);
2002
+ if (!body || !hasUnstick(h)) {
2003
+ return null;
2004
+ }
2005
+ try {
2006
+ const answer = h.hooks.unstick(h.ctx, playerId, { x: body.at.x, y: body.at.y, z: body.at.z });
2007
+ if (answer === null || answer === undefined) {
2008
+ return null;
2009
+ }
2010
+ if (answersLater(answer)) {
2011
+ console.warn('[hub] unstick hook: it must answer at once, not with a promise; the arrival is used');
2012
+ return null;
2013
+ }
2014
+ if (typeof answer !== 'object') {
2015
+ console.warn('[hub] unstick hook: not a spot ({ x, z } inside the world box); the arrival is used');
2016
+ return null;
2017
+ }
2018
+ // Each field read once, here, into a value of this function's own.
2019
+ const x = answer.x;
2020
+ const z = answer.z;
2021
+ const givenY = answer.y;
2022
+ const y = givenY === undefined && [x, z].every(Number.isFinite) ? standingY(h, { x, y: 1.2, z }) : givenY;
2023
+ const facing = answer.facing;
2024
+ const name = answer.to;
2025
+ const B = Actors.BOUNDS;
2026
+ if (
2027
+ ![x, y, z].every((v) => typeof v === 'number' && Number.isFinite(v)) || Math.abs(x) > B.xz || Math.abs(z) > B.xz || y < B.low || y > B.high ||
2028
+ (facing !== undefined && !(typeof facing === 'number' && Number.isFinite(facing)))
2029
+ ) {
2030
+ console.warn('[hub] unstick hook: not a spot ({ x, z } inside the world box); the arrival is used');
2031
+ return null;
2032
+ }
2033
+ const to = typeof name === 'string' && name.trim() ? name.trim().slice(0, WHERE_TEXT_MAX) : null;
2034
+ return { at: { x, y, z }, facing: facing === undefined ? undefined : facing * DEG, to };
2035
+ } catch (err) {
2036
+ try {
2037
+ console.warn(`[hub] unstick hook failed: ${err?.message ?? err}`);
2038
+ } catch {
2039
+ console.warn('[hub] unstick hook failed');
2040
+ }
2041
+ return null;
2042
+ }
2043
+ }
2044
+
2045
+ // Whether this player may be moved by "Stuck?" at all: in a town of a deck
2046
+ // with `hub.stuck`, here, arrived, and their visit not ended.
2047
+ function mayUnstick(h, playerId) {
2048
+ const entry = playerId ? h.players.get(playerId) : null;
2049
+ return stuckHere(h) && Boolean(h.sim?.players.has(playerId)) && Boolean(entry?.arrived) && !entry.ended;
2050
+ }
2051
+
2052
+ // v1.39: what a tap would do for this player now, asked by a client about to
2053
+ // show the chip (`{ k: 'hub-unstick', ask: true }`) so its words can say where
2054
+ // the tap goes. Only a place with the `unstick` hook is asked, and answers
2055
+ // (`hub-unstick-to`): once a second, to a player who may be moved and is not
2056
+ // held. Nobody is moved by it.
2057
+ function unstickAsk(h, player) {
2058
+ const playerId = player?.playerId;
2059
+ const now = Date.now();
2060
+ const last = (h.unstuckAskAt ??= new Map());
2061
+ if (!hasUnstick(h) || !mayUnstick(h, playerId) || h.held.has(playerId) || now - (last.get(playerId) ?? -Infinity) < JUMP_EVERY_MS) {
2062
+ return;
2063
+ }
2064
+ last.set(playerId, now);
2065
+ const spot = unstickSpot(h, playerId);
2066
+ h.session?.send(playerId, { k: 'hub-unstick-to', spot: Boolean(spot), to: spot ? spot.to : arrivalName(h) });
2067
+ }
2068
+
2069
+ // A player who asked to be moved (the chrome's "Stuck?" chip and Doors row):
2070
+ // to the spot the place picks for them (v1.39, its `unstick` hook), else to
2071
+ // the arrival by the fall rule's own placement (`placeGroup`), for that one
2072
+ // player. Never in a game, never a held player or one who has not arrived or
2073
+ // has ended, once in 5 s, and counted as a jump (so not within a second of
2074
+ // one). A sitter gets up first, as for any jump.
2075
+ function unstick(h, player) {
2076
+ const playerId = player?.playerId;
2077
+ const now = Date.now();
2078
+ const last = (h.unstuckAt ??= new Map());
2079
+ if (
2080
+ !mayUnstick(h, playerId) ||
2081
+ now - (last.get(playerId) ?? -Infinity) < UNSTICK_EVERY_MS ||
2082
+ now - (h.jumpAt.get(playerId) ?? 0) < JUMP_EVERY_MS
2083
+ ) {
2084
+ return;
2085
+ }
2086
+ Idle.stand(h, playerId);
2087
+ if (h.held.has(playerId)) {
2088
+ return;
2089
+ }
2090
+ // The place is asked before anything is spent, and cannot stop what
2091
+ // follows (`unstickSpot`): from here the player is moved and answered.
2092
+ const hooked = hasUnstick(h);
2093
+ const spot = hooked ? unstickSpot(h, playerId) : null;
2094
+ last.set(playerId, now);
2095
+ h.jumpAt.set(playerId, now);
2096
+ if (spot) {
2097
+ placeAt(h, playerId, spot.at, spot.facing);
2098
+ } else {
2099
+ placeGroup(h, [playerId]);
2100
+ }
2101
+ settle(h, playerId);
2102
+ h.session?.send(playerId, {
2103
+ k: 'hub-jumped',
2104
+ facing: h.sim.players.get(playerId)?.facing ?? 0,
2105
+ // v1.39, only from a place with the hook: where the player was put.
2106
+ ...(hooked ? { stuck: { spot: Boolean(spot), to: spot ? spot.to : arrivalName(h) } } : {}),
2107
+ });
2108
+ }
2109
+
1134
2110
  // A spot in front of a door, for a jump to a door with no pad.
1135
2111
  function frontOf(door) {
1136
2112
  const t = door.t;
1137
2113
  return doorPoint({ x: t.x, z: t.z, rotationY: t.rotationY ?? 0 }, (Math.random() - 0.5) * JUMP_SPREAD, JUMP_OUT);
1138
2114
  }
1139
2115
 
2116
+ // What `ballot.js` uses of this layer (v1.68): names and avatars are the
2117
+ // kit's own, never the deck's; a player not in the session is no face.
2118
+ function ballotDeps(h) {
2119
+ return {
2120
+ blockedPairs: () => blockedPairs(h),
2121
+ namesOf: (ids) => namesOf(h, ids),
2122
+ usernameOf: (playerId) => (h.sim?.players.has(playerId) ? h.session?.players.find((p) => p.playerId === playerId)?.username ?? null : null),
2123
+ avatarOf: (playerId) => (h.players.get(playerId)?.hello ? h.players.get(playerId).avatar : null),
2124
+ };
2125
+ }
2126
+
2127
+ // What `say.js` uses of this layer. A deck whose manifest sets `cues` (v1.23)
2128
+ // hands it more; any other hands it exactly what it did.
2129
+ function sayDeps(h) {
2130
+ const d = { h, blockedPairs, jumpDoors: doors };
2131
+ if (h.manifest.cues) {
2132
+ d.cues = true;
2133
+ d.goDoors = jumpDoors;
2134
+ d.proposalDoor = Party.proposalDoor;
2135
+ }
2136
+ return d;
2137
+ }
2138
+
1140
2139
  // What `party.js` uses of this layer.
1141
2140
  function partyDeps(h) {
1142
2141
  // A party member put on a pad is settled there like any jump.
@@ -1144,7 +2143,7 @@ function partyDeps(h) {
1144
2143
  placeAt(state, playerId, at, facing);
1145
2144
  settle(state, playerId);
1146
2145
  };
1147
- return { h, blockedPairs, usernameOf, placeAt: placeAndSettle, stand: Idle.stand, jumpDoors, front: frontOf };
2146
+ return { h, blockedPairs, usernameOf, standingY, placeAt: placeAndSettle, stand: Idle.stand, jumpDoors, front: frontOf };
1148
2147
  }
1149
2148
 
1150
2149
  // Where the players a client asks about are (the chrome's People list and its
@@ -1321,6 +2320,17 @@ function deckDoorPlace(h, props, deck) {
1321
2320
  };
1322
2321
  }
1323
2322
 
2323
+ // All outgoing travel paths retire the lease after sending the command.
2324
+ function sendGo(h, playerId, msg) {
2325
+ if (h.session?.send) {
2326
+ h.session.send(playerId, msg);
2327
+ Shot.stopHolding(h, playerId);
2328
+ // An explicit kit trip ends the visit rather than retaining it for a drop.
2329
+ h.resumeDeparting?.add(playerId);
2330
+ h.resumePending?.delete(playerId);
2331
+ }
2332
+ }
2333
+
1324
2334
  // Send players through one of this place's doors (contract §4), into a new
1325
2335
  // instance or, with `instance`, one this place sent players to before (a late
1326
2336
  // join). In dev the destination is a named session whose key names the place;
@@ -1370,7 +2380,7 @@ function go(h, door, playerIds, { instance } = {}) {
1370
2380
  typeof instance === 'string' && instance.startsWith(`${prefix}hub.${to}.`) ? instance : prefix + Place.devKey(to);
1371
2381
  tellWent(h, playerIds, door);
1372
2382
  for (const playerId of playerIds) {
1373
- h.session?.send(playerId, {
2383
+ sendGo(h, playerId, {
1374
2384
  k: 'hub-go',
1375
2385
  door,
1376
2386
  key,
@@ -1412,7 +2422,7 @@ function goLayer(h, door, playerIds) {
1412
2422
  return null;
1413
2423
  }
1414
2424
  for (const playerId of going) {
1415
- h.session?.send(playerId, {
2425
+ sendGo(h, playerId, {
1416
2426
  k: 'hub-go',
1417
2427
  door,
1418
2428
  key: null,
@@ -1445,7 +2455,7 @@ function goClassic(h, hub, door, playerIds) {
1445
2455
  return null;
1446
2456
  }
1447
2457
  for (const playerId of going) {
1448
- h.session?.send(playerId, {
2458
+ sendGo(h, playerId, {
1449
2459
  k: 'hub-go',
1450
2460
  door,
1451
2461
  classic: true,
@@ -1547,6 +2557,7 @@ function doorShut(h, player, data) {
1547
2557
  if (!playerId || !found) {
1548
2558
  return;
1549
2559
  }
2560
+ h.resumeDeparting?.delete(playerId);
1550
2561
  unshut(h, playerId);
1551
2562
  if (h.padDoors.has(found.id) && !h.padDoors.get(found.id).has(playerId)) {
1552
2563
  // Already stepped off while the trip was failing.
@@ -1629,7 +2640,7 @@ function padFired(h, door, pad, users, fired) {
1629
2640
  for (const userId of group) {
1630
2641
  const playerId = users.get(userId) ?? here.get(userId);
1631
2642
  if (playerId) {
1632
- h.session?.send(playerId, {
2643
+ sendGo(h, playerId, {
1633
2644
  k: 'hub-go',
1634
2645
  door,
1635
2646
  pad: pad.padId,
@@ -1664,7 +2675,14 @@ function readResults(h) {
1664
2675
  continue;
1665
2676
  }
1666
2677
  entry.read = 'reading';
1667
- users.set(userId, { playerId, avatarRev: entry.avatarRev, wearRev: h.wearRev.get(playerId) ?? 0, startedAt: Date.now() });
2678
+ users.set(userId, {
2679
+ playerId,
2680
+ avatarRev: entry.avatarRev,
2681
+ colorRev: entry.colorRev,
2682
+ wearRev: h.wearRev.get(playerId) ?? 0,
2683
+ earnedRev: h.earnedRev.get(playerId) ?? 0,
2684
+ startedAt: Date.now(),
2685
+ });
1668
2686
  }
1669
2687
  if (users.size) {
1670
2688
  hub
@@ -1685,34 +2703,66 @@ function readResults(h) {
1685
2703
  });
1686
2704
  }
1687
2705
  const now = Date.now();
1688
- if (now - h.boardsAt < BOARD_EVERY_MS) {
2706
+ if (h.boardsReading || now - h.boardsAt < BOARD_EVERY_MS) {
1689
2707
  return;
1690
2708
  }
1691
2709
  // A cabinet's board carries its pictures (v1.7), and a read answers in one
1692
2710
  // frame of the host's channel: cabinets are read apart from the doors, a
1693
- // few at a time. A place with none makes the one read it always did.
2711
+ // few at a time.
1694
2712
  const cabinets = Cabinets.cabinetDoorIds(h);
1695
2713
  const all = doors(h).map((d) => d.id);
1696
- const doorIds = all.filter((id) => !cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
1697
- const batches = doorIds.length ? [doorIds] : [];
1698
- const cabinetIds = all.filter((id) => cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
2714
+ const doorIds = all.filter((id) => !cabinets.has(id));
2715
+ const batches = [];
2716
+ for (let i = 0; i < doorIds.length; i += BOARD_DOORS_PER_READ) {
2717
+ batches.push(doorIds.slice(i, i + BOARD_DOORS_PER_READ));
2718
+ }
2719
+ const cabinetIds = all.filter((id) => cabinets.has(id));
1699
2720
  for (let i = 0; i < cabinetIds.length; i += CABINET_BOARDS_PER_READ) {
1700
2721
  batches.push(cabinetIds.slice(i, i + CABINET_BOARDS_PER_READ));
1701
2722
  }
1702
2723
  if (batches.length) {
1703
2724
  h.boardsAt = now;
1704
- Promise.all(batches.map((ids) => hub.readResults({ doorIds: ids })))
1705
- .then((reads) => {
1706
- h.boards = new Map(reads.flatMap((read) => Object.entries(read.boards ?? {})));
1707
- // Doors to other decks take their title and group from the boards,
1708
- // and a cabinet its card.
1709
- Cabinets.refresh(h, doors(h));
1710
- })
1711
- .catch((err) => refused(h, 'boards', err));
2725
+ h.boardsReading = true;
2726
+ readBoards(h, hub, batches)
2727
+ .catch((err) => refused(h, 'boards', err))
2728
+ .finally(() => {
2729
+ h.boardsReading = false;
2730
+ });
1712
2731
  }
1713
2732
  }
1714
2733
 
1715
- function applyRead(h, { playerId, avatarRev, wearRev, startedAt }, read) {
2734
+ // Storage requests share a small in-flight budget with other hub ops. Read
2735
+ // one batch at a time, keeping the previous boards of a batch that fails.
2736
+ async function readBoards(h, hub, batches) {
2737
+ const boards = new Map(h.boards);
2738
+ for (const ids of batches) {
2739
+ try {
2740
+ const read = await hub.readResults({ doorIds: ids });
2741
+ const rows = Object.entries(read.boards ?? {});
2742
+ for (const id of ids) {
2743
+ boards.delete(id);
2744
+ }
2745
+ for (const [id, board] of rows) {
2746
+ boards.set(id, board);
2747
+ }
2748
+ h.boards = boards;
2749
+ } catch (err) {
2750
+ refused(h, 'boards', err);
2751
+ }
2752
+ }
2753
+ const listed = new Set(doors(h).map((d) => d.id));
2754
+ for (const id of boards.keys()) {
2755
+ if (!listed.has(id)) {
2756
+ boards.delete(id);
2757
+ }
2758
+ }
2759
+ h.boards = boards;
2760
+ // Doors to other decks take their title and group from the boards,
2761
+ // and a cabinet its card, even when another batch failed.
2762
+ Cabinets.refresh(h, doors(h));
2763
+ }
2764
+
2765
+ function applyRead(h, { playerId, avatarRev, colorRev, wearRev, earnedRev, startedAt }, read) {
1716
2766
  const entry = h.players.get(playerId);
1717
2767
  if (!entry || !read) {
1718
2768
  return;
@@ -1721,10 +2771,19 @@ function applyRead(h, { playerId, avatarRev, wearRev, startedAt }, read) {
1721
2771
  History.take(h, playerId, read, startedAt);
1722
2772
  // The wearable likewise, unless the game put one on since (v1.4).
1723
2773
  Wear.applyRead(h, playerId, wearRev, read);
2774
+ // The earned item likewise, unless an unlock or choice was made since (v1.53).
2775
+ Earned.applyRead(h, playerId, earnedRev, read);
1724
2776
  // The platform avatar, unless the client chose another since the read began.
1725
2777
  if (Number.isInteger(read.avatar) && read.avatar >= 0 && read.avatar < AVATARS && entry.avatarRev === avatarRev) {
2778
+ if (entry.avatar !== read.avatar) {
2779
+ // A colour queued for the previous character cannot follow a new body.
2780
+ entry.color = cleanAvatarColor(read.avatarColor);
2781
+ }
1726
2782
  entry.avatar = read.avatar;
1727
2783
  }
2784
+ if (entry.colorRev === colorRev) {
2785
+ entry.color = cleanAvatarColor(read.avatarColor);
2786
+ }
1728
2787
  const row = entry.fromDeckId
1729
2788
  ? (read.recent ?? []).find((r) => r.deckId === entry.fromDeckId && Date.now() - Date.parse(r.at) < RESULT_FRESH_MS)
1730
2789
  : null;
@@ -1756,6 +2815,30 @@ function refused(h, op, err) {
1756
2815
  }
1757
2816
  }
1758
2817
 
2818
+ // A place's next-visit line (v1.52), latched for its player alone. Send now
2819
+ // so a subsequent hub.go or hub.end cannot overtake the line.
2820
+ function leaving(h, playerId, text) {
2821
+ if (typeof playerId !== 'string' || !(h.players.has(playerId) || h.sim?.players.has(playerId))) {
2822
+ refused(h, 'leaving', { code: 'player', message: 'a player here is required' });
2823
+ return false;
2824
+ }
2825
+ if (text !== null && typeof text !== 'string') {
2826
+ refused(h, 'leaving', { code: 'text', message: 'text must be a string or null' });
2827
+ return false;
2828
+ }
2829
+ const line = text === null ? null : text.trim().slice(0, HUD_LIMITS.text) || null;
2830
+ if ((h.leaving.get(playerId) ?? null) === line) {
2831
+ return true;
2832
+ }
2833
+ if (line === null) {
2834
+ h.leaving.delete(playerId);
2835
+ } else {
2836
+ h.leaving.set(playerId, line);
2837
+ }
2838
+ h.session?.send(playerId, { k: 'hub-leaving', text: line });
2839
+ return true;
2840
+ }
2841
+
1759
2842
  // Per-player HUD overrides go to their player alone, when they change. Where
1760
2843
  // a block hides players, each player is also sent the shared HUD as they may
1761
2844
  // read it, when that names someone the shared one leaves out.
@@ -1898,16 +2981,81 @@ function labelsOf(h) {
1898
2981
  // Every helloed player's avatar, for everyone: all but the players a block
1899
2982
  // hides from someone here, whose avatars go to each player who may see them
1900
2983
  // alone (`sendAvatarOverrides`).
2984
+ //
2985
+ // `hubAv` only ever carries one of the first four (v1.51): a client from
2986
+ // before the twelve has no blueprint for another and would not draw the
2987
+ // player at all, so one who wears 4-15 is listed there as `avatar % 4`, the
2988
+ // stand-in a v1.51 client draws for an index past its own. Who really wears
2989
+ // what is `hubAv2`, below.
1901
2990
  function avatars(h, hidden) {
1902
2991
  const out = {};
1903
2992
  for (const [playerId, entry] of h.players) {
1904
2993
  if (entry.hello && !hidden?.has(playerId)) {
2994
+ out[playerId] = standIn(entry.avatar);
2995
+ }
2996
+ }
2997
+ return out;
2998
+ }
2999
+
3000
+ function standIn(avatar) {
3001
+ return avatar < OLD_AVATARS ? avatar : avatar % OLD_AVATARS;
3002
+ }
3003
+
3004
+ // `hubAv2` (v1.51): the avatar of each player who wears one past the first
3005
+ // four, by `hubAv`'s rules of who is listed. A client that knows it draws
3006
+ // that; one from before ignores it and draws `hubAv`'s stand-in.
3007
+ function avatars2(h, hidden) {
3008
+ const out = {};
3009
+ for (const [playerId, entry] of h.players) {
3010
+ if (entry.hello && !hidden?.has(playerId) && entry.avatar >= OLD_AVATARS) {
1905
3011
  out[playerId] = entry.avatar;
1906
3012
  }
1907
3013
  }
1908
3014
  return out;
1909
3015
  }
1910
3016
 
3017
+ // In the snapshot only while someone wears one; in deltas from the first one
3018
+ // on, and `{}` once when the last is gone, so a client that had the block
3019
+ // hears that it is empty. A place where nobody ever wears one never sends the
3020
+ // key: its bytes are what they were before v1.51.
3021
+ function avatars2ForJoin(h) {
3022
+ const real = avatars2(h, blockedPairs(h));
3023
+ return Object.keys(real).length ? { hubAv2: real } : {};
3024
+ }
3025
+
3026
+ function latchAvatars2(h, out) {
3027
+ const real = avatars2(h, blockedPairs(h));
3028
+ if (Object.keys(real).length || h.sent.has('hubAv2')) {
3029
+ latch(h, 'hubAv2', real, out);
3030
+ }
3031
+ }
3032
+
3033
+ function cleanAvatarColor(color) {
3034
+ return Number.isInteger(color) && color >= 0 && color < 16 ? color : 0;
3035
+ }
3036
+
3037
+ function avatarColors(h, hidden) {
3038
+ const out = {};
3039
+ for (const [playerId, entry] of h.players) {
3040
+ if (entry.hello && !hidden?.has(playerId) && entry.color > 0) {
3041
+ out[playerId] = entry.color;
3042
+ }
3043
+ }
3044
+ return out;
3045
+ }
3046
+
3047
+ function avatarColorsForJoin(h) {
3048
+ const colors = avatarColors(h, blockedPairs(h));
3049
+ return Object.keys(colors).length ? { hubAvC: colors } : {};
3050
+ }
3051
+
3052
+ function latchAvatarColors(h, out) {
3053
+ const colors = avatarColors(h, blockedPairs(h));
3054
+ if (Object.keys(colors).length || h.sent.has('hubAvC')) {
3055
+ latch(h, 'hubAvC', colors, out);
3056
+ }
3057
+ }
3058
+
1911
3059
  // Who a block hides from whom (`blocks.js`), asked of the host once a tick
1912
3060
  // and again when the roster changes.
1913
3061
  function blockedPairs(h) {
@@ -1925,16 +3073,30 @@ function sendAvatarOverrides(h) {
1925
3073
  const hidden = blockedPairs(h);
1926
3074
  for (const playerId of h.sim.players.keys()) {
1927
3075
  const out = {};
3076
+ // v1.51: as `hubAv` and `hubAv2` are, the stand-in for everyone and the
3077
+ // avatar really worn beside it, the second only when there is one.
3078
+ const real = {};
3079
+ const colors = {};
1928
3080
  for (const shrouded of hidden?.keys() ?? []) {
1929
3081
  const entry = h.players.get(shrouded);
1930
3082
  if (entry?.hello && !hidden.get(playerId)?.has(shrouded)) {
1931
- out[shrouded] = entry.avatar;
3083
+ out[shrouded] = standIn(entry.avatar);
3084
+ if (entry.color > 0) {
3085
+ colors[shrouded] = entry.color;
3086
+ }
3087
+ if (entry.avatar >= OLD_AVATARS) {
3088
+ real[shrouded] = entry.avatar;
3089
+ }
1932
3090
  }
1933
3091
  }
1934
- const json = JSON.stringify(out);
3092
+ // The message is the whole of what this player is told here: one without
3093
+ // `hubAv2` says nobody in it wears one of the twelve (any more).
3094
+ const some = Object.keys(real).length > 0;
3095
+ const colored = Object.keys(colors).length > 0;
3096
+ const json = colored ? JSON.stringify([out, real, colors]) : some ? JSON.stringify([out, real]) : JSON.stringify(out);
1935
3097
  if ((h.sentAvMe.get(playerId) ?? '{}') !== json) {
1936
3098
  h.sentAvMe.set(playerId, json);
1937
- h.session?.send(playerId, { k: 'hub-av', hubAv: out });
3099
+ h.session?.send(playerId, { k: 'hub-av', hubAv: out, ...(some ? { hubAv2: real } : {}), ...(colored ? { hubAvC: colors } : {}) });
1938
3100
  }
1939
3101
  }
1940
3102
  }
@@ -1963,7 +3125,66 @@ function latchWearing(h, out) {
1963
3125
  }
1964
3126
  }
1965
3127
 
3128
+ // What `hub.unlock` and `hub.wearEarned` (v1.53) are handed.
3129
+ function earnedDeps(h, playerId, op) {
3130
+ return {
3131
+ platform: platformHub(h),
3132
+ userId: userIdOf(h, playerId),
3133
+ declared: h.unlocks,
3134
+ deckId: h.deckId,
3135
+ refused: (err) => refused(h, op, err),
3136
+ };
3137
+ }
3138
+
3139
+ // `hubEarned` (v1.53) as `hubWear` goes: in the snapshot only while someone
3140
+ // shows an earned item, in deltas from the first one on.
3141
+ function earnedForJoin(h) {
3142
+ const earned = Earned.earnedForAll(h, blockedPairs(h));
3143
+ return Object.keys(earned).length ? { hubEarned: earned } : {};
3144
+ }
3145
+
3146
+ function latchEarned(h, out) {
3147
+ const earned = Earned.earnedForAll(h, blockedPairs(h));
3148
+ if (Object.keys(earned).length || h.sent.has('hubEarned')) {
3149
+ latch(h, 'hubEarned', earned, out);
3150
+ }
3151
+ }
3152
+
3153
+ // `hubTry` (v1.28) the same way: in the snapshot only while a try-on is
3154
+ // shown, in deltas from the first one on, `{}` once when the last is gone.
3155
+ function tryingForJoin(h) {
3156
+ const trying = Wear.tryingOf(h, blockedPairs(h));
3157
+ return Object.keys(trying).length ? { hubTry: trying } : {};
3158
+ }
3159
+
3160
+ function latchTrying(h, out) {
3161
+ const trying = Wear.tryingOf(h, blockedPairs(h));
3162
+ if (Object.keys(trying).length || h.sent.has('hubTry')) {
3163
+ latch(h, 'hubTry', trying, out);
3164
+ }
3165
+ }
3166
+
1966
3167
  function latch(h, field, value, out) {
3168
+ if (h.cells && ['labels', 'tints', 'marks'].includes(field)) {
3169
+ const previous = h.sentMaps.get(field) ?? {};
3170
+ const next = Object.fromEntries(Object.entries(value).map(([id, v]) => [id, JSON.stringify(v)]));
3171
+ const delta = Object.create(null);
3172
+ for (const [id, json] of Object.entries(next)) {
3173
+ if (previous[id] !== json) {
3174
+ delta[id] = value[id];
3175
+ }
3176
+ }
3177
+ for (const id of Object.keys(previous)) {
3178
+ if (!Object.hasOwn(next, id)) {
3179
+ delta[id] = null;
3180
+ }
3181
+ }
3182
+ h.sentMaps.set(field, next);
3183
+ if (Object.keys(delta).length) {
3184
+ out[`${field}D`] = delta;
3185
+ }
3186
+ return;
3187
+ }
1967
3188
  const json = JSON.stringify(value);
1968
3189
  if (h.sent.get(field) !== json) {
1969
3190
  h.sent.set(field, json);
@@ -1971,6 +3192,50 @@ function latch(h, field, value, out) {
1971
3192
  }
1972
3193
  }
1973
3194
 
3195
+ // Both hooks share one body-cell and camera-neighbour lookup per tick.
3196
+ function playerCells(h, sim) {
3197
+ if (h.cellTick === sim.timeMs && h.cellViews) {
3198
+ return h.cellViews;
3199
+ }
3200
+ h.cellTick = sim.timeMs;
3201
+ h.cellViews = new Map();
3202
+ for (const [id, player] of sim.players) {
3203
+ const at = player.at;
3204
+ const cell = Cells.cellAt(h.cells, at.x, at.z, h.playerCells.get(id));
3205
+ h.playerCells.set(id, cell);
3206
+ h.cellViews.set(id, { cell, visible: Cells.visibleCells(h.cells, at.x, at.z) });
3207
+ }
3208
+ return h.cellViews;
3209
+ }
3210
+
3211
+ function cellPlayers(h, sim, known, hidden) {
3212
+ const views = playerCells(h, sim);
3213
+ const userIds = new Map([...sim.players.keys()].map((id) => [id, userIdOf(h, id)]));
3214
+ const sees = new Map();
3215
+ const now = Date.now();
3216
+ for (const [viewer, view] of views) {
3217
+ const cached = h.friendsCache?.get(viewer);
3218
+ const entry = cached && now - cached.at < cached.ttl ? cached : null;
3219
+ const friends = new Set([
3220
+ ...(entry?.ids ?? []), ...(entry?.follows ?? []), ...(entry?.followedBy ?? []),
3221
+ ]);
3222
+ const at = sim.players.get(viewer).at;
3223
+ const scored = [];
3224
+ for (const [id, candidate] of views) {
3225
+ if (id === viewer || hidden?.(viewer, id) || (view.visible !== null && candidate.cell !== null && !view.visible.has(candidate.cell))) {
3226
+ continue;
3227
+ }
3228
+ const other = sim.players.get(id).at;
3229
+ const d = (at.x - other.x) ** 2 + (at.y - other.y) ** 2 + (at.z - other.z) ** 2;
3230
+ scored.push({ id, friend: friends.has(userIds.get(id)), d: known.get(viewer)?.has(id) ? d * KEEP_NEARER ** 2 : d });
3231
+ }
3232
+ scored.sort((a, b) => Number(b.friend) - Number(a.friend) || a.d - b.d);
3233
+ const cap = Math.min(h.caps.get(viewer) ?? h.place.nearestPlayers, h.place.nearestPlayers);
3234
+ sees.set(viewer, new Set(scored.slice(0, cap).map(({ id }) => id)));
3235
+ }
3236
+ return sees;
3237
+ }
3238
+
1974
3239
  // A scene actor of the place, or a copy the game spawned.
1975
3240
  function isSceneActor(h, id) {
1976
3241
  return Actors.isActor(h, id);