castle-web-cli 0.4.193 → 0.4.194

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 (75) hide show
  1. package/dist/agent.js +87 -4
  2. package/dist/api.d.ts +1 -0
  3. package/dist/api.js +5 -0
  4. package/dist/bundle.js +2 -1
  5. package/dist/castleJson.d.ts +1 -0
  6. package/dist/check.js +14 -6
  7. package/dist/devSessionServer.d.ts +6 -0
  8. package/dist/devSessionServer.js +23 -1
  9. package/dist/filesChanged.js +7 -3
  10. package/dist/importUpdateHook.d.ts +31 -0
  11. package/dist/importUpdateHook.js +135 -0
  12. package/dist/importUpdateHookRunner.d.ts +2 -0
  13. package/dist/importUpdateHookRunner.js +24 -0
  14. package/dist/imports.js +56 -6
  15. package/dist/index.js +58 -7
  16. package/dist/init.d.ts +1 -0
  17. package/dist/init.js +6 -1
  18. package/dist/native/loop.js +29 -9
  19. package/dist/platformDoc.js +4 -4
  20. package/dist/remix.js +4 -1
  21. package/dist/serve.js +133 -32
  22. package/dist/serverBundle.js +1 -1
  23. package/dist/versions.d.ts +14 -0
  24. package/dist/versions.js +21 -0
  25. package/dist/vitePlugins.d.ts +1 -0
  26. package/dist/vitePlugins.js +18 -0
  27. package/kits/multiplayer-2d/CLAUDE.md +9 -2
  28. package/kits/multiplayer-2d/blueprints/crate.scene +32 -4
  29. package/kits/multiplayer-2d/blueprints/other-player.scene +31 -4
  30. package/kits/multiplayer-2d/blueprints/player.scene +38 -6
  31. package/kits/multiplayer-2d/blueprints/wall.scene +25 -3
  32. package/kits/multiplayer-2d/castle.json +3 -3
  33. package/kits/multiplayer-2d/test/two-client-test.mjs +4 -4
  34. package/kits/multiplayer-3d/CLAUDE.md +5 -2
  35. package/kits/multiplayer-3d/castle.json +3 -3
  36. package/kits/multiplayer-3d/scenes/main.scene +128 -0
  37. package/kits/physics-2d/CLAUDE.md +11 -5
  38. package/kits/physics-2d/behaviors/Camera.jsx +5 -6
  39. package/kits/physics-2d/behaviors/Goal.jsx +5 -2
  40. package/kits/physics-2d/behaviors/Joints.jsx +4 -3
  41. package/kits/physics-2d/behaviors/Layout.jsx +120 -3
  42. package/kits/physics-2d/behaviors/Sprite.jsx +9 -9
  43. package/kits/physics-2d/behaviors/Style.jsx +22 -15
  44. package/kits/physics-2d/behaviors/Text.jsx +7 -6
  45. package/kits/physics-2d/blueprints/ball.scene +27 -5
  46. package/kits/physics-2d/blueprints/block.scene +16 -3
  47. package/kits/physics-2d/blueprints/cauldron.scene +3 -1
  48. package/kits/physics-2d/blueprints/crate.scene +23 -4
  49. package/kits/physics-2d/blueprints/goal.scene +12 -2
  50. package/kits/physics-2d/blueprints/text.scene +13 -3
  51. package/kits/physics-2d/castle.json +2 -1
  52. package/kits/physics-2d/editors/SceneEditor.jsx +26 -2
  53. package/kits/physics-2d/editors/SelectionOverlay.jsx +27 -20
  54. package/kits/physics-2d/engine/blueprint.js +111 -54
  55. package/kits/physics-2d/engine/blueprintCore.js +59 -0
  56. package/kits/physics-2d/engine/collider.js +28 -17
  57. package/kits/physics-2d/engine/layout.js +61 -0
  58. package/kits/physics-2d/engine/layoutOriginMigration.js +223 -0
  59. package/kits/physics-2d/engine/physics/PhysicsSystem.js +11 -7
  60. package/kits/physics-2d/engine/physics/controls.js +4 -8
  61. package/kits/physics-2d/engine/physics/matterBridge.js +13 -8
  62. package/kits/physics-2d/engine/scene.js +38 -34
  63. package/kits/physics-2d/engine/spriteGeometry.js +17 -9
  64. package/kits/physics-2d/engine/tap.js +4 -3
  65. package/kits/physics-2d/scenes/main.scene +59 -6
  66. package/kits/physics-2d/scenes/sandbox.scene +69 -7
  67. package/kits/physics-2d/scripts/onUpdate.mjs +199 -0
  68. package/kits/real-time/castle.json +2 -2
  69. package/kits/real-time/code/server/persist.js +14 -0
  70. package/kits/turn-based/CLAUDE.md +12 -7
  71. package/kits/turn-based/blueprints/board.scene +3 -1
  72. package/kits/turn-based/blueprints/square.scene +3 -1
  73. package/kits/turn-based/castle.json +5 -3
  74. package/kits/turn-based/code/behaviors/Board.jsx +33 -21
  75. package/package.json +1 -1
