castle-web-cli 0.4.204 → 0.4.206

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 (134) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.d.ts +1 -0
  4. package/dist/agent-prompts.js +7 -2
  5. package/dist/agent.d.ts +3 -2
  6. package/dist/agent.js +29 -18
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/devSessionStorage.js +65 -4
  10. package/dist/effortSupport.d.ts +7 -0
  11. package/dist/effortSupport.js +31 -0
  12. package/dist/imports.d.ts +1 -1
  13. package/dist/imports.js +59 -19
  14. package/dist/index.js +4 -3
  15. package/dist/init.d.ts +9 -1
  16. package/dist/init.js +64 -25
  17. package/dist/kitCatalog.d.ts +13 -0
  18. package/dist/kitCatalog.js +111 -0
  19. package/dist/platformDoc.js +7 -2
  20. package/dist/serve.js +35 -2
  21. package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
  22. package/dist/shell/index.html +1 -1
  23. package/dist/vitePlugins.js +19 -1
  24. package/kits/base/CLAUDE.md +2 -0
  25. package/kits/base/castle.json +1 -1
  26. package/kits/base/sdk/README.md +131 -0
  27. package/kits/base/sdk/agent.d.ts +6 -0
  28. package/kits/base/sdk/agent.js +70 -0
  29. package/kits/base/sdk/castle.d.ts +4 -0
  30. package/kits/base/sdk/castle.js +2 -0
  31. package/kits/base/sdk/commands.d.ts +106 -0
  32. package/kits/base/sdk/commands.js +21 -0
  33. package/kits/base/sdk/decks.d.ts +7 -0
  34. package/kits/base/sdk/decks.js +31 -0
  35. package/kits/base/sdk/runtime.d.ts +4 -2
  36. package/kits/base/sdk/runtime.js +51 -40
  37. package/kits/base/sdk/server/storage.d.ts +44 -0
  38. package/kits/base/sdk/server/storage.js +54 -0
  39. package/kits/base/sdk/transport.d.ts +5 -1
  40. package/kits/base/sdk/transport.js +106 -23
  41. package/kits/multiplayer-2d/castle.json +5 -4
  42. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  43. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  44. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  45. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  46. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  47. package/kits/multiplayer-3d/castle.json +5 -4
  48. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  49. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  50. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  51. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  52. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  53. package/kits/multiplayer-3d/code/server/world.js +12 -4
  54. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  55. package/kits/physics-2d/castle.json +1 -0
  56. package/kits/physics-3d/CLAUDE.md +65 -7
  57. package/kits/physics-3d/castle.json +4 -3
  58. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  59. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  60. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  61. package/kits/physics-3d/engine3d/blob.js +1058 -0
  62. package/kits/physics-3d/engine3d/branches.js +300 -0
  63. package/kits/physics-3d/engine3d/cage.js +496 -0
  64. package/kits/physics-3d/engine3d/cageops.js +516 -0
  65. package/kits/physics-3d/engine3d/frame.js +669 -0
  66. package/kits/physics-3d/engine3d/look.js +675 -0
  67. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  68. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  69. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  70. package/kits/physics-3d/engine3d/motion.js +560 -0
  71. package/kits/physics-3d/engine3d/objtext.js +37 -0
  72. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  73. package/kits/physics-3d/engine3d/paint.js +674 -0
  74. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  75. package/kits/physics-3d/engine3d/paths.js +324 -0
  76. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  77. package/kits/physics-3d/engine3d/scatter.js +102 -0
  78. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  79. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  80. package/kits/physics-3d/engine3d/sweep.js +480 -0
  81. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  82. package/kits/physics-3d/engine3d/world3d.js +119 -17
  83. package/kits/physics-3d/eslint.config.js +13 -0
  84. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  85. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  86. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  87. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  88. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  89. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  90. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  91. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  92. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  93. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  94. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  95. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  96. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  97. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  98. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  99. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  100. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  101. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  102. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  103. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  104. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  105. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  106. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  107. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  108. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  109. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  110. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  111. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  112. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  113. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  114. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  115. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  116. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  117. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  118. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  119. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  120. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  121. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  122. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  123. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  124. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  125. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  126. package/kits/physics-3d/scripts/render/index.html +20 -0
  127. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  128. package/kits/physics-3d/scripts/render.mjs +646 -0
  129. package/kits/real-time/castle.json +2 -2
  130. package/kits/real-time/code/client/ownership.js +14 -4
  131. package/kits/real-time/code/client/smooth.js +2 -2
  132. package/kits/real-time/code/server/session.js +20 -4
  133. package/kits/turn-based/castle.json +1 -0
  134. package/package.json +2 -2
