castle-web-cli 0.4.156 → 0.4.158

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 (243) hide show
  1. package/dist/agent-failures.d.ts +1 -0
  2. package/dist/agent-failures.js +6 -4
  3. package/dist/agent-prompts.js +4 -0
  4. package/dist/agent.d.ts +11 -0
  5. package/dist/agent.js +175 -15
  6. package/dist/bundle.js +8 -2
  7. package/dist/castle-host/host.js +114 -8
  8. package/dist/castleJson.js +6 -1
  9. package/dist/check.d.ts +1 -0
  10. package/dist/check.js +25 -0
  11. package/dist/devSessionServer.js +31 -7
  12. package/dist/imports.js +1 -19
  13. package/dist/index.js +15 -1
  14. package/dist/init.d.ts +2 -2
  15. package/dist/init.js +78 -42
  16. package/dist/mcpPlaytest.d.ts +1 -0
  17. package/dist/mcpPlaytest.js +182 -0
  18. package/dist/metering.d.ts +24 -0
  19. package/dist/metering.js +87 -0
  20. package/dist/sdkResolve.d.ts +3 -0
  21. package/dist/sdkResolve.js +55 -0
  22. package/dist/serve.js +50 -4
  23. package/dist/serverBundle.js +8 -3
  24. package/dist/shell/assets/{index-DsDkYFvP.js → index-BuSYLy-C.js} +64 -64
  25. package/dist/shell/assets/{index-DwezawBs.css → index-DfZmu3XC.css} +1 -1
  26. package/dist/shell/index.html +2 -2
  27. package/dist/vitePlugins.d.ts +1 -0
  28. package/dist/vitePlugins.js +20 -0
  29. package/kits/base/CLAUDE.md +196 -0
  30. package/kits/{blank → base}/castle.json +5 -2
  31. package/kits/base/editorHost.js +172 -0
  32. package/kits/{blank → base}/node_modules/.package-lock.json +3 -2
  33. package/kits/{blank → base}/package-lock.json +7 -4
  34. package/kits/{blank → base}/package.json +4 -2
  35. package/kits/base/sdk/README.md +569 -0
  36. package/kits/base/sdk/castle.d.ts +27 -0
  37. package/kits/base/sdk/castle.js +16 -0
  38. package/kits/base/sdk/commands.d.ts +181 -0
  39. package/kits/base/sdk/commands.js +16 -0
  40. package/kits/base/sdk/context.d.ts +17 -0
  41. package/kits/base/sdk/context.js +15 -0
  42. package/kits/base/sdk/errors.d.ts +22 -0
  43. package/kits/base/sdk/errors.js +16 -0
  44. package/kits/base/sdk/files.d.ts +15 -0
  45. package/kits/base/sdk/files.js +52 -0
  46. package/kits/base/sdk/haptics.d.ts +6 -0
  47. package/kits/base/sdk/haptics.js +36 -0
  48. package/kits/base/sdk/leaderboard.d.ts +26 -0
  49. package/kits/base/sdk/leaderboard.js +296 -0
  50. package/kits/base/sdk/lifecycle.d.ts +4 -0
  51. package/kits/base/sdk/lifecycle.js +13 -0
  52. package/kits/base/sdk/multiplayer.d.ts +43 -0
  53. package/kits/base/sdk/multiplayer.js +464 -0
  54. package/kits/base/sdk/multiplayerProtocol.d.ts +51 -0
  55. package/kits/base/sdk/multiplayerProtocol.js +5 -0
  56. package/kits/base/sdk/passes.d.ts +7 -0
  57. package/kits/base/sdk/passes.js +84 -0
  58. package/kits/base/sdk/portal.d.ts +7 -0
  59. package/kits/base/sdk/portal.js +35 -0
  60. package/kits/base/sdk/runtime.d.ts +62 -0
  61. package/kits/base/sdk/runtime.js +970 -0
  62. package/kits/base/sdk/saveQueue.d.ts +27 -0
  63. package/kits/base/sdk/saveQueue.js +205 -0
  64. package/kits/base/sdk/server/platformHandle.d.ts +25 -0
  65. package/kits/base/sdk/server/platformHandle.js +1 -0
  66. package/kits/base/sdk/server/wrapper.d.ts +28 -0
  67. package/kits/base/sdk/server/wrapper.js +109 -0
  68. package/kits/base/sdk/storage.d.ts +16 -0
  69. package/kits/base/sdk/storage.js +323 -0
  70. package/kits/base/sdk/time.d.ts +17 -0
  71. package/kits/base/sdk/time.js +120 -0
  72. package/kits/base/sdk/transport.d.ts +17 -0
  73. package/kits/base/sdk/transport.js +141 -0
  74. package/kits/base/sdk/types.d.ts +3 -0
  75. package/kits/base/sdk/types.js +1 -0
  76. package/kits/base/sdk/user.d.ts +10 -0
  77. package/kits/base/sdk/user.js +45 -0
  78. package/kits/multiplayer-2d/.prettierrc +5 -0
  79. package/kits/multiplayer-2d/CLAUDE.md +129 -0
  80. package/kits/multiplayer-2d/behaviors/Box.jsx +92 -0
  81. package/kits/multiplayer-2d/behaviors/Player.jsx +86 -0
  82. package/kits/multiplayer-2d/blueprints/crate.scene +13 -0
  83. package/kits/multiplayer-2d/blueprints/other-player.scene +13 -0
  84. package/kits/multiplayer-2d/blueprints/player.scene +15 -0
  85. package/kits/multiplayer-2d/blueprints/wall.scene +12 -0
  86. package/kits/multiplayer-2d/castle.json +39 -0
  87. package/kits/multiplayer-2d/code/client/avatars.js +79 -0
  88. package/kits/multiplayer-2d/code/client/poses.js +168 -0
  89. package/kits/multiplayer-2d/code/server/index.js +26 -0
  90. package/kits/multiplayer-2d/code/server/limits.js +99 -0
  91. package/kits/multiplayer-2d/code/server/ownership.js +177 -0
  92. package/kits/multiplayer-2d/code/server/players.js +127 -0
  93. package/kits/multiplayer-2d/code/server/sceneBodies.js +98 -0
  94. package/kits/multiplayer-2d/code/server/world.js +337 -0
  95. package/kits/multiplayer-2d/code/systems/multiplayer.js +424 -0
  96. package/kits/multiplayer-2d/eslint.config.js +21 -0
  97. package/kits/multiplayer-2d/fonts.generated.js +9 -0
  98. package/kits/multiplayer-2d/index.html +25 -0
  99. package/kits/multiplayer-2d/main.jsx +10 -0
  100. package/kits/multiplayer-2d/package-lock.json +351 -0
  101. package/kits/multiplayer-2d/package.json +30 -0
  102. package/kits/multiplayer-2d/scenes/main.scene +20 -0
  103. package/kits/multiplayer-2d/test/two-client-test.mjs +341 -0
  104. package/kits/multiplayer-2d/theme.style +4 -0
  105. package/kits/multiplayer-3d/.prettierrc +5 -0
  106. package/kits/multiplayer-3d/CLAUDE.md +215 -0
  107. package/kits/multiplayer-3d/blueprints/ball.scene +21 -0
  108. package/kits/multiplayer-3d/blueprints/other-player.scene +21 -0
  109. package/kits/multiplayer-3d/castle.json +43 -0
  110. package/kits/multiplayer-3d/code/client/avatars.js +136 -0
  111. package/kits/multiplayer-3d/code/client/nameTags.js +101 -0
  112. package/kits/multiplayer-3d/code/client/poses.js +220 -0
  113. package/kits/multiplayer-3d/code/server/index.js +23 -0
  114. package/kits/multiplayer-3d/code/server/limits.js +107 -0
  115. package/kits/multiplayer-3d/code/server/ownership.js +157 -0
  116. package/kits/multiplayer-3d/code/server/players.js +114 -0
  117. package/kits/multiplayer-3d/code/server/sceneBodies.js +88 -0
  118. package/kits/multiplayer-3d/code/server/world.js +306 -0
  119. package/kits/multiplayer-3d/code/systems/multiplayer.js +427 -0
  120. package/kits/multiplayer-3d/eslint.config.js +20 -0
  121. package/kits/multiplayer-3d/fonts.generated.js +9 -0
  122. package/kits/multiplayer-3d/index.html +22 -0
  123. package/kits/multiplayer-3d/main.jsx +9 -0
  124. package/kits/multiplayer-3d/package-lock.json +368 -0
  125. package/kits/multiplayer-3d/package.json +32 -0
  126. package/kits/multiplayer-3d/scenes/main.scene +409 -0
  127. package/kits/multiplayer-3d/theme.style +3 -0
  128. package/kits/physics-2d/CLAUDE.md +6 -0
  129. package/kits/physics-2d/castle.json +7 -1
  130. package/kits/physics-2d/editors/behaviorRegistry.js +5 -0
  131. package/kits/physics-2d/editors/editorRegistry.jsx +3 -1
  132. package/kits/physics-2d/engine/files.js +9 -5
  133. package/kits/physics-2d/engine/systemRegistry.js +2 -0
  134. package/kits/physics-2d/engine/ui.module.css +11 -0
  135. package/kits/physics-2d/package-lock.json +8 -2
  136. package/kits/physics-2d/package.json +2 -2
  137. package/kits/physics-3d/CLAUDE.md +4 -4
  138. package/kits/physics-3d/behaviors/Shape.jsx +1 -1
  139. package/kits/physics-3d/blueprints/crate.scene +1 -1
  140. package/kits/physics-3d/blueprints/door.scene +4 -4
  141. package/kits/physics-3d/blueprints/pillar.scene +1 -1
  142. package/kits/physics-3d/blueprints/platform.scene +1 -1
  143. package/kits/physics-3d/blueprints/statue.scene +1 -1
  144. package/kits/physics-3d/blueprints/wall.scene +1 -1
  145. package/kits/physics-3d/castle.json +8 -11
  146. package/kits/physics-3d/docs/pxmodel-format.md +1 -1
  147. package/kits/physics-3d/engine3d/materials.js +3 -3
  148. package/kits/physics-3d/engine3d/modelFiles.js +4 -2
  149. package/kits/physics-3d/engine3d/world3d.js +1 -1
  150. package/kits/physics-3d/fonts.generated.js +9 -0
  151. package/kits/physics-3d/main.jsx +1 -1
  152. package/kits/physics-3d/package-lock.json +85 -2
  153. package/kits/physics-3d/package.json +6 -2
  154. package/kits/physics-3d/scenes/main.scene +1 -1
  155. package/kits/physics-3d/scenes/model-lab.scene +1 -1
  156. package/kits/real-time/.prettierrc +5 -0
  157. package/kits/real-time/CLAUDE.md +60 -0
  158. package/kits/real-time/castle.json +19 -0
  159. package/kits/real-time/code/client/clock.js +68 -0
  160. package/kits/real-time/code/client/connection.js +134 -0
  161. package/kits/real-time/code/client/gameHooks.js +50 -0
  162. package/kits/real-time/code/client/interpolate.js +82 -0
  163. package/kits/real-time/code/client/messages.js +55 -0
  164. package/kits/real-time/code/client/ownership.js +94 -0
  165. package/kits/real-time/code/client/smooth.js +54 -0
  166. package/kits/real-time/code/server/blockDelta.js +48 -0
  167. package/kits/real-time/code/server/gameHooks.js +47 -0
  168. package/kits/real-time/code/server/limits.js +35 -0
  169. package/kits/real-time/code/server/session.js +251 -0
  170. package/kits/real-time/eslint.config.js +22 -0
  171. package/kits/real-time/index.html +45 -0
  172. package/kits/real-time/package.json +14 -0
  173. package/kits/{tabletop → turn-based}/CLAUDE.md +42 -49
  174. package/kits/turn-based/blueprints/board.scene +15 -0
  175. package/kits/turn-based/blueprints/square.scene +25 -0
  176. package/kits/turn-based/castle.json +37 -0
  177. package/kits/turn-based/code/behaviors/Board.jsx +169 -0
  178. package/kits/turn-based/code/behaviors/Square.jsx +26 -0
  179. package/kits/turn-based/code/server/index.js +152 -0
  180. package/kits/turn-based/drawings/square.sprite +25 -0
  181. package/kits/turn-based/eslint.config.js +12 -0
  182. package/kits/turn-based/fonts.generated.js +9 -0
  183. package/kits/{tabletop → turn-based}/index.html +5 -3
  184. package/kits/{tabletop → turn-based}/main.jsx +2 -2
  185. package/kits/{tabletop → turn-based}/package-lock.json +17 -4
  186. package/kits/{tabletop → turn-based}/package.json +5 -2
  187. package/kits/turn-based/room.js +289 -0
  188. package/kits/turn-based/scenes/main.scene +227 -0
  189. package/kits/{tabletop → turn-based}/testing.js +131 -99
  190. package/kits/turn-based/theme.style +3 -0
  191. package/package.json +1 -1
  192. package/kits/blank/CLAUDE.md +0 -198
  193. package/kits/tabletop/castle.json +0 -34
  194. package/kits/tabletop/room.js +0 -269
  195. /package/kits/{blank → base}/index.html +0 -0
  196. /package/kits/{blank → base}/node_modules/castle-web-fonts/README.md +0 -0
  197. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.d.ts +0 -0
  198. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.js +0 -0
  199. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.d.ts +0 -0
  200. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.js +0 -0
  201. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +0 -0
  202. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.js +0 -0
  203. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +0 -0
  204. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +0 -0
  205. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +0 -0
  206. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.js +0 -0
  207. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +0 -0
  208. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.js +0 -0
  209. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +0 -0
  210. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +0 -0
  211. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +0 -0
  212. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +0 -0
  213. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +0 -0
  214. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.js +0 -0
  215. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +0 -0
  216. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.js +0 -0
  217. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +0 -0
  218. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.js +0 -0
  219. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.d.ts +0 -0
  220. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.js +0 -0
  221. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +0 -0
  222. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/FONTS.md +0 -0
  223. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +0 -0
  224. /package/kits/{blank → base}/node_modules/castle-web-fonts/package.json +0 -0
  225. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  226. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  227. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  228. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  229. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  230. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  231. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/SOURCE.txt +0 -0
  232. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  233. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  234. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  235. /package/kits/physics-3d/drawings/{crate.pxart → crate.sprite} +0 -0
  236. /package/kits/physics-3d/drawings/{door-edge.pxart → door-edge.sprite} +0 -0
  237. /package/kits/physics-3d/drawings/{door.pxart → door.sprite} +0 -0
  238. /package/kits/physics-3d/drawings/{face.pxart → face.sprite} +0 -0
  239. /package/kits/physics-3d/drawings/{floor.pxart → floor.sprite} +0 -0
  240. /package/kits/physics-3d/drawings/{platform.pxart → platform.sprite} +0 -0
  241. /package/kits/physics-3d/drawings/{statue.pxart → statue.sprite} +0 -0
  242. /package/kits/physics-3d/drawings/{wall.pxart → wall.sprite} +0 -0
  243. /package/kits/{tabletop → turn-based}/.prettierrc +0 -0