@@ -0,0 +1,223 @@
1
+ // Stamping `originX: 0, originY: 0` into a deck authored before the Layout
2
+ // origin defaulted to CENTER.
3
+ //
4
+ // `Layout.originX/originY` say which point of the box `x`/`y` names, and an
5
+ // absent origin now means the center (`engine/layout.js`). Every actor in a deck
6
+ // written before that change omits the origin and means the TOP-LEFT, so the new
7
+ // engine would move all of them by half their size.
8
+ //
9
+ // The migration writes the old meaning down. It is deliberately NOT a conversion
10
+ // to center: deck code reads `Layout.x` as the top-left (clamps, bounce tests,
11
+ // `x + width / 2`) and rewriting that is not something a migration can do. So
12
+ // nothing moves, every deck keeps rendering exactly as it did, and a creator
13
+ // converts a blueprint to center when they want to, from the inspector's Origin
14
+ // select (`setBlueprintOriginCascade`, which compensates the instances).
15
+ //
16
+ // Pure: `stampTopLeftOrigin` takes a file map and hands back the writes.
17
+ // `scripts/onUpdate.mjs` is the side that reads and writes the disk, and it is
18
+ // what the CLI runs as this kit's `onUpdate` hook.
19
+ //
20
+ // Known residual: a `scene.spawnActor({ components: { Layout: {...} } })` in
21
+ // deck code has no file to stamp and takes the center default at runtime. There
22
+ // is no file to fix, so the hook only points at them.
23
+ import { isBlueprintPath, parseBlueprintText } from './blueprintCore.js';
24
+
25
+ // The last kit version published with a top-left default -- the kit's
26
+ // `publishedVersion` as committed on `main` before the center-origin release.
27
+ // RE-CONFIRM THIS AT RELEASE: it is the whole gate, and a value from the wrong
28
+ // side of the release either misses every old deck or stamps top-left onto data
29
+ // somebody authored as center. See `.claude/skills/release/SKILL.md`.
30
+ export const LAST_TOP_LEFT_PUBLISHED_VERSION = '2026-09-13T17:33:26.446Z';
31
+
32
+ // Kit versions are the server's `updatedAt`, so a plain string compare orders
33
+ // them -- but only for a real ISO timestamp, which is why the shape is checked
34
+ // rather than assumed.
35
+ const ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
36
+
37
+ function isIsoVersion(value) {
38
+ return typeof value === 'string' && ISO_RE.test(value);
39
+ }
40
+
41
+ /**
42
+ * Whether this particular update is the one that changes what an absent origin
43
+ * means for this deck.
44
+ *
45
+ * The gate is on `from` and it is load-bearing: an omitted origin is ambiguous
46
+ * on disk -- in an old deck it means top-left, in a new one it means center on
47
+ * purpose -- so the pin the deck was sitting at is the only thing that can tell
48
+ * them apart. A deck already on a post-release kit is never touched, and neither
49
+ * is a deck moving between two pre-release versions.
50
+ */
51
+ export function needsTopLeftStamp({ from, to } = {}) {
52
+ if (!isIsoVersion(from) || !isIsoVersion(to)) return false;
53
+ return from <= LAST_TOP_LEFT_PUBLISHED_VERSION && to > LAST_TOP_LEFT_PUBLISHED_VERSION;
54
+ }
55
+
56
+ // An 8-line mirror of the SDK's `resolveDeckFile` / `deckPrefixOf`
57
+ // (`sdk/src/files.ts`), which stays canonical -- this module has to be readable
58
+ // by plain Node, and the SDK is a browser package. Change it there first.
59
+ const IMPORTS_PREFIX = '@imports/';
60
+ const IMPORTS_DIR = 'imports';
61
+
62
+ function deckPrefixOf(filePath) {
63
+ const match = new RegExp(`^(${IMPORTS_DIR}/[^/]+/)`).exec(filePath ?? '');
64
+ return match ? match[1] : '';
65
+ }
66
+
67
+ function resolveRef(ref, from) {
68
+ const raw = String(ref ?? '').replace(/^\.\//, '');
69
+ if (raw.startsWith(IMPORTS_PREFIX)) return `${IMPORTS_DIR}/${raw.slice(IMPORTS_PREFIX.length)}`;
70
+ return deckPrefixOf(String(from ?? '').replace(/^\.\//, '')) + raw;
71
+ }
72
+
73
+ // Whether the deck may write this file at all. Everything under `imports/`
74
+ // belongs to the deck it came from -- unless this deck forked it, in which case
75
+ // the deck's own `forks/<alias>/<inner>` is what gets written and the imported
76
+ // path is only where the text is keyed.
77
+ function isOwned(path, forks) {
78
+ return !path.startsWith(`${IMPORTS_DIR}/`) || forks[path] !== undefined;
79
+ }
80
+
81
+ function writePathFor(path, forks) {
82
+ return forks[path] ?? path;
83
+ }
84
+
85
+ // One axis at a time, and only where nothing is written: an instance that
86
+ // already states `originX` means it, and its own axis stays whatever it says.
87
+ // Returns whether anything was added.
88
+ function stampLayout(layout) {
89
+ let stamped = false;
90
+ if (layout.originX === undefined) {
91
+ layout.originX = 0;
92
+ stamped = true;
93
+ }
94
+ if (layout.originY === undefined) {
95
+ layout.originY = 0;
96
+ stamped = true;
97
+ }
98
+ return stamped;
99
+ }
100
+
101
+ // A blueprint template: the origin is inherited, so stamping it here is what
102
+ // covers every instance that doesn't state one. A template with no `Layout` gets
103
+ // nothing -- there is no box to anchor.
104
+ function stampTemplate(data) {
105
+ const layout = data?.actors?.[0]?.components?.Layout;
106
+ if (!layout || typeof layout !== 'object') return false;
107
+ return stampLayout(layout);
108
+ }
109
+
110
+ // Whether an actor's origin comes from a template this migration is also
111
+ // stamping. That is the only case an instance can be left alone in: it inherits
112
+ // the `0` about to be written on the template, and a one-axis override of its
113
+ // own keeps that axis.
114
+ function inheritsStamp(actor, scenePath, files, forks) {
115
+ if (typeof actor?.blueprint !== 'string' || !actor.blueprint) return false;
116
+ const key = resolveRef(actor.blueprint, scenePath);
117
+ if (!isOwned(key, forks) || !isBlueprintPath(key)) return false;
118
+ // Dangling or tombstoned: nothing will be stamped there, so the instance's own
119
+ // Layout is all the origin it has.
120
+ return parseBlueprintText(files[key]) !== null;
121
+ }
122
+
123
+ // Every actor in one scene. An actor that inherits from a stamped template needs
124
+ // nothing; anything else -- an orphan (the pre-blueprint shape), an instance of
125
+ // an import's blueprint, an instance whose template is gone -- carries its own
126
+ // origin and gets it written down.
127
+ //
128
+ // An instance of an import's template may have no `Layout` at all, because it
129
+ // inherited every field of it. It gets one: the origin is the one thing about
130
+ // that box this deck now has to state, and it cannot state it on a file it
131
+ // doesn't own.
132
+ function stampSceneActors(data, scenePath, files, forks, stats) {
133
+ let stamped = false;
134
+ for (const actor of data?.actors ?? []) {
135
+ if (!actor || typeof actor !== 'object') continue;
136
+ if (inheritsStamp(actor, scenePath, files, forks)) continue;
137
+ const orphan = !actor.blueprint;
138
+ const layout = actor.components?.Layout;
139
+ // An orphan with no Layout has no box; an instance with no Layout inherits
140
+ // one from a template this migration cannot write.
141
+ if (orphan && (!layout || typeof layout !== 'object')) continue;
142
+ if (!layout || typeof layout !== 'object') {
143
+ actor.components = { ...(actor.components ?? {}), Layout: { originX: 0, originY: 0 } };
144
+ stats.instances += 1;
145
+ stamped = true;
146
+ continue;
147
+ }
148
+ if (!stampLayout(layout)) continue;
149
+ if (orphan) stats.orphans += 1;
150
+ else stats.instances += 1;
151
+ stamped = true;
152
+ }
153
+ return stamped;
154
+ }
155
+
156
+ // Re-serialize `data` the way `text` was written, so a migration shows up as
157
+ // added `originX`/`originY` lines and nothing else. A compact one-line scene
158
+ // stays one line; anything else keeps the indent it used and its trailing
159
+ // newline. Key order comes free from the JSON round trip -- the two new keys
160
+ // land at the end of the Layout object.
161
+ function reserializeLike(text, data) {
162
+ if (!text.includes('\n')) return JSON.stringify(data);
163
+ const indentMatch = /\n([ \t]+)/.exec(text);
164
+ const indent = indentMatch ? (indentMatch[1][0] === '\t' ? '\t' : indentMatch[1].length) : 2;
165
+ return JSON.stringify(data, null, indent) + (text.endsWith('\n') ? '\n' : '');
166
+ }
167
+
168
+ function emptyStats() {
169
+ return {
170
+ /** Deck-owned `.scene` files looked at. */
171
+ considered: 0,
172
+ /** Blueprint templates stamped. */
173
+ templates: 0,
174
+ /** Instance Layouts stamped or created. */
175
+ instances: 0,
176
+ /** Orphan-actor Layouts stamped. */
177
+ orphans: 0,
178
+ /** Paths under `imports/` this deck has not forked, so never written. */
179
+ skippedImported: [],
180
+ /** Paths whose JSON did not parse, so never written. */
181
+ unparseable: [],
182
+ };
183
+ }
184
+
185
+ /**
186
+ * The writes that state a pre-origin deck's top-left anchoring outright.
187
+ *
188
+ * @param files every `.scene` in the deck as whole-deck key -> text, INCLUDING
189
+ * the ones under `imports/` (a template has to be readable to know
190
+ * whether an instance inherits from it). A forked file's text is
191
+ * keyed at the imported path it stands in for.
192
+ * @param forks imported path -> the `forks/<alias>/<inner>` path that overlays
193
+ * it, for the ones this deck has forked.
194
+ * @returns `{ writes: [{ path, text }], stats }`. Pure -- nothing is read from
195
+ * or written to disk here.
196
+ */
197
+ export function stampTopLeftOrigin(files, { forks = {} } = {}) {
198
+ const writes = [];
199
+ const stats = emptyStats();
200
+ for (const path of Object.keys(files ?? {}).sort()) {
201
+ if (!path.endsWith('.scene')) continue;
202
+ if (!isOwned(path, forks)) {
203
+ stats.skippedImported.push(path);
204
+ continue;
205
+ }
206
+ let data;
207
+ try {
208
+ data = JSON.parse(files[path]);
209
+ } catch {
210
+ stats.unparseable.push(path);
211
+ continue;
212
+ }
213
+ stats.considered += 1;
214
+ const blueprint = isBlueprintPath(path);
215
+ const changed = blueprint
216
+ ? stampTemplate(data)
217
+ : stampSceneActors(data, path, files, forks, stats);
218
+ if (!changed) continue;
219
+ if (blueprint) stats.templates += 1;
220
+ writes.push({ path: writePathFor(path, forks), text: reserializeLike(files[path], data) });
221
+ }
222
+ return { writes, stats };
223
+ }
@@ -11,6 +11,7 @@ import { isBehaviorEnabled } from '../scene';
11
11
 
12
12
  import Matter from 'matter-js';
13
13
  import { getColliderRect } from '../collider';
14
+ import { layoutCenter } from '../layout';
14
15
  import { buildJointConstraints, jointSignature, patchJoint } from './joints';
15
16
  import {
16
17
  DEFAULT_GRAVITY,
@@ -187,6 +188,10 @@ export class PhysicsSystem {
187
188
  const body = createBody(actor, rect);
188
189
  const center = rectCenter(rect);
189
190
  const layout = actor.components.Layout;
191
+ // A pure delta from the stored `x`/`y` to the collider AABB center, so the
192
+ // origin needs no mention here: the rect already had it applied, and
193
+ // `writeBack` subtracts the same delta again. `bodySignature` carries the
194
+ // origin so an origin edit mid-play rebuilds this cache.
190
195
  const offset = { dx: center.x - layout.x, dy: center.y - layout.y };
191
196
  // Cache what physics last wrote so a later Layout write can be detected
192
197
  // with !== (raw values: an omitted rotation stays undefined).
@@ -497,7 +502,10 @@ export class PhysicsSystem {
497
502
  const layout = this.layoutOf(actor);
498
503
  if (layout) layout.rotation = deg;
499
504
  },
500
- // Layout top-left convention (not body center).
505
+ // Layout convention (not body center): `x`/`y` are the point of the box
506
+ // named by `originX`/`originY` -- the box center when absent (see
507
+ // DEFAULT_ORIGIN_* in engine/layout.js). `scene.layoutRect(actor)` reads
508
+ // the box back.
501
509
  setPosition: (actor, { x, y }) => {
502
510
  const layout = this.layoutOf(actor);
503
511
  if (!layout) return;
@@ -541,11 +549,11 @@ export class PhysicsSystem {
541
549
  const joints = actor.components.Joints;
542
550
  const list = isBehaviorEnabled(joints) ? joints?.list : null;
543
551
  if (!Array.isArray(list)) continue;
544
- const a = centerOfLayout(actor.components.Layout);
552
+ const a = layoutCenter(actor.components.Layout);
545
553
  for (const joint of list) {
546
554
  const target = joint?.target && scene.getActor(joint.target);
547
555
  if (!target || !a) continue;
548
- const b = centerOfLayout(target.components.Layout);
556
+ const b = layoutCenter(target.components.Layout);
549
557
  if (!b) continue;
550
558
  out.push({
551
559
  ownerId: actor.id,
@@ -562,10 +570,6 @@ export class PhysicsSystem {
562
570
  }
563
571
  }
564
572
 
565
- function centerOfLayout(L) {
566
- return L ? { x: L.x + (L.width ?? 0) / 2, y: L.y + (L.height ?? 0) / 2 } : null;
567
- }
568
-
569
573
  function pairKey(a, b) {
570
574
  return a < b ? `${a}|${b}` : `${b}|${a}`;
571
575
  }
@@ -5,6 +5,7 @@
5
5
  // through scene.physics. (Controls are touch/pointer-first; keyboard, when
6
6
  // added, should only DUPLICATE an on-screen control, never be the only input.)
7
7
  // Stick force-mode math lives in AnalogStick.jsx — it has no other consumer.
8
+ import { layoutCenter } from '../layout';
8
9
 
9
10
  // Authored Draggable `stiffness` (0..1, 0 = floppy .. 1 = rigid) -> the matter
10
11
  // constraint values that hold the object. Geometric, like joints.js's rope map
@@ -21,10 +22,6 @@ export function dragHold(stiffness) {
21
22
  return { stiffness: 0.001 * Math.pow(400, s), damping: 0.02 + 0.25 * s };
22
23
  }
23
24
 
24
- export function centerOf(layout) {
25
- return { x: layout.x + layout.width / 2, y: layout.y + layout.height / 2 };
26
- }
27
-
28
25
  export function length(v) {
29
26
  return Math.hypot(v.x, v.y);
30
27
  }
@@ -81,11 +78,10 @@ export function inActorWorldSpace(ctx, layout, draw) {
81
78
  const rot = layout?.rotation ?? 0;
82
79
  ctx.save();
83
80
  if (rot) {
84
- const cx = layout.x + layout.width / 2;
85
- const cy = layout.y + layout.height / 2;
86
- ctx.translate(cx, cy);
81
+ const center = layoutCenter(layout);
82
+ ctx.translate(center.x, center.y);
87
83
  ctx.rotate((-rot * Math.PI) / 180);
88
- ctx.translate(-cx, -cy);
84
+ ctx.translate(-center.x, -center.y);
89
85
  }
90
86
  draw(ctx);
91
87
  ctx.restore();
@@ -1,3 +1,6 @@
1
+ import Matter from 'matter-js';
2
+ import { getColliderShapes, pointsBounds } from '../collider';
3
+ import { layoutOriginX, layoutOriginY } from '../layout';
1
4
  import { isBehaviorEnabled } from '../scene';
2
5
  // Pure helpers bridging Cauldron actors (Layout + Collider + RigidBody
3
6
  // components) to matter-js bodies. No engine state lives here -- the
@@ -6,19 +9,19 @@ import { isBehaviorEnabled } from '../scene';
6
9
  // collider geometry, including sprite-fit `auto` mode).
7
10
  //
8
11
  // Coordinate systems:
9
- // - Cauldron Layout: top-left origin, +y down, `rotation` in degrees CW.
12
+ // - Cauldron Layout: `x`/`y` is the box point named by `originX`/`originY`
13
+ // (center when absent -- see DEFAULT_ORIGIN_* in engine/layout.js), +y down,
14
+ // `rotation` in degrees CW about the box CENTER.
10
15
  // - matter-js Body: centroid origin, +y down, `angle` in radians.
11
- // Rotation converts by DEG<->RAD; position via the body's cached center-offset
12
- // from Layout's top-left (see PhysicsSystem).
16
+ // Rotation converts by DEG<->RAD; position via the body's cached offset from
17
+ // Layout's `x`/`y` to the collider AABB center, which folds the origin in (see
18
+ // PhysicsSystem.addBody).
13
19
  //
14
20
  // matter-js unit notes (see Body defaults): `frictionAir` is linear damping,
15
21
  // `restitution` is bounciness, `friction` is contact friction. There is no
16
22
  // native per-body gravity multiplier and no kinematic body type -- both are
17
23
  // emulated here (applyWorldGravity, and kinematic == static-moved-from-Layout).
18
24
 
19
- import Matter from 'matter-js';
20
- import { getColliderShapes, pointsBounds } from '../collider';
21
-
22
25
  export const DEG_TO_RAD = Math.PI / 180;
23
26
  export const RAD_TO_DEG = 180 / Math.PI;
24
27
 
@@ -92,8 +95,10 @@ function shapeToPart(s) {
92
95
  // Structural signature: when this changes we rebuild the body (shape set / sizes
93
96
  // / type) rather than live-patching material props in place. Resolved sizes are
94
97
  // included, so resizing the Layout box (which rescales every fraction shape)
95
- // triggers a rebuild.
98
+ // triggers a rebuild -- and so is the Layout origin, which changes the body's
99
+ // cached offset from `layout.x/y` without changing any shape's size.
96
100
  export function bodySignature(actor) {
101
+ const layout = actor.components?.Layout;
97
102
  const shapes = getColliderShapes(actor) ?? [];
98
103
  const sig = shapes
99
104
  .map((s) =>
@@ -104,7 +109,7 @@ export function bodySignature(actor) {
104
109
  : `${s.type[0]}${(s.points ?? []).length}`
105
110
  )
106
111
  .join(',');
107
- return `${sig}|${rigidBodyType(actor)}`;
112
+ return `${sig}|${rigidBodyType(actor)}|${layoutOriginX(layout)},${layoutOriginY(layout)}`;
108
113
  }
109
114
 
110
115
  // Build a fresh matter body -- a single part, or a compound of all collider
@@ -2,6 +2,7 @@ import { resolveDeckFile } from 'castle-web-sdk';
2
2
  import { initialFiles, parseJsonFile } from './files';
3
3
  import { actorUsesBlueprint, getBlueprintTemplate, mergeComponents } from './blueprint';
4
4
  import { getColliderRect, intersects, spriteIsEmpty } from './collider';
5
+ import { layoutCenter, layoutRect } from './layout';
5
6
  import { systemInstallers } from './systemRegistry';
6
7
  import { deckFontFamily } from './fonts';
7
8
  import { wrapText } from './text';
@@ -215,6 +216,15 @@ export class SceneRuntime {
215
216
  return getColliderRect(actor, this.sprites);
216
217
  }
217
218
 
219
+ // The actor's Layout box in world units with `originX/originY` applied -- the
220
+ // rect it actually occupies. Deck code asks for this instead of doing
221
+ // `layout.x + width / 2` by hand, which is only right for a top-left origin
222
+ // (and deck behaviors can't import `engine/layout.js`).
223
+ layoutRect(actorOrId) {
224
+ const actor = typeof actorOrId === 'string' ? this.getActor(actorOrId) : actorOrId;
225
+ return layoutRect(getLayout(actor));
226
+ }
227
+
218
228
  overlaps(first, second) {
219
229
  const a = this.colliderRect(first);
220
230
  const b = this.colliderRect(second);
@@ -524,14 +534,9 @@ export class SceneRuntime {
524
534
  const actors = this.getActors().slice().reverse();
525
535
  const hits = [];
526
536
  for (const actor of actors) {
527
- const layout = getLayout(actor);
528
- if (!layout) continue;
529
- if (
530
- x >= layout.x &&
531
- x <= layout.x + layout.width &&
532
- y >= layout.y &&
533
- y <= layout.y + layout.height
534
- ) {
537
+ const box = layoutRect(getLayout(actor));
538
+ if (!box) continue;
539
+ if (x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height) {
535
540
  hits.push(actor);
536
541
  }
537
542
  }
@@ -545,13 +550,13 @@ export class SceneRuntime {
545
550
  const maxY = rect.y + rect.height;
546
551
  const ids = [];
547
552
  for (const actor of this.getActors()) {
548
- const layout = getLayout(actor);
549
- if (!layout) continue;
553
+ const box = layoutRect(getLayout(actor));
554
+ if (!box) continue;
550
555
  if (
551
- layout.x + layout.width >= minX &&
552
- layout.x <= maxX &&
553
- layout.y + layout.height >= minY &&
554
- layout.y <= maxY
556
+ box.x + box.width >= minX &&
557
+ box.x <= maxX &&
558
+ box.y + box.height >= minY &&
559
+ box.y <= maxY
555
560
  ) {
556
561
  ids.push(actor.id);
557
562
  }
@@ -711,9 +716,7 @@ function applyActorOrder(sceneData, ordered) {
711
716
  // Ignores Layout.rotation -- v1 selection bounds are axis-aligned (the canvas
712
717
  // `drawSelection` still draws the rotated outline for per-actor feedback).
713
718
  export function getLayoutRect(actor) {
714
- const layout = getLayout(actor);
715
- if (!layout) return null;
716
- return { x: layout.x, y: layout.y, width: layout.width, height: layout.height };
719
+ return layoutRect(getLayout(actor));
717
720
  }
718
721
 
719
722
  // Union axis-aligned bounding box of the given actors in world units, or null
@@ -852,9 +855,9 @@ function shouldDrawEditPlaceholder(actor, sprites) {
852
855
  // Wraps to two lines when the actor is too narrow for one -- a label that always
853
856
  // overflows its actor stops reading as belonging to it.
854
857
  function drawDisabledSpriteLabel(ctx, actor) {
855
- const layout = getLayout(actor);
856
- if (!layout) return;
857
- const fontSize = Math.max(8, Math.min(12, layout.width / 9));
858
+ const box = layoutRect(getLayout(actor));
859
+ if (!box) return;
860
+ const fontSize = Math.max(8, Math.min(12, box.width / 9));
858
861
  ctx.save();
859
862
  ctx.font = `600 ${fontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
860
863
  ctx.textAlign = 'center';
@@ -863,13 +866,13 @@ function drawDisabledSpriteLabel(ctx, actor) {
863
866
  const padY = fontSize * 0.4;
864
867
 
865
868
  const single = 'Sprite disabled';
866
- const lines = wrapText(ctx, single, Math.max(0, layout.width - padX * 2));
869
+ const lines = wrapText(ctx, single, Math.max(0, box.width - padX * 2));
867
870
  const lineHeight = fontSize * 1.15;
868
871
  const textWidth = Math.max(...lines.map((line) => ctx.measureText(line).width));
869
872
  const width = textWidth + padX * 2;
870
873
  const height = lineHeight * lines.length + padY * 2;
871
- const cx = layout.x + layout.width / 2;
872
- const cy = layout.y + layout.height / 2;
874
+ const cx = box.x + box.width / 2;
875
+ const cy = box.y + box.height / 2;
873
876
  const x = cx - width / 2;
874
877
  const y = cy - height / 2;
875
878
  const r = Math.min(4, height / 2);
@@ -888,14 +891,14 @@ function drawDisabledSpriteLabel(ctx, actor) {
888
891
  }
889
892
 
890
893
  function drawEditPlaceholder(ctx, actor) {
891
- const layout = getLayout(actor);
892
- if (!layout) return;
894
+ const box = layoutRect(getLayout(actor));
895
+ if (!box) return;
893
896
  ctx.save();
894
897
  ctx.fillStyle = 'rgba(255, 255, 255, 0.04)';
895
- ctx.fillRect(layout.x, layout.y, layout.width, layout.height);
898
+ ctx.fillRect(box.x, box.y, box.width, box.height);
896
899
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.25)';
897
900
  ctx.lineWidth = 1;
898
- ctx.strokeRect(layout.x + 0.5, layout.y + 0.5, layout.width - 1, layout.height - 1);
901
+ ctx.strokeRect(box.x + 0.5, box.y + 0.5, box.width - 1, box.height - 1);
899
902
  ctx.restore();
900
903
  }
901
904
 
@@ -942,24 +945,25 @@ function roundedRect(ctx, x, y, width, height, radius) {
942
945
 
943
946
  function drawSelection(ctx, actor) {
944
947
  const layout = getLayout(actor);
945
- if (!layout) return;
948
+ const box = layoutRect(layout);
949
+ if (!box) return;
946
950
  ctx.save();
947
951
  applyLayoutRotation(ctx, layout);
948
952
  ctx.strokeStyle = '#fff';
949
953
  ctx.lineWidth = 2;
950
954
  ctx.setLineDash([6, 4]);
951
- ctx.strokeRect(layout.x + 1, layout.y + 1, layout.width - 2, layout.height - 2);
955
+ ctx.strokeRect(box.x + 1, box.y + 1, box.width - 2, box.height - 2);
952
956
  ctx.restore();
953
957
  }
954
958
 
959
+ // Rotation pivots on the box CENTER whatever the origin is (see engine/layout.js).
955
960
  function applyLayoutRotation(ctx, layout) {
956
961
  const rotation = layout?.rotation ?? 0;
957
- if (!rotation || !layout) return;
958
- const cx = layout.x + layout.width / 2;
959
- const cy = layout.y + layout.height / 2;
960
- ctx.translate(cx, cy);
962
+ if (!rotation) return;
963
+ const center = layoutCenter(layout);
964
+ ctx.translate(center.x, center.y);
961
965
  ctx.rotate((rotation * Math.PI) / 180);
962
- ctx.translate(-cx, -cy);
966
+ ctx.translate(-center.x, -center.y);
963
967
  }
964
968
 
965
969
  function getLayout(actor) {
@@ -2,30 +2,38 @@
2
2
  // Sprite.jsx (rendering) and the Collider rect logic (engine/collider.js) can
3
3
  // use the same math without behaviors/ <-> engine/ import cycles.
4
4
 
5
- // Destination rect for a draw mode: the Layout box for `stretch`/`tile`, or an
5
+ // Destination rect for a draw mode, inside the content `box` (a real world-space
6
+ // rect -- `layoutRect` inset by Style.padding, see behaviors/Style.jsx, NOT the
7
+ // raw Layout component): the whole box for `stretch`/`tile`, or an
6
8
  // aspect-ratio-preserving centered rect for `fit` and `cover`:
7
9
  // - `fit` (CSS object-fit: contain): the largest rect with the art's aspect
8
10
  // ratio that fits INSIDE the box -- letterboxed sides just aren't drawn.
9
11
  // - `cover` (CSS object-fit: cover): the smallest rect with the art's aspect
10
12
  // ratio that fully COVERS the box -- the overflow is cropped by the caller
11
- // clipping to the Layout box (see Sprite.draw).
13
+ // clipping to the content box (see Sprite.draw).
12
14
  // `artSize` only needs `.width`/`.height` -- a rendered canvas or a sprite's
13
15
  // `.resolution` both work.
14
- export function spriteDestRect(mode, layout, artSize) {
15
- if (mode !== 'fit' && mode !== 'cover') return layout;
16
+ //
17
+ // Always a FRESH rect, never the `box` argument itself: callers treat the result
18
+ // as their own to read past the box's lifetime, and handing back the input made
19
+ // `dest === box` for two of the four modes -- true only by accident.
20
+ export function spriteDestRect(mode, box, artSize) {
21
+ if (mode !== 'fit' && mode !== 'cover') {
22
+ return { x: box.x, y: box.y, width: box.width, height: box.height };
23
+ }
16
24
  const aspect = artSize.width / artSize.height;
17
- let width = layout.width;
25
+ let width = box.width;
18
26
  let height = width / aspect;
19
27
  // `fit` shrinks until the art fits inside the box; `cover` grows until it
20
28
  // fills the box. The comparison flips between the two.
21
- const overflows = mode === 'fit' ? height > layout.height : height < layout.height;
29
+ const overflows = mode === 'fit' ? height > box.height : height < box.height;
22
30
  if (overflows) {
23
- height = layout.height;
31
+ height = box.height;
24
32
  width = height * aspect;
25
33
  }
26
34
  return {
27
- x: layout.x + (layout.width - width) / 2,
28
- y: layout.y + (layout.height - height) / 2,
35
+ x: box.x + (box.width - width) / 2,
36
+ y: box.y + (box.height - height) / 2,
29
37
  width,
30
38
  height,
31
39
  };
@@ -1,3 +1,4 @@
1
+ import { layoutRect } from './layout';
1
2
  import { TAP_CLAIM } from './physics/controls';
2
3
 
3
4
  // Built-in tap. Any enabled behavior may implement `onTap(actor, scene)`; the
@@ -84,7 +85,7 @@ function hits(actor, scene, pointer) {
84
85
  if (actor.components?.Collider && scene.physics?.containsPoint) {
85
86
  return scene.physics.containsPoint(actor, x, y);
86
87
  }
87
- const layout = actor.components?.Layout;
88
- if (!layout) return false;
89
- return x >= layout.x && x <= layout.x + layout.width && y >= layout.y && y <= layout.y + layout.height;
88
+ const box = layoutRect(actor.components?.Layout);
89
+ if (!box) return false;
90
+ return x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height;
90
91
  }
@@ -1,12 +1,65 @@
1
1
  {
2
2
  "name": "Main",
3
3
  "background": "#1a1932",
4
- "physics": { "gravity": 1 },
4
+ "physics": {
5
+ "gravity": 1
6
+ },
5
7
  "actors": [
6
- { "id": "ball", "blueprint": "blueprints/ball.scene", "components": { "Layout": { "x": 70, "y": 560 } } },
7
- { "id": "floor", "blueprint": "blueprints/block.scene", "components": { "Layout": { "x": 0, "y": 640, "width": 500, "height": 60 } } },
8
- { "id": "leftWall", "blueprint": "blueprints/block.scene", "components": { "Layout": { "x": 0, "y": 0, "width": 50, "height": 700 } } },
9
- { "id": "rightWall", "blueprint": "blueprints/block.scene", "components": { "Layout": { "x": 450, "y": 0, "width": 50, "height": 700 } } },
10
- { "id": "goal", "blueprint": "blueprints/goal.scene", "components": { "Layout": { "x": 300, "y": 420 } } }
8
+ {
9
+ "id": "ball",
10
+ "blueprint": "blueprints/ball.scene",
11
+ "components": {
12
+ "Layout": {
13
+ "x": 92,
14
+ "y": 582
15
+ }
16
+ }
17
+ },
18
+ {
19
+ "id": "floor",
20
+ "blueprint": "blueprints/block.scene",
21
+ "components": {
22
+ "Layout": {
23
+ "x": 250,
24
+ "y": 670,
25
+ "width": 500,
26
+ "height": 60
27
+ }
28
+ }
29
+ },
30
+ {
31
+ "id": "leftWall",
32
+ "blueprint": "blueprints/block.scene",
33
+ "components": {
34
+ "Layout": {
35
+ "x": 25,
36
+ "y": 350,
37
+ "width": 50,
38
+ "height": 700
39
+ }
40
+ }
41
+ },
42
+ {
43
+ "id": "rightWall",
44
+ "blueprint": "blueprints/block.scene",
45
+ "components": {
46
+ "Layout": {
47
+ "x": 475,
48
+ "y": 350,
49
+ "width": 50,
50
+ "height": 700
51
+ }
52
+ }
53
+ },
54
+ {
55
+ "id": "goal",
56
+ "blueprint": "blueprints/goal.scene",
57
+ "components": {
58
+ "Layout": {
59
+ "x": 355,
60
+ "y": 437
61
+ }
62
+ }
63
+ }
11
64
  ]
12
65
  }