@@ -106,6 +106,48 @@ export interface EvaluateCharacterInformationInput {
106
106
  operationId: string;
107
107
  maxDeliveries?: number;
108
108
  }
109
+ export type CharacterStoryOpportunity = {
110
+ type: "approach" | "room_entry" | "world_action";
111
+ id: string;
112
+ };
113
+ export interface EvaluateCharacterBeatsInput {
114
+ operationId: string;
115
+ opportunityId: string;
116
+ opportunity: CharacterStoryOpportunity;
117
+ presentCharacterIds: string[];
118
+ }
119
+ export interface CharacterBeatSelection {
120
+ deliveryId: string;
121
+ beatId: string;
122
+ characterId: string;
123
+ openingText: string;
124
+ }
125
+ export interface CharacterBeatEvaluationResult {
126
+ operationId: string;
127
+ opportunityId: string;
128
+ opportunityCount: number;
129
+ gameTime: number | null;
130
+ selection: CharacterBeatSelection | null;
131
+ }
132
+ export type CharacterBeatEvaluationOperation = Omit<CharacterOperation, "result"> & {
133
+ result: CharacterBeatEvaluationResult | null;
134
+ };
135
+ export interface CompleteScheduledCharacterBeatInput {
136
+ operationId: string;
137
+ deliveryId: string;
138
+ outcomeId: string;
139
+ }
140
+ export interface CharacterScheduledBeatCompletionResult {
141
+ completionId: string;
142
+ deliveryId: string;
143
+ beatId: string;
144
+ characterId: string;
145
+ outcomeId: string;
146
+ completedAt: string;
147
+ }
148
+ export type CharacterScheduledBeatCompletionOperation = Omit<CharacterOperation, "result"> & {
149
+ result: CharacterScheduledBeatCompletionResult | null;
150
+ };
109
151
  export interface CharacterInformationEvaluationResult {
110
152
  generation: number;
111
153
  evaluatedAt: string;
@@ -153,6 +195,8 @@ export interface ServerPlaythroughCharacters {
153
195
  deliverKnowledge(input: DeliverCharacterKnowledgeInput): Promise<CharacterOperation>;
154
196
  completeBeat(input: CompleteCharacterBeatInput): Promise<CharacterOperation>;
155
197
  evaluateInformation(input: EvaluateCharacterInformationInput): Promise<CharacterInformationEvaluationOperation>;
198
+ evaluateBeats(input: EvaluateCharacterBeatsInput): Promise<CharacterBeatEvaluationOperation>;
199
+ completeScheduledBeat(input: CompleteScheduledCharacterBeatInput): Promise<CharacterScheduledBeatCompletionOperation>;
156
200
  status(operationId: string): Promise<CharacterOperation>;
157
201
  history(options?: ServerCharacterHistoryOptions): Promise<CharacterHistory>;
158
202
  }
@@ -159,6 +159,25 @@ function createPlaythrough(call, subject, generation) {
159
159
  ...(maxDeliveries === undefined ? {} : { maxDeliveries }),
160
160
  });
161
161
  },