@@ -0,0 +1,341 @@
1
+ // This integration test opens two browser clients against a served kit. It
2
+ // checks other player movement, shared crate movement, final convergence, and
3
+ // browser errors, then saves one screenshot from each client.
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ import { createRequire } from 'module';
9
+
10
+ const require = createRequire('/Users/nikki/Development/castle-xyz/castle-www/');
11
+ // Playwright comes from castle-www's node_modules. Workspace browser automation
12
+ // is restricted to Castle decks, and both pages opened here are this served deck.
13
+ const { chromium } = require('playwright');
14
+
15
+ const deckDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
16
+
17
+ // How long a client is given to connect and receive its first world.
18
+ const JOIN_TIMEOUT_MS = 30_000;
19
+
20
+ // Input is driven in short slices so each direction uses the latest client state.
21
+ const STEER_SLICE_MS = 60;
22
+
23
+ const ARROWS = { left: 'ArrowLeft', right: 'ArrowRight', up: 'ArrowUp', down: 'ArrowDown' };
24
+
25
+ // Accept an explicit play origin through:
26
+ // node test/two-client-test.mjs --url http://127.0.0.1:50528
27
+ // With no argument, the test reads the active serve metadata.
28
+ function parseArgs(argv) {
29
+ const args = {};
30
+ for (let i = 0; i < argv.length; i += 1) {
31
+ if (argv[i] === '--url') {
32
+ args.url = argv[i + 1];
33
+ }
34
+ }
35
+ return args;
36
+ }
37
+
38
+ // The origin the deck actually renders on, written by `castle-web serve`.
39
+ function playUrl(args) {
40
+ if (args.url) {
41
+ return args.url;
42
+ }
43
+ const file = path.join(deckDir, '.castle', 'serve.json');
44
+ if (!fs.existsSync(file)) {
45
+ throw new Error('No .castle/serve.json; serve the deck first or pass --url.');
46
+ }
47
+ return JSON.parse(fs.readFileSync(file, 'utf8')).contentPlayUrl;
48
+ }
49
+
50
+ async function openClient(browser, url, index) {
51
+ // Separate browser contexts give each page its own session identity.
52
+ const context = await browser.newContext();
53
+ const page = await context.newPage();
54
+ const errors = [];
55
+ // Capture uncaught exceptions and error-level console output for the final check.
56
+ page.on('pageerror', (e) => errors.push(String(e).slice(0, 300)));
57
+ page.on('console', (message) => {
58
+ if (message.type() === 'error') {
59
+ errors.push(message.text().slice(0, 300));
60
+ }
61
+ });
62
+ await page.goto(`${url}/?edit=0`, { waitUntil: 'domcontentloaded', timeout: 60_000 });
63
+ return { index, context, page, errors, held: new Set() };
64
+ }
65
+
66
+ // Read the state published by MultiplayerSystem.publish. These are the same
67
+ // Layout-derived values used by rendering rather than a separate test model.
68
+ function read(client) {
69
+ return client.page.evaluate(() => globalThis.__multiplayer ?? null);
70
+ }
71
+
72
+ async function waitFor(client, describe, ok, timeoutMs) {
73
+ // Keep the last published state so a timeout reports useful connection data.
74
+ const startedAt = Date.now();
75
+ let last = null;
76
+ while (Date.now() - startedAt < timeoutMs) {
77
+ last = await read(client);
78
+ if (last && ok(last)) {
79
+ return last;
80
+ }
81
+ await client.page.waitForTimeout(100);
82
+ }
83
+ throw new Error(`client ${client.index}: ${describe} (last state ${JSON.stringify(last)})`);
84
+ }
85
+
86
+ // Hold exactly the named arrow keys, pressing and releasing only what changed.
87
+ async function hold(client, wanted) {
88
+ const want = new Set(wanted);
89
+ for (const key of client.held) {
90
+ if (!want.has(key)) {
91
+ await client.page.keyboard.up(key);
92
+ client.held.delete(key);
93
+ }
94
+ }
95
+ for (const key of want) {
96
+ if (!client.held.has(key)) {
97
+ await client.page.keyboard.down(key);
98
+ client.held.add(key);
99
+ }
100
+ }
101
+ }
102
+
103
+ // Return the keys that move a character from `from` toward `to`. The dead zone
104
+ // prevents alternating opposite inputs after the character reaches the target.
105
+ function keysToward(from, to, deadZone = 6) {
106
+ const keys = [];
107
+ if (to.x - from.x > deadZone) {
108
+ keys.push(ARROWS.right);
109
+ }
110
+ if (from.x - to.x > deadZone) {
111
+ keys.push(ARROWS.left);
112
+ }
113
+ if (to.y - from.y > deadZone) {
114
+ keys.push(ARROWS.down);
115
+ }
116
+ if (from.y - to.y > deadZone) {
117
+ keys.push(ARROWS.up);
118
+ }
119
+ return keys;
120
+ }
121
+
122
+ // Walk toward a point that is recomputed each slice, for up to `ms`. `target`
123
+ // gets this client's current state and returns where to head, or null to stop.
124
+ async function walk(client, target, ms) {
125
+ const until = Date.now() + ms;
126
+ while (Date.now() < until) {
127
+ const state = await read(client);
128
+ const to = state?.me ? target(state) : null;
129
+ if (!to) {
130
+ break;
131
+ }
132
+ await hold(client, keysToward({ x: state.me[0] + 17, y: state.me[1] + 17 }, to));
133
+ await client.page.waitForTimeout(STEER_SLICE_MS);
134
+ }
135
+ await hold(client, []);
136
+ }
137
+
138
+ function distance(a, b) {
139
+ // Test poses store their card-space x and y in the first two array entries.
140
+ return Math.hypot(a[0] - b[0], a[1] - b[1]);
141
+ }
142
+
143
+ const results = [];
144
+
145
+ function check(name, passed, detail) {
146
+ // Defer process failure until all movement and browser-error checks have run.
147
+ results.push({ name, passed, detail });
148
+ console.log(` ${passed ? 'ok ' : 'FAIL'} ${name}${detail ? ` -- ${detail}` : ''}`);
149
+ }
150
+
151
+ // One client walks a fixed distance to the right; the other must see it happen,
152
+ // during the walk as well as after it.
153
+ async function checkRemoteMovement(mover, watcher) {
154
+ const before = await waitFor(
155
+ watcher,
156
+ 'never saw the other character',
157
+ (state) => state.players[moverId] !== undefined,
158
+ JOIN_TIMEOUT_MS,
159
+ );
160
+ const from = before.players[moverId];
161
+ const startX = (await read(mover)).me[0];
162
+
163
+ // Sample during movement to check continuous synchronization. Final-position
164
+ // agreement by itself does not cover the interpolation path.
165
+ let worstWhileMoving = 0;
166
+ const watching = setInterval(async () => {
167
+ const [here, there] = [await read(mover), await read(watcher)];
168
+ const seen = there?.players?.[moverId];
169
+ if (here?.me && seen) {
170
+ worstWhileMoving = Math.max(worstWhileMoving, distance(here.me, seen));
171
+ }
172
+ }, 150);
173
+ await walk(mover, () => ({ x: startX + 160, y: 0 }), 3_000);
174
+ clearInterval(watching);
175
+ check(
176
+ 'the two clients stay together while the character walks',
177
+ worstWhileMoving > 0 && worstWhileMoving < 60,
178
+ `worst gap seen mid-walk was ${worstWhileMoving.toFixed(1)}px`,
179
+ );
180
+
181
+ // The watcher draws behind the present by the interpolation delay, so it needs
182
+ // a moment past the last report to arrive at the same place.
183
+ await watcher.page.waitForTimeout(1_000);
184
+ const after = await read(watcher);
185
+ const seen = after.players[moverId];
186
+ const moved = seen[0] - from[0];
187
+ check(
188
+ 'the other client sees the character move',
189
+ moved > 40,
190
+ `it moved ${moved.toFixed(1)}px on the watching client`,
191
+ );
192
+
193
+ const mine = (await read(mover)).me;
194
+ check(
195
+ 'both clients agree where that character is',
196
+ distance(mine, seen) < 30,
197
+ `${distance(mine, seen).toFixed(1)}px apart`,
198
+ );
199
+ }
200
+
201
+ // One client shoves the nearest crate; both must end up with it in one place.
202
+ async function checkCratePush(pusher, watcher) {
203
+ const start = await read(pusher);
204
+ const nearest = nearestCrate(start);
205
+ const before = start.objects[nearest];
206
+ const watchedBefore = (await read(watcher)).objects[nearest];
207
+
208
+ // Sample during the push. Ownership makes the pusher simulate the crate while
209
+ // the watching client follows reported poses.
210
+ let worstWhileMoving = 0;
211
+ const watching = setInterval(async () => {
212
+ const [here, there] = [await read(pusher), await read(watcher)];
213
+ const a = here?.objects?.[nearest];
214
+ const b = there?.objects?.[nearest];
215
+ if (a && b && distance(a, before) > 10) {
216
+ worstWhileMoving = Math.max(worstWhileMoving, distance(a, b));
217
+ }
218
+ }, 150);
219
+
220
+ // Walk at the far side of the crate, so the character keeps going once it has
221
+ // made contact instead of stopping on the near face.
222
+ await walk(
223
+ pusher,
224
+ (state) => {
225
+ const crate = state.objects[nearest];
226
+ const me = { x: state.me[0] + 17, y: state.me[1] + 17 };
227
+ const centre = { x: crate[0] + 22, y: crate[1] + 22 };
228
+ const away = { x: centre.x - me.x, y: centre.y - me.y };
229
+ const length = Math.hypot(away.x, away.y) || 1;
230
+ return { x: centre.x + (away.x / length) * 60, y: centre.y + (away.y / length) * 60 };
231
+ },
232
+ 7_000,
233
+ );
234
+ clearInterval(watching);
235
+ check(
236
+ 'the two clients stay together while the crate is moving',
237
+ worstWhileMoving > 0 && worstWhileMoving < 70,
238
+ `worst gap seen mid-push was ${worstWhileMoving.toFixed(1)}px`,
239
+ );
240
+ await watcher.page.waitForTimeout(1_500);
241
+
242
+ const pushed = (await read(pusher)).objects[nearest];
243
+ const watched = (await read(watcher)).objects[nearest];
244
+ check(
245
+ 'the crate moved on the pushing client',
246
+ distance(before, pushed) > 20,
247
+ `${nearest} moved ${distance(before, pushed).toFixed(1)}px`,
248
+ );
249
+ check(
250
+ 'the crate moved on the watching client too',
251
+ distance(watchedBefore, watched) > 20,
252
+ `it moved ${distance(watchedBefore, watched).toFixed(1)}px there`,
253
+ );
254
+ check(
255
+ 'both clients agree where the crate is',
256
+ distance(pushed, watched) < 25,
257
+ `${distance(pushed, watched).toFixed(1)}px apart`,
258
+ );
259
+ console.log(
260
+ ` note ${nearest} owned by the pusher: ${(await read(pusher)).mine.includes(nearest)}`,
261
+ );
262
+ }
263
+
264
+ function nearestCrate(state) {
265
+ const me = { x: state.me[0] + 17, y: state.me[1] + 17 };
266
+ let best = null;
267
+ let bestAt = Infinity;
268
+ for (const [id, pose] of Object.entries(state.objects)) {
269
+ // Crate and player centres use the default 44px and 34px Layout dimensions.
270
+ const at = Math.hypot(pose[0] + 22 - me.x, pose[1] + 22 - me.y);
271
+ if (at < bestAt) {
272
+ best = id;
273
+ bestAt = at;
274
+ }
275
+ }
276
+ return best;
277
+ }
278
+
279
+ let moverId = null;
280
+
281
+ async function main() {
282
+ const url = playUrl(parseArgs(process.argv.slice(2)));
283
+ console.log(`play origin: ${url}`);
284
+ // SwiftShader supplies the WebGL implementation used by the canvas renderer
285
+ // when Chromium runs headless in an environment without a GPU.
286
+ const browser = await chromium.launch({
287
+ headless: true,
288
+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
289
+ });
290
+ const clients = [];
291
+ // Open sequentially so the first client has joined before the second is measured.
292
+ for (let i = 0; i < 2; i += 1) {
293
+ clients.push(await openClient(browser, url, i));
294
+ await clients[i].page.waitForTimeout(1_500);
295
+ }
296
+ const [alice, bob] = clients;
297
+
298
+ // Both clients must have a roster peer and an interpolation clock before input.
299
+ for (const client of clients) {
300
+ const state = await waitFor(
301
+ client,
302
+ 'did not connect and see the other player',
303
+ (s) => s.state === 'connected' && s.others >= 1 && s.ready,
304
+ JOIN_TIMEOUT_MS,
305
+ );
306
+ console.log(
307
+ ` client ${client.index}: ${state.selfId}, ${state.others} other, delay ${state.delay}ms`,
308
+ );
309
+ }
310
+ moverId = (await read(alice)).selfId;
311
+
312
+ console.log('checks:');
313
+ // Movement covers avatar interpolation; the crate push covers ownership transfer.
314
+ await checkRemoteMovement(alice, bob);
315
+ await checkCratePush(alice, bob);
316
+
317
+ // Save the final rendered room from each client for visual inspection.
318
+ const shots = path.join(deckDir, 'screenshots');
319
+ fs.mkdirSync(shots, { recursive: true });
320
+ for (const client of clients) {
321
+ await client.page.screenshot({ path: path.join(shots, `client-${client.index}.png`) });
322
+ }
323
+ console.log(`screenshots: ${shots}`);
324
+
325
+ for (const client of clients) {
326
+ // Duplicate console messages are collapsed to keep failure output readable.
327
+ const unique = [...new Set(client.errors)];
328
+ check(
329
+ `client ${client.index} logged no errors`,
330
+ unique.length === 0,
331
+ unique.slice(0, 3).join(' | '),
332
+ );
333
+ }
334
+
335
+ await browser.close();
336
+ const failed = results.filter((r) => !r.passed);
337
+ console.log(failed.length === 0 ? '\nall checks passed' : `\n${failed.length} check(s) failed`);
338
+ process.exit(failed.length === 0 ? 0 : 1);
339
+ }
340
+
341
+ await main();
@@ -0,0 +1,4 @@
1
+ {
2
+ "palette": "endesga-64",
3
+ "font": "DMSans"
4
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "printWidth": 100,
3
+ "tabWidth": 2,
4
+ "singleQuote": true
5
+ }
@@ -0,0 +1,215 @@
1
+ # multiplayer-3d
2
+
3
+ The wire, the clock, the interpolation, the ownership rule, and a server that
4
+ builds a rapier world from the deck's own scene. Code only; it draws nothing. A
5
+ deck imports this beside `castle.physics-3d`, which is the engine and the
6
+ editors.
7
+
8
+ Extracted from `cauldron-decks/hangout-3d-clean`, which stays the worked example.
9
+
10
+ **The dimension-free half of it lives in `castle.real-time`**, imported, and is
11
+ shared with `castle.multiplayer-2d`. What is left here is what knows about
12
+ rapier, three.js, metres, or a quaternion. Nothing here forwards to there: a
13
+ caller that wants the clock, the transport, the tracks, the smoothing, the
14
+ ownership rule, the wire kinds, the deck hooks or the block latches imports them
15
+ from `@imports/castle.real-time/code/...`.
16
+
17
+ | here | what it is |
18
+ | ----------------------------------- | ------------------------------------------------------- |
19
+ | `client/poses.js` | the pose codec the core calls back into, and the metres |
20
+ | `client/avatars.js`, `nameTags.js` | other players' actors and their three.js labels |
21
+ | `systems/multiplayer.js` | the frame loop, wiring the core to the engine |
22
+ | `server/index.js` | `makeSession` with this kit's world, players, ownership |
23
+ | `server/limits.js` | the metres and the tests over them |
24
+ | `server/world.js`, `ownership.js`, `players.js`, `sceneBodies.js` | the rapier world |
25
+
26
+ The move report carries `[x, y, z, facing]` in `p`, with no separate `f` field:
27
+ the transport sends one packed array and never looks inside it. A deck that
28
+ forked `connection.js` also owns its server's `setPose`, so the two halves of
29
+ that wire stay together.
30
+
31
+ **Two products, two words.** "The kit" is always THIS — `castle.multiplayer-3d`.
32
+ "The engine" is always `castle.physics-3d`: the renderer, the editors, and the
33
+ behaviors (`Player`, `Transform`, `Shape`, `Body`, `Door`) a scene is built from.
34
+ The kit has no behaviors and no `behaviors/` directory; when a file here names
35
+ `Door` or a controller it means the engine's.
36
+
37
+ **Namespace imports take an uppercase name**, so a call reads as a proper noun at
38
+ the site: `import * as Smoothing from './smooth.js'`, then `Smoothing.smooth(…)`.
39
+ File names stay lowercase.
40
+
41
+ ## Layout
42
+
43
+ ```
44
+ code/client/ the pose format, and the browser half of it
45
+ code/server/ what runs in the session process
46
+ code/systems/ the frame loop, wiring the core to the engine
47
+ ```
48
+
49
+ `client/poses.js` is the exception to the split: it is the pose format, so
50
+ `server/index.js`, `server/world.js` and `server/players.js` import it too. It
51
+ sits under `client/` because that is where the format is written down, not
52
+ because only the browser reads it.
53
+
54
+ ## How a deck uses it
55
+
56
+ ```jsonc
57
+ // castle.json
58
+ "server": { "main": "imports/castle.multiplayer-3d/code/server/index.js" }
59
+ ```
60
+
61
+ and then writes `code/systems/multiplayer.js` (below, and NOT optional — nothing
62
+ here runs a frame loop), plus these, all optional, all found by root-anchored
63
+ glob in `code/server/gameHooks.js`:
64
+
65
+ | deck file | what it is |
66
+ | ------------------------------- | --------------------------------------------------- |
67
+ | `code/server/game.js` | the game, as six hooks on a default export |
68
+ | `code/server/deckComponents.js` | `export const componentDefaults = { Cargo: {...} }` |
69
+
70
+ `@imports/castle.real-time/code/server/blockDelta.js` is there for the same
71
+ hooks: `blockDelta(holder, block)` and `movedBy(holder, field, value, epsilon)`,
72
+ for deciding whether the block `delta(sim)` returns is news. Both write their
73
+ latch onto the deck's own state object — see the file for which property names
74
+ they take.
75
+
76
+ The six hooks: `ready(sim)`, `message(session, player, data)`,
77
+ `place(sim, handovers)`, `step(sim, handovers)`, `join(sim)`, `delta(sim)`.
78
+ `place` runs BEFORE the physics step, which is where a write through a deferred
79
+ channel (`player.at`, `setNextKinematicTranslation`) has to happen to reach the
80
+ body this tick. `delta` is also a reason to send — a tick where nothing moved but
81
+ a round ended is broadcast rather than swallowed.
82
+
83
+ `message` is dispatched before the `sim` guard: a lobby handshake has nothing to
84
+ do with the physics world and must not wait on `createSimulation()`.
85
+
86
+ ## The deck's client system: `code/systems/multiplayer.js`
87
+
88
+ The kit ships one, and it stands aside when the deck has its own. `client/` and
89
+ `castle.real-time` are a set of parts with no frame loop; this is the system that
90
+ drives them. The five decks' copies are 280-350 lines and four are within ~60
91
+ lines of each other, so a deck that needs its own starts from the nearest.
92
+
93
+ The engine's system registry globs `/code/systems/**/*.js` and calls each
94
+ module's `installSystem(runtime)` once per created runtime, so the file is
95
+ installed by existing there — there is nothing to register. `installSystem`
96
+ constructs the class and calls `runtime.registerSystem(system)`. One field per
97
+ kit module:
98
+
99
+ | field | from |
100
+ | ----------- | ----------------------------------------- |
101
+ | `net` | `connectSession()`, null until joined |
102
+ | `clock` | `makeClock()` |
103
+ | `players` | playerId -> `makeTrack()` |
104
+ | `objects` | scene actor id -> `makeTrack()` |
105
+ | `own` | `makeOwnership()` |
106
+ | `shown` | `makeSmoothing()` |
107
+ | `avatars` | `makeAvatars()` |
108
+ | `clampedTo` | the last pose the server refused, or null |
109
+
110
+ All but `avatars` come from `castle.real-time`, and every call that reads inside
111
+ a pose takes `client/poses.js` as an argument: `pushSample(track, msg.t, pose,
112
+ Poses.same)`, `sampleAt(track, at, Poses.blend)`, `smooth(shown, id, sampled, dt,
113
+ Poses)`, `toClaim(..., Poses.REACH)`.
114
+
115
+ `afterBehaviors(scene, dt)` is the frame, and its order matters:
116
+
117
+ 1. **Connect on the first stepped frame**, not in the constructor. The scene
118
+ editor builds runtimes it never steps, and those must not join a session.
119
+ 2. **Drain.** For each message from `net.drain()`: `noteArrival(clock, msg.t, msg.localMs)`,
120
+ then `applyHandovers(own, msg.own, selfId)`, then one
121
+ `pushSample(track, msg.t, pose)` per entry of `msg.ps` and `msg.os`. `msg.t`
122
+ is simulation time and `msg.localMs` is this page's clock at arrival — samples
123
+ are filed under `msg.t`, never under arrival. A `WORLD` message is the room as
124
+ it is, so it REPLACES a track rather than landing on top of a stale one. Our
125
+ own entry in `msg.ps` is news only when its `clamped` flag is set.
126
+ 3. **Draw**, at `renderTime(clock, performance.now())`, and only once
127
+ `ready(clock)`: `sampleAt` -> `smooth` -> `Poses.applyPose`. Write the rapier body
128
+ as well as the Transform (`scene.physics3d.bodyOf(actor)`) — rapier writes a
129
+ dynamic body's pose back over the Transform every frame, so the Transform
130
+ alone is discarded. Skip anything in `own.mine`: writing the server's older
131
+ copy over the copy this client is simulating is the fight that stops a push
132
+ from landing.
133
+ 4. **Accept the clamp.** Ease onto `clampedTo` over a few frames; take it at once
134
+ only past a few metres, where easing would read as sliding.
135
+ 5. **Report.** `toClaim` / `toRelease` over the claimable actors, `Poses.poseOf`
136
+ for each object in `own.mine`, then
137
+ `net.sendMove(Poses.packMove(transform), owned, claims, releases)` — the
138
+ transport takes a packed pose. This runs AFTER the
139
+ engine's `Player` behavior and the local physics — the system reports where
140
+ the player got to, it does not move them.
141
+
142
+ Also `reset(scene)`, called on a scene load: the actors the kit spawned are gone,
143
+ so `clearAvatars` and drop every track, but the connection outlives it. And
144
+ `dispose(scene)`, which resets and then `net.close()`.
145
+
146
+ Everything else in the file is the deck's: which actors are claimable, what a
147
+ other player is drawn as, the deck's own message kinds, and where the deck's
148
+ game gets stepped.
149
+
150
+ ## Rules for editing this kit
151
+
152
+ **Root-anchor anything that reaches out of the kit.** Once imported, these files
153
+ live at `imports/<alias>/code/...`, so `../../scenes/main.scene` is the KIT's
154
+ scene, not the deck's. `sceneBodies.js` reads `/scenes/main.scene?raw` and
155
+ `gameHooks.js` globs `/code/server/game.js` for exactly this reason. A relative
156
+ path that escapes `code/` is a bug.
157
+
158
+ **`server/index.js` is meant never to be forked.** Every hook a deck needs goes
159
+ through `gameHooks.js`. If a deck has to fork it, a seam is missing — add the
160
+ seam, do not tell the deck to fork.
161
+
162
+ **A forked file's relative imports resolve from the IMPORT's directory, not the
163
+ fork's.** `forks/<alias>/code/server/world.js` importing `./limits.js` gets the
164
+ import's `limits.js`, which is the intended behavior. Reaching a DECK file from a
165
+ fork needs a root-anchored `/code/...` specifier — a relative one lands inside
166
+ `forks/`. A fork of a `castle.real-time` file goes under
167
+ `forks/castle.real-time/`, which is where that file lives.
168
+
169
+ **A deck omits a kit file by not importing it.** There is no mechanism for
170
+ dropping one; an unimported module is simply never in the graph. It still sits
171
+ in `imports/` on disk, which is reading noise but not runtime cost.
172
+
173
+ ## The avatars boundary
174
+
175
+ `avatars.js` keeps the bookkeeping — which actor belongs to which player, when
176
+ to spawn and despawn one, one name tag each. The deck decides everything about
177
+ appearance, through `showPlayer`'s options and its return:
178
+
179
+ | deck decides | how |
180
+ | ---------------------------- | ----------------------------------- |
181
+ | what a player is drawn as | `options.blueprint` |
182
+ | whether a player is named | `username: null` draws no label |
183
+ | how high the label floats | `options.tagHeight` |
184
+ | anything applied after spawn | `showPlayer` returns the actor |
185
+ | how a label is drawn | `avatars.tags.get(playerId).sprite` |
186
+
187
+ `options.blueprint` defaults to `blueprints/other-player.scene` in the deck's
188
+ own root, so a deck that ships that file passes no options.
189
+
190
+ An actor keeps the blueprint it was spawned from. A deck that changes a player's
191
+ appearance mid-session drops the actor first — `dropMissing(avatars, scene, new
192
+ Map())` — and the next `showPlayer` respawns it.
193
+
194
+ ## What is deliberately NOT here
195
+
196
+ - **The player blueprint itself.** The kit spawns a scene from the deck's own
197
+ root; the deck ships it. `blueprints/other-player.scene` is only the name it
198
+ looks for when the deck names none.
199
+ - **Any HUD.** Five decks wrote five HUDs with no shared lines.
200
+ - **Gameplay verbs** — carry, vehicle, round, lobby. Measured across six decks
201
+ and none of them survived contact; see the audit.
202
+
203
+ ## The name tags
204
+
205
+ A `THREE.Sprite`'s apparent size is its world scale over its distance, so a fixed
206
+ scale is right at one distance and wrong everywhere else — the label covered a
207
+ large part of the card whenever a camera got close, which every camera in this
208
+ family does. `moveNameTag` takes the camera and holds the tag at a constant
209
+ SCREEN size inside `SAME_SIZE_M`, shrinking with distance beyond it.
210
+
211
+ Two more at the call site in `avatars.js`: the tag is compared against the DRAWN
212
+ text (comparing the raw username rebuilt an anonymous player's canvas and texture
213
+ every frame), and `connection.js`'s `status().you` falls back to the roster entry
214
+ for the local playerId, so a local player's own tag is not missing while the
215
+ SDK's `you` is still null.
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "Ball",
3
+ "actors": [
4
+ {
5
+ "components": {
6
+ "Transform": { "y": 0.7 },
7
+ "Shape": {
8
+ "kind": "sphere",
9
+ "radius": 0.7,
10
+ "color": "#f4e04d",
11
+ "roughness": 0.35,
12
+ "clearcoat": 0.6
13
+ },
14
+ "Body": { "type": "dynamic", "friction": 0.3, "restitution": 0.6 },
15
+ "Solid": {},
16
+ "Ball": {},
17
+ "Lookable": { "text": "a ball. the server owns this one.", "range": 4 }
18
+ }
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "Other Player",
3
+ "actors": [
4
+ {
5
+ "components": {
6
+ "Transform": { "y": 1 },
7
+ "Shape": {
8
+ "kind": "capsule",
9
+ "radius": 0.35,
10
+ "height": 1.4,
11
+ "color": "#7fc9b8",
12
+ "roughness": 0.4,
13
+ "clearcoat": 0.5
14
+ },
15
+ "Body": { "type": "kinematic", "lockRotations": true },
16
+ "Solid": {},
17
+ "Model": { "file": "@imports/castle.physics-3d/models/player.pxmodel", "yOffset": -0.7 }
18
+ }
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,43 @@
1
+ {
2
+ "title": "multiplayer-3d",
3
+ "editor": {
4
+ "hiddenPaths": [],
5
+ "visiblePaths": [
6
+ "code/**",
7
+ "theme.style",
8
+ "fonts.generated.js",
9
+ "scenes/**",
10
+ "blueprints/**"
11
+ ],
12
+ "defaultPlayFile": "scenes/main.scene"
13
+ },
14
+ "imports": {
15
+ "castle.real-time": {
16
+ "deckId": "xFVr-afOLuUQ",
17
+ "version": "2026-09-01T20:54:44.750Z"
18
+ },
19
+ "castle.physics-3d": {
20
+ "deckId": "JH0SclbPVP0y",
21
+ "version": "2026-09-01T01:02:48.784Z"
22
+ },
23
+ "castle.physics-2d": {
24
+ "deckId": "ckRZGFW4iPrx",
25
+ "version": "2026-09-01T01:02:46.041Z",
26
+ "via": "castle.physics-3d"
27
+ },
28
+ "castle.base": {
29
+ "deckId": "yRcmH4_aYllE",
30
+ "version": "2026-09-01T01:02:34.326Z"
31
+ }
32
+ },
33
+ "autoUpdateWhenImported": true,
34
+ "deckId": "ZwA_P_-VO-Qh",
35
+ "cardId": "bvRmCzyUpt_a",
36
+ "publishedVersion": "2026-09-02T03:33:45.811Z",
37
+ "main": "main.jsx",
38
+ "server": {
39
+ "main": "code/server/index.js",
40
+ "tickRate": 30,
41
+ "maxPlayers": 8
42
+ }
43
+ }