162
+ async evaluateBeats(input) {
163
+ return call("characterEvaluateBeats", {
164
+ subject,
165
+ generation,
166
+ operationId: assertOperationId(input?.operationId),
167
+ opportunityId: assertOpportunityId(input?.opportunityId),
168
+ opportunity: assertStoryOpportunity(input?.opportunity),
169
+ presentCharacterIds: assertPresentCharacterIds(input?.presentCharacterIds),
170
+ });
171
+ },
172
+ async completeScheduledBeat(input) {
173
+ return call("characterCompleteScheduledBeat", {
174
+ subject,
175
+ generation,
176
+ operationId: assertOperationId(input?.operationId),
177
+ deliveryId: assertOpportunityId(input?.deliveryId, "deliveryId"),
178
+ outcomeId: assertNarrativeId(input?.outcomeId, "outcomeId"),
179
+ });
180
+ },
162
181
  async status(operationId) {
163
182
  return call("characterStatus", {
164
183
  subject,
@@ -343,6 +362,41 @@ function assertOperationId(value) {
343
362
  }
344
363
  return value;
345
364
  }
365
+ function assertOpportunityId(value, field = "opportunityId") {
366
+ if (typeof value !== "string" ||
367
+ value.length === 0 ||
368
+ value.length > MAX_OPERATION_ID_CHARACTERS ||
369
+ value.includes("\0") ||
370
+ hasUnpairedSurrogate(value) ||
371
+ utf8Length(value) > MAX_OPERATION_ID_BYTES) {
372
+ throw characterArgumentError(`${field} must be valid text of at most ${MAX_OPERATION_ID_CHARACTERS} characters and ${MAX_OPERATION_ID_BYTES} bytes.`);
373
+ }
374
+ return value;
375
+ }
376
+ function assertStoryOpportunity(value) {
377
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
378
+ throw characterArgumentError("opportunity must contain a type and id.");
379
+ }
380
+ const opportunity = value;
381
+ if (Object.keys(opportunity).some((key) => key !== "type" && key !== "id") ||
382
+ !["approach", "room_entry", "world_action"].includes(String(opportunity.type))) {
383
+ throw characterArgumentError("opportunity type is invalid.");
384
+ }
385
+ return {
386
+ type: opportunity.type,
387
+ id: assertNarrativeId(opportunity.id, "opportunity.id"),
388
+ };
389
+ }
390
+ function assertPresentCharacterIds(value) {
391
+ if (!Array.isArray(value) || value.length > 16) {
392
+ throw characterArgumentError("presentCharacterIds must contain at most 16 character ids.");
393
+ }
394
+ const ids = value.map((item) => assertNarrativeId(item, "presentCharacterIds"));
395
+ if (new Set(ids).size !== ids.length) {
396
+ throw characterArgumentError("presentCharacterIds must not contain duplicates.");
397
+ }
398
+ return ids.sort();
399
+ }
346
400
  function assertNarrativeId(value, field) {
347
401
  if (typeof value !== "string" ||
348
402
  value.length === 0 ||
@@ -1,5 +1,9 @@
1
1
  import { type CommandName, type CommandParams, type CommandResult, type LifecycleEvent } from "./commands";
2
2
  type PostChannel = "mobile" | "web";
3
+ export interface HostStreamOptions {
4
+ onStream?: (event: unknown) => void;
5
+ signal?: AbortSignal;
6
+ }
3
7
  interface ReactNativeWebViewBridge {
4
8
  postMessage: (message: string) => void;
5
9
  }
@@ -11,7 +15,7 @@ declare global {
11
15
  };
12
16
  }
13
17
  }
14
- export declare function hostRequest<C extends CommandName>(command: C, params: CommandParams[C]): Promise<CommandResult[C]>;
18
+ export declare function hostRequest<C extends CommandName>(command: C, params: CommandParams[C], stream?: HostStreamOptions): Promise<CommandResult[C]>;
15
19
  export declare function getCommandChannel(): PostChannel | "local";
16
20
  export declare function hostNotify(event: LifecycleEvent): void;
17
21
  export declare function postUnloadDone(unloadId: string, state?: string): void;
@@ -7,10 +7,14 @@
7
7
  // - web → window.parent.postMessage; responses via 'message' events
8
8
  // - local → the castle-web serve dev server, over runtime.ts's websocket
9
9
  // Error reconstruction is uniform here so callers always get a CastleError.
10
- import { CASTLE_SDK_PROTOCOL, isResponseEnvelope, unloadRequestId, } from "./commands";
10
+ //
11
+ // A streaming command (agent.chat) gets stream envelopes on its requestId before
12
+ // its response. Each one goes to the caller's onStream and restarts the wait,
13
+ // and the caller's AbortSignal sends the host a cancel envelope.
14
+ import { CASTLE_SDK_PROTOCOL, COMMAND_TIMEOUTS_MS, STREAM_IDLE_TIMEOUT_MS, isResponseEnvelope, isStreamEnvelope, unloadRequestId, } from "./commands";
11
15
  import { getCastleEmbed } from "./context";
12
16
  import { CastleError } from "./errors";
13
- import { sendLocalCommand } from "./runtime";
17
+ import { cancelLocalCommand, releaseLocalCommand, sendLocalCommand } from "./runtime";
14
18
  const REQUEST_TIMEOUT_MS = 15000;
15
19
  // Interactive platform commands hold the screen while the player interacts with
16
20
  // a host-native sheet (e.g. a pass purchase), so the flat data-command timeout
@@ -20,16 +24,16 @@ const INTERACTIVE_COMMANDS = new Set([
20
24
  "snapshot.offer",
21
25
  "portal.open",
22
26
  ]);
27
+ // Request ids carry a per-page prefix so that a host serving several decks at
28
+ // once can key a cancel by requestId alone.
29
+ const requestIdPrefix = `csdk_${Math.random().toString(36).slice(2, 10)}_`;
23
30
  let nextRequestId = 1;
24
31
  const pending = new Map();
25
32
  let listenersInstalled = false;
26
33
  let unloadHandler = null;
27
- export async function hostRequest(command, params) {
34
+ export async function hostRequest(command, params, stream = {}) {
28
35
  try {
29
- const channel = resolveChannel();
30
- const env = channel === "local"
31
- ? await sendLocalCommand(command, params)
32
- : await postCommand(channel, command, params);
36
+ const env = await sendCommand(resolveChannel(), command, params, stream);
33
37
  return interpretResponse(command, env);
34
38
  }
35
39
  catch (error) {
@@ -103,20 +107,84 @@ function resolveChannel() {
103
107
  // local dev server (top-level page served by `castle-web serve`).
104
108
  return window.parent && window.parent !== window ? "web" : "local";
105
109
  }
106
- function postCommand(channel, command, params) {
107
- installHostListener();
108
- const requestId = `csdk_${nextRequestId++}`;
110
+ function sendCommand(channel, command, params, stream) {
111
+ const requestId = `${requestIdPrefix}${nextRequestId++}`;
109
112
  return new Promise((resolve, reject) => {
110
- const timeout = INTERACTIVE_COMMANDS.has(command)
111
- ? undefined
112
- : setTimeout(() => {
113
- pending.delete(requestId);
114
- reject(new Error(`Castle host did not respond to ${command}.`));
115
- }, REQUEST_TIMEOUT_MS);
116
- pending.set(requestId, { resolve, reject, timeout });
113
+ if (stream.signal?.aborted) {
114
+ reject(cancelledError(command));
115
+ return;
116
+ }
117
+ const entry = { command, channel, resolve, reject, onStream: stream.onStream };
118
+ pending.set(requestId, entry);
119
+ restartTimeout(requestId, entry, COMMAND_TIMEOUTS_MS[command] ?? REQUEST_TIMEOUT_MS);
120
+ watchAbort(requestId, entry, stream.signal);
121
+ if (channel === "local") {
122
+ sendLocalCommand(requestId, command, params, receive).catch((error) => {
123
+ forget(requestId);
124
+ reject(error instanceof Error ? error : new Error(String(error)));
125
+ });
126
+ return;
127
+ }
128
+ installHostListener();
117
129
  sendEnvelope(channel, { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params });
118
130
  });
119
131
  }
132
+ // Interactive commands have no timeout; they resolve only when the host replies.
133
+ function restartTimeout(requestId, entry, ms) {
134
+ if (entry.timeout) {
135
+ clearTimeout(entry.timeout);
136
+ }
137
+ if (INTERACTIVE_COMMANDS.has(entry.command)) {
138
+ return;
139
+ }
140
+ entry.timeout = setTimeout(() => {
141
+ forget(requestId);
142
+ entry.reject(new Error(`Castle host did not respond to ${entry.command}.`));
143
+ }, ms);
144
+ }
145
+ function watchAbort(requestId, entry, signal) {
146
+ if (!signal) {
147
+ return;
148
+ }
149
+ const onAbort = () => {
150
+ forget(requestId);
151
+ if (entry.channel === "local") {
152
+ cancelLocalCommand(requestId);
153
+ }
154
+ else {
155
+ const envelope = {
156
+ castleSdk: CASTLE_SDK_PROTOCOL,
157
+ requestId,
158
+ cancel: true,
159
+ };
160
+ sendEnvelope(entry.channel, envelope);
161
+ }
162
+ entry.reject(cancelledError(entry.command));
163
+ };
164
+ signal.addEventListener("abort", onAbort, { once: true });
165
+ entry.stopWatchingAbort = () => signal.removeEventListener("abort", onAbort);
166
+ }
167
+ function forget(requestId) {
168
+ const entry = pending.get(requestId);
169
+ if (!entry) {
170
+ return;
171
+ }
172
+ pending.delete(requestId);
173
+ if (entry.timeout) {
174
+ clearTimeout(entry.timeout);
175
+ }
176
+ entry.stopWatchingAbort?.();
177
+ if (entry.channel === "local") {
178
+ releaseLocalCommand(requestId);
179
+ }
180
+ }
181
+ function cancelledError(command) {
182
+ return new CastleError({
183
+ code: "CANCELLED",
184
+ message: `${command} was cancelled.`,
185
+ operation: command,
186
+ });
187
+ }
120
188
  function sendEnvelope(channel, envelope) {
121
189
  const json = JSON.stringify(envelope);
122
190
  if (channel === "mobile") {
@@ -146,21 +214,36 @@ function receive(message) {
146
214
  settle(message);
147
215
  return;
148
216
  }
217
+ if (isStreamEnvelope(message)) {
218
+ deliverStream(message.requestId, message.stream);
219
+ return;
220
+ }
149
221
  const unloadId = unloadRequestId(message);
150
222
  if (unloadId !== null)
151
223
  unloadHandler?.(unloadId);
152
224
  }
153
225
  function settle(message) {
154
- if (!isResponseEnvelope(message))
155
- return;
156
226
  const entry = pending.get(message.requestId);
157
- if (!entry)
227
+ if (!entry) {
158
228
  return;
159
- if (entry.timeout)
160
- clearTimeout(entry.timeout);
161
- pending.delete(message.requestId);
229
+ }
230
+ forget(message.requestId);
162
231
  entry.resolve(message);
163
232
  }
233
+ // A throwing onStream is logged, and the stream goes on.
234
+ function deliverStream(requestId, event) {
235
+ const entry = pending.get(requestId);
236
+ if (!entry) {
237
+ return;
238
+ }
239
+ restartTimeout(requestId, entry, STREAM_IDLE_TIMEOUT_MS);
240
+ try {
241
+ entry.onStream?.(event);
242
+ }
243
+ catch (error) {
244
+ console.error(`Castle ${entry.command} stream handler threw:`, error);
245
+ }
246
+ }
164
247
  function interpretResponse(command, env) {
165
248
  if (env.ok)
166
249
  return env.data;
@@ -1,20 +1,21 @@
1
1
  {
2
2
  "title": "multiplayer-2d",
3
+ "description": "Multiplayer. The Scene Editor, with multiple players in the same session.",
3
4
  "editor": {
4
5
  "defaultPlayFile": "scenes/main.scene"
5
6
  },
6
7
  "imports": {
7
8
  "castle.real-time": {
8
9
  "deckId": "xFVr-afOLuUQ",
9
- "version": "2026-09-22T19:48:58.226Z"
10
+ "version": "2026-09-24T07:00:06.238Z"
10
11
  },
11
12
  "castle.physics-2d": {
12
13
  "deckId": "ckRZGFW4iPrx",
13
- "version": "2026-09-22T19:49:07.246Z"
14
+ "version": "2026-09-23T02:16:34.231Z"
14
15
  },
15
16
  "castle.base": {
16
17
  "deckId": "yRcmH4_aYllE",
17
- "version": "2026-09-22T19:48:55.642Z"
18
+ "version": "2026-09-24T02:13:40.120Z"
18
19
  }
19
20
  },
20
21
  "autoUpdateWhenImported": true,
@@ -26,5 +27,5 @@
26
27
  },
27
28
  "deckId": "oiFu96LkwZ09",
28
29
  "cardId": "nkJgrvrCby3H",
29
- "publishedVersion": "2026-09-22T19:49:27.017Z"
30
+ "publishedVersion": "2026-09-24T18:05:54.492Z"
30
31
  }
@@ -52,6 +52,13 @@ export function packPose(x, y, angle) {
52
52
  return [position(x), position(y), radians(angle)];
53
53
  }
54
54
 
55
+ // Pack a body's velocity as `[vx, vy, spin]` in matter's own units: pixels and
56
+ // radians per 1/60 s. It follows an owned object's pose in a move report and a
57
+ // grant in a handover.
58
+ export function packVelocity(velocity, spin) {
59
+ return [position(velocity.x), position(velocity.y), radians(spin)];
60
+ }
61
+
55
62
  // Pack a character as `[x, y, facing, clamped]`. `facing` is the direction it is
56
63
  // moving and affects only the drawing.
57
64
  //
@@ -43,6 +43,9 @@ export const OWNER_TIMEOUT_MS = 1500;
43
43
  // by a character travels a few hundred pixels a second.
44
44
  export const MAX_OBJECT_SPEED = 1500;
45
45
 
46
+ // Cap the spin an owner may report, in radians per second.
47
+ export const MAX_OBJECT_SPIN = 60;
48
+
46
49
  //
47
50
  // Server-side corrections
48
51
  //
@@ -7,9 +7,16 @@
7
7
  // it makes lands in `handovers`, which the session broadcasts the same tick.
8
8
 
9
9
  import Matter from 'matter-js';
10
- import { number } from '@imports/castle.real-time/code/server/limits.js';
10
+ import { clamp, number } from '@imports/castle.real-time/code/server/limits.js';
11
+ import { packVelocity } from '../client/poses.js';
11
12
  import * as Limits from './limits.js';
12
13
 
14
+ // A velocity of zero, for an owner that never reported one.
15
+ const AT_REST = [0, 0, 0];
16
+
17
+ // Matter velocities are per 1/60 s, whatever rate the world steps at.
18
+ const STEPS_PER_SECOND = 60;
19
+
13
20
  // Grant requested objects that are claimable, in reach, and available to this
14
21
  // player. Server-side grants provide one authoritative owner for each object.
15
22
  export function claim(sim, playerId, ids, handovers) {
@@ -80,30 +87,40 @@ function mayTakeOver(sim, entry, claimant, at) {
80
87
  // Assign one object to `playerId`, or to server simulation when it is null, and
81
88
  // append the change to the current broadcast when a list was supplied.
82
89
  function handOver(sim, entry, id, playerId, handovers) {
90
+ // An owned object moves at the velocity its owner last reported. A static
91
+ // body's own velocity follows the report rate, not the object.
92
+ const velocity = entry.owner
93
+ ? (entry.velocity ?? AT_REST)
94
+ : packVelocity(Matter.Body.getVelocity(entry.body), Matter.Body.getAngularVelocity(entry.body));
95
+
83
96
  // Both timestamps start at the handover tick. reportedAt drives expiration;
84
97
  // claimedAt enforces the minimum hold before a proximity-based takeover.
85
98
  entry.owner = playerId;
86
99
  entry.reportedAt = sim.timeMs;
87
100
  entry.claimedAt = sim.timeMs;
101
+ entry.velocity = velocity;
88
102
  if (playerId) {
89
103
  // An owned object is placed from client reports. Static mode prevents server
90
104
  // physics from moving it while retaining collision response for other bodies.
91
105
  Matter.Body.setStatic(entry.body, true);
92
106
  } else {
93
- // Server simulation resumes in dynamic mode at rest. Client-only velocity
94
- // is not a valid initial velocity for the server's Matter world.
107
+ // Server simulation resumes in dynamic mode at the velocity the object had,
108
+ // so a sliding crate is still sliding when the server takes it back.
109
+ const [vx, vy, spin] = velocity;
95
110
  Matter.Body.setStatic(entry.body, false);
96
- Matter.Body.setVelocity(entry.body, { x: 0, y: 0 });
97
- Matter.Body.setAngularVelocity(entry.body, 0);
111
+ Matter.Body.setVelocity(entry.body, { x: vx, y: vy });
112
+ Matter.Body.setAngularVelocity(entry.body, spin);
98
113
  }
99
114
 
100
115
  // On the wire, zero identifies server ownership and a player id identifies a grant.
116
+ // The velocity follows, and a new owner starts its local body at it.
101
117
  // The list is optional so a deck hook can reuse this outside a broadcast.
102
- handovers?.push([id, playerId ?? 0]);
118
+ handovers?.push([id, playerId ?? 0, ...velocity]);
103
119
  }
104
120
 
105
121
  // Apply the poses reported for the objects granted to `playerId`. A report for
106
- // an object owned by somebody else, or by nobody, is ignored.
122
+ // an object owned by somebody else, or by nobody, is ignored. A pose may be
123
+ // followed by the object's velocity, which the object keeps when handed over.
107
124
  export function setObjectPoses(sim, playerId, poses, handovers) {
108
125
  if (!Array.isArray(poses)) {
109
126
  return;
@@ -111,7 +128,7 @@ export function setObjectPoses(sim, playerId, poses, handovers) {
111
128
 
112
129
  // Sixteen checks per message bound the validation work requested by one client.
113
130
  for (const pose of poses.slice(0, 16)) {
114
- const [id, x, y, angle] = pose;
131
+ const [id, x, y, angle, ...velocity] = pose;
115
132
  const entry = sim.objects.get(id);
116
133
  if (entry?.owner !== playerId) {
117
134
  continue;
@@ -141,9 +158,20 @@ export function setObjectPoses(sim, playerId, poses, handovers) {
141
158
  // lets an owned crate transfer an impulse to server-simulated bodies.
142
159
  Matter.Body.setPosition(entry.body, to, true);
143
160
  Matter.Body.setAngle(entry.body, number(angle));
161
+ entry.velocity = readVelocity(velocity);
144
162
  }
145
163
  }
146
164
 
165
+ // Read a reported velocity. Missing values read as zero, and each part is cut
166
+ // to the object limits so a report cannot fling the object on return.
167
+ function readVelocity([vx, vy, spin]) {
168
+ const most = Limits.MAX_OBJECT_SPEED / STEPS_PER_SECOND;
169
+ const speed = Math.hypot(number(vx), number(vy));
170
+ const scale = speed > most ? most / speed : 1;
171
+ const turn = Limits.MAX_OBJECT_SPIN / STEPS_PER_SECOND;
172
+ return [number(vx) * scale, number(vy) * scale, clamp(number(spin), -turn, turn)];
173
+ }
174
+
147
175
  // Release objects whose owner left or stopped reporting. The shared session
148
176
  // calls this every tick before it processes new grants.
149
177
  export function sweepOwners(sim, handovers) {
@@ -184,6 +184,7 @@ class MultiplayerSystem {
184
184
  // Apply ownership before poses so a newly granted object stops consuming
185
185
  // network poses on the first frame of local simulation.
186
186
  Ownership.applyHandovers(this.own, msg.own, selfId);
187
+ startGranted(scene, msg.own, selfId);
187
188
  for (const [id, x, y, facing, clamped] of msg.ps ?? []) {
188
189
  if (id !== selfId) {
189
190
  sample(this.players, msg, id, [x, y, facing]);
@@ -343,12 +344,17 @@ class MultiplayerSystem {
343
344
  const releases = Ownership.toRelease(this.own, objects, me, Poses.REACH);
344
345
 
345
346
  // Only granted objects are reported, because the server ignores a pose for
346
- // any other id.
347
+ // any other id. The velocity after each pose is what the object keeps when
348
+ // handed on.
347
349
  const owned = [];
348
350
  for (const [id] of objects) {
349
351
  const actor = this.own.mine.has(id) && scene.getActor(id);
350
352
  if (actor) {
351
- owned.push([id, ...Poses.poseOf(actor.components.Layout)]);
353
+ const body = scene.physics.bodyFor(actor);
354
+ const velocity = body
355
+ ? Poses.packVelocity(Matter.Body.getVelocity(body), Matter.Body.getAngularVelocity(body))
356
+ : [];
357
+ owned.push([id, ...Poses.poseOf(actor.components.Layout), ...velocity]);
352
358
  }
353
359
  }
354
360
 
@@ -494,6 +500,21 @@ function sample(tracks, msg, id, pose) {
494
500
  Interpolate.pushSample(track, msg.t, pose, Poses.same);
495
501
  }
496
502
 
503
+ // Start each object granted to this player at the velocity its handover
504
+ // carries. Until the grant, network poses placed its local body at rest.
505
+ function startGranted(scene, handovers, selfId) {
506
+ for (const [id, playerId, ...velocity] of handovers ?? []) {
507
+ const actor = playerId === selfId && velocity.length === 3 && scene.getActor(id);
508
+ const body = actor && scene.physics.bodyFor(actor);
509
+ if (!body) {
510
+ continue;
511
+ }
512
+ const [vx, vy, spin] = velocity;
513
+ Matter.Body.setVelocity(body, { x: vx, y: vy });
514
+ Matter.Body.setAngularVelocity(body, spin);
515
+ }
516
+ }
517
+
497
518
  // Put an actor's matter body where its Layout now says, at rest. The next
498
519
  // network sample supplies the position after this one.
499
520
  function writeBody(scene, actor, angle) {
@@ -191,13 +191,24 @@ Poses)`, `toClaim(..., Poses.REACH)`.
191
191
  are filed under `msg.t`, never under arrival. A `WORLD` message is the room as
192
192
  it is, so it REPLACES a track rather than landing on top of a stale one. Our
193
193
  own entry in `msg.ps` is news only when its `clamped` flag is set.
194
+ Object rows carry an ownership epoch: a `msg.os` row is `[id, ...pose,
195
+ epoch]`, a handover in `msg.own` is `[id, owner, ...velocity, epoch]`, and a
196
+ `WORLD`'s `msg.own` has one such row for every object with 1 on the end when
197
+ it is asleep. Strip the epoch before filing the pose, drop a pose from an
198
+ epoch older than the object's newest handover, and start the object's track
199
+ over at each handover. An owned object's report ends in `epoch, seq, base`
200
+ (`reportTail` in the kit's system); `msg.ack` acknowledges them.
194
201
  3. **Draw**, at `renderTime(clock, performance.now())`, and only once
195
202
  `ready(clock)`: `sampleAt` -> `smooth` -> `Poses.applyPose`. Write the rapier body
196
203
  as well as the Transform (`scene.physics3d.bodyOf(actor)`) — rapier writes a
197
204
  dynamic body's pose back over the Transform every frame, so the Transform
198
205
  alone is discarded. Skip anything in `own.mine`: writing the server's older
199
206
  copy over the copy this client is simulating is the fight that stops a push
200
- from landing.
207
+ from landing. The kit's system draws only distant objects this way. A
208
+ dynamic object near the player is a live body steered toward the network's
209
+ present (`client/steer.js`), and so is one this client has just let go of;
210
+ an object changes between the two only at rest. A pose that has not changed
211
+ is not written again.
201
212
  4. **Accept the clamp.** Ease onto `clampedTo` over a few frames; take it at once
202
213
  only past a few metres, where easing would read as sliding.
203
214
  5. **Report.** `toClaim` / `toRelease` over the claimable actors, `Poses.poseOf`
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "title": "multiplayer-3d",
3
+ "description": "Multiplayer with 3D (experimental). The Scene Editor 3D, with multiple players in the same session.",
3
4
  "editor": {
4
5
  "defaultPlayFile": "scenes/main.scene"
5
6
  },
6
7
  "imports": {
7
8
  "castle.real-time": {
8
9
  "deckId": "xFVr-afOLuUQ",
9
- "version": "2026-09-22T19:48:58.226Z"
10
+ "version": "2026-09-24T08:31:35.178Z"
10
11
  },
11
12
  "castle.physics-3d": {
12
13
  "deckId": "JH0SclbPVP0y",
@@ -14,18 +15,18 @@
14
15
  },
15
16
  "castle.physics-2d": {
16
17
  "deckId": "ckRZGFW4iPrx",
17
- "version": "2026-09-22T19:49:07.246Z",
18
+ "version": "2026-09-23T02:16:34.231Z",
18
19
  "via": "castle.physics-3d"
19
20
  },
20
21
  "castle.base": {
21
22
  "deckId": "yRcmH4_aYllE",
22
- "version": "2026-09-22T19:48:55.642Z"
23
+ "version": "2026-09-24T02:13:40.120Z"
23
24
  }
24
25
  },
25
26
  "autoUpdateWhenImported": true,
26
27
  "deckId": "ZwA_P_-VO-Qh",
27
28
  "cardId": "bvRmCzyUpt_a",
28
- "publishedVersion": "2026-09-22T19:49:32.861Z",
29
+ "publishedVersion": "2026-09-24T18:45:09.264Z",
29
30
  "main": "main.jsx",
30
31
  "server": {
31
32
  "main": "code/server/index.js",
@@ -146,8 +146,14 @@ function dressHead(scene, actorId, userId) {
146
146
  return;
147
147
  }
148
148
 
149
+ // The picture is laid out on a box's faces. A head of any other geometry
150
+ // keeps its own material.
151
+ const { width, height, depth } = mesh.geometry.parameters ?? {};
152
+ if (!width || !height || !depth) {
153
+ return;
154
+ }
155
+
149
156
  // White under the picture, so the head's skin color does not tint it.
150
- const { width, height, depth } = mesh.geometry.parameters;
151
157
  const dressed = makeShapeMesh(
152
158
  { kind: 'box', width, height, depth, color: '#ffffff', art: { sides: path, front: path } },
153
159
  scene.sprites,