@ignifx/2d 0.0.0 → 0.2.0

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Component, DEG_TO_RAD, IgnifxError, Phase, RAD_TO_DEG, Script, Signal, Vec2, array, assertNever, asset, bool, color, createDefaults, decodeProps, defineExtension, defineSchema, describeSchema, entityRef, enumOf, f32, i32, map, optional, record, str, toJsonSchema, u32, vec2, vec4 } from "@ignifx/core";
2
- import { addSprite2D, addSpriteRendererLayer, clearSprite2DLayer, createSprite2DLayer, createSpriteRenderer, disableSprite2DYSort, disposeSpriteRenderer, enableDeviceLostSpriteRecovery, enableSprite2DYSort, getSprite2DHandleIndex, getSprite2DVisibleBoundsToRef, isSprite2DHandleAlive, loadTexture2D, pickSprite2D, registerSpriteRenderer, releaseTexture, removeSprite2D, removeSpriteRendererLayer, setSprite2DYSortHandleBias, spriteBlendAdditive, spriteBlendAlpha, spriteBlendMultiply, spriteBlendOpaque, spriteBlendPremultiplied, unregisterSpriteRenderer, updateSprite2D } from "@babylonjs/lite";
1
+ import { Color, Component, DEG_TO_RAD, IgnifxError, Phase, RAD_TO_DEG, RENDERING_SETTINGS_SECTION, Script, Signal, Vec2, array, assertNever, asset, bool, color, createDefaults, decodeProps, defineExtension, defineSchema, describeSchema, entityRef, enumOf, f32, i32, map, optional, record, str, toJsonSchema, u32, vec2, vec4 } from "@ignifx/core";
2
+ import { addSprite2D, addSpriteRendererLayer, clearSprite2DLayer, createSprite2DCustomShader, createSprite2DLayer, createSpriteRenderer, disableSprite2DYSort, disposeSpriteRenderer, enableDeviceLostSpriteRecovery, enableSprite2DYSort, getSprite2DHandleIndex, getSprite2DVisibleBoundsToRef, isSprite2DHandleAlive, loadTexture2D, pickSprite2D, registerSpriteRenderer, releaseTexture, removeSprite2D, removeSpriteRendererLayer, setSprite2DShaderParams, setSprite2DYSortHandleBias, sprite2DScreenToWorldToRef, spriteBlendAdditive, spriteBlendAlpha, spriteBlendMultiply, spriteBlendOpaque, spriteBlendPremultiplied, unregisterSpriteRenderer, updateSprite2D } from "@babylonjs/lite";
3
3
  //#region src/augmentation.ts
4
4
  /**
5
5
  * Defines `app.twoD`, pairing with the augmentation above.
@@ -120,17 +120,66 @@ function twoDError(code, message, options) {
120
120
  * Frames are in **image pixels with a top-left origin**, which is what every atlas packer emits.
121
121
  * The conversion into Lite's normalised UVs happens in the loader, once.
122
122
  */
123
- /** The `format` discriminator every `.atlas.json` document carries. @public */
123
+ /**
124
+ * The `format` discriminator every `.atlas.json` document carries.
125
+ *
126
+ * @public
127
+ */
124
128
  const SPRITE_ATLAS_FORMAT = "ignifx.spriteatlas";
125
- /** The document version this build reads and writes. @public */
129
+ /**
130
+ * The document version this build reads and writes.
131
+ *
132
+ * @public
133
+ */
126
134
  const SPRITE_ATLAS_FORMAT_VERSION = 1;
127
- /** The asset type name the loader registers. @public */
135
+ /**
136
+ * The asset type name the loader registers.
137
+ *
138
+ * @public
139
+ */
128
140
  const SPRITE_ATLAS_ASSET_TYPE = "spriteatlas";
129
- /** The address suffixes that select the sprite-atlas loader. @public */
141
+ /**
142
+ * The address suffixes that select the sprite-atlas loader.
143
+ *
144
+ * @public
145
+ */
130
146
  const SPRITE_ATLAS_FILE_EXTENSIONS = Object.freeze([".atlas.json"]);
131
- /** The fragment prefix that addresses one frame: `"sprites/hero.atlas.json#frame:idle_0"`. @public */
147
+ /**
148
+ * The fragment prefix that addresses one frame: `"sprites/hero.atlas.json#frame:idle_0"`.
149
+ *
150
+ * @public
151
+ */
132
152
  const SPRITE_FRAME_FRAGMENT_PREFIX = "frame:";
133
153
  /**
154
+ * Normalises either written form of a 2D value.
155
+ *
156
+ * @param value - What the document wrote, or `undefined`.
157
+ * @param fallback - What to use when the document wrote nothing.
158
+ * @returns The normalised vector.
159
+ *
160
+ * @public
161
+ */
162
+ function readVec2(value, fallback) {
163
+ if (value === void 0) return fallback;
164
+ if (isPair(value)) return {
165
+ x: value[0],
166
+ y: value[1]
167
+ };
168
+ return typeof value.x === "number" && typeof value.y === "number" ? {
169
+ x: value.x,
170
+ y: value.y
171
+ } : fallback;
172
+ }
173
+ /**
174
+ * Whether a written 2D value is the `[x, y]` array form.
175
+ *
176
+ * @param value - The value the document carried.
177
+ * @returns `true` when it is a two-number array.
178
+ */
179
+ function isPair(value) {
180
+ return Array.isArray(value) && typeof value[0] === "number" && typeof value[1] === "number";
181
+ }
182
+ /**
134
183
  * Fills in the defaults of an atlas document and checks the invariants a loader relies on.
135
184
  *
136
185
  * @param input - The document, as authored or as an importer emitted it.
@@ -149,7 +198,7 @@ function defineSpriteAtlas(input, address = "<inline>") {
149
198
  });
150
199
  };
151
200
  if (input.format !== void 0 && input.format !== "ignifx.spriteatlas") fail(`its format is ${input.format}, not ${SPRITE_ATLAS_FORMAT}`);
152
- if (input.version !== void 0 && input.version !== 1) fail(`its version is ${String(input.version)}, and this build reads ${String(1)}`);
201
+ if (input.formatVersion !== void 0 && input.formatVersion !== 1) fail(`its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(1)}`);
153
202
  if (typeof input.image !== "string" || input.image === "") fail("it names no image");
154
203
  if (!Array.isArray(input.frames) || input.frames.length === 0) fail("it declares no frames");
155
204
  const seen = /* @__PURE__ */ new Set();
@@ -164,16 +213,36 @@ function defineSpriteAtlas(input, address = "<inline>") {
164
213
  if (!(frame.w > 0) || !(frame.h > 0)) fail(`frame ${frame.name} has a non-positive size`);
165
214
  if (!(frame.x >= 0) || !(frame.y >= 0)) fail(`frame ${frame.name} starts outside the image`);
166
215
  }
216
+ const frames = [];
217
+ for (let index = 0; index < input.frames.length; index += 1) {
218
+ const frame = input.frames[index];
219
+ if (frame === void 0) continue;
220
+ frames.push({
221
+ ...frame,
222
+ pivot: readVec2(frame.pivot, CENTRE_PIVOT$3),
223
+ ...frame.sourceSize === void 0 ? {} : { sourceSize: readVec2(frame.sourceSize, {
224
+ x: frame.w,
225
+ y: frame.h
226
+ }) }
227
+ });
228
+ }
167
229
  return {
168
230
  format: SPRITE_ATLAS_FORMAT,
169
- version: 1,
231
+ formatVersion: 1,
170
232
  image: input.image,
171
233
  sampling: input.sampling ?? "linear",
172
234
  premultipliedAlpha: input.premultipliedAlpha ?? false,
173
- frames: input.frames
235
+ frames
174
236
  };
175
237
  }
176
238
  /**
239
+ * The pivot a frame that declares none uses.
240
+ */
241
+ const CENTRE_PIVOT$3 = Object.freeze({
242
+ x: .5,
243
+ y: .5
244
+ });
245
+ /**
177
246
  * Splits a sprite address into its atlas address and its frame name.
178
247
  *
179
248
  * @param fragment - The part after `#`, or `null` for a bare atlas address.
@@ -308,13 +377,16 @@ var SpriteAtlasAsset = class {
308
377
  frame(index) {
309
378
  const declared = this.definition.frames[index];
310
379
  if (declared === void 0) return null;
311
- const pivot = declared.pivot ?? DEFAULT_PIVOT;
312
- const source = declared.sourceSize;
380
+ const pivot = readVec2(declared.pivot, DEFAULT_PIVOT);
381
+ const source = readVec2(declared.sourceSize, {
382
+ x: declared.w,
383
+ y: declared.h
384
+ });
313
385
  return {
314
386
  name: declared.name,
315
387
  index,
316
- widthPx: source?.x ?? declared.w,
317
- heightPx: source?.y ?? declared.h,
388
+ widthPx: source.x,
389
+ heightPx: source.y,
318
390
  pivot
319
391
  };
320
392
  }
@@ -369,7 +441,11 @@ const DEFAULT_PIVOT = Object.freeze({
369
441
  *
370
442
  * Everything except the blend-mode table is `@internal`.
371
443
  */
372
- /** The blend modes `SpriteRenderer.blend` accepts, in the order an inspector should list them. @public */
444
+ /**
445
+ * The blend modes `SpriteRenderer.blend` accepts, in the order an inspector should list them.
446
+ *
447
+ * @public
448
+ */
373
449
  const SPRITE_BLEND_MODES = [
374
450
  "alpha",
375
451
  "premultiplied",
@@ -670,11 +746,32 @@ function visibleBounds(view, widthPx, heightPx, out) {
670
746
  return getSprite2DVisibleBoundsToRef(view, widthPx, heightPx, out);
671
747
  }
672
748
  /**
673
- * Picks the topmost sprite under a viewport pixel.
749
+ * Unprojects a viewport pixel into the layer-pixel space a layer's sprites live in.
750
+ *
751
+ * @param view - The layer's view.
752
+ * @param screenXPx - The viewport x, from the left edge.
753
+ * @param screenYPx - The viewport y, from the top edge.
754
+ * @param out - The point to write: its `x` and `y` take the layer-space coordinates.
755
+ * @returns `out`.
756
+ *
757
+ * @internal
758
+ */
759
+ function screenToLayer(view, screenXPx, screenYPx, out) {
760
+ return sprite2DScreenToWorldToRef(view, screenXPx, screenYPx, out);
761
+ }
762
+ /**
763
+ * Picks the topmost sprite under a **layer-pixel** point.
764
+ *
765
+ * @remarks
766
+ * This is the trap in Lite's picking API, and it is not in the declaration: despite the parameter
767
+ * names, `pickSprite2D` compares `xPx`/`yPx` directly against each sprite's stored `positionPx` and
768
+ * **never applies the layer's view** (`lib/sprite/picking/pick-sprite-2d.js` lines 26-27). A
769
+ * viewport pixel therefore has to be unprojected with {@link screenToLayer} first, per layer,
770
+ * because a world layer and a screen-space layer carry different views.
674
771
  *
675
772
  * @param layers - The layers to test, in draw order.
676
- * @param xPx - The viewport x.
677
- * @param yPx - The viewport y.
773
+ * @param xPx - The layer-space x.
774
+ * @param yPx - The layer-space y.
678
775
  * @returns The hit, or `null`.
679
776
  *
680
777
  * @internal
@@ -682,6 +779,41 @@ function visibleBounds(view, widthPx, heightPx, out) {
682
779
  function pickSprite(layers, xPx, yPx) {
683
780
  return pickSprite2D(layers, xPx, yPx);
684
781
  }
782
+ /**
783
+ * Compiles a WGSL fragment body into a layer shader (`index.d.ts` 3160).
784
+ *
785
+ * @remarks
786
+ * The body is compiled on demand and the result is pure data, so one compiled shader can back many
787
+ * layers. `Sprite2DLayerOptions.customShader` is only read at creation and
788
+ * `Sprite2DLayer.customShader` is `readonly` — a layer's shader cannot be swapped later.
789
+ *
790
+ * @param fragment - The WGSL fragment body.
791
+ * @returns The compiled shader.
792
+ *
793
+ * @internal
794
+ */
795
+ function compileLayerShader(fragment) {
796
+ return createSprite2DCustomShader({ fragment });
797
+ }
798
+ /**
799
+ * Writes a custom shader's `fx.params` vec4 for one layer.
800
+ *
801
+ * @param layer - The layer.
802
+ * @param x - The first component.
803
+ * @param y - The second component.
804
+ * @param z - The third component.
805
+ * @param w - The fourth component.
806
+ *
807
+ * @internal
808
+ */
809
+ function setShaderParams(layer, x, y, z, w) {
810
+ setSprite2DShaderParams(layer, [
811
+ x,
812
+ y,
813
+ z,
814
+ w
815
+ ]);
816
+ }
685
817
  //#endregion
686
818
  //#region src/service/sorting-layers.ts
687
819
  /**
@@ -693,7 +825,11 @@ function pickSprite(layers, xPx, yPx) {
693
825
  * derived from, and it refuses a name the project never declared instead of silently drawing on
694
826
  * the wrong layer.
695
827
  */
696
- /** The sorting layer a component that names none draws on. @public */
828
+ /**
829
+ * The sorting layer a component that names none draws on.
830
+ *
831
+ * @public
832
+ */
697
833
  const DEFAULT_SORTING_LAYER = "Default";
698
834
  /**
699
835
  * How far apart two sorting layers' Lite `order` values sit.
@@ -819,6 +955,8 @@ var SpriteRenderer = class SpriteRenderer extends Component {
819
955
  #isDirty = true;
820
956
  /** Whether a static entity has been synced at least once. */
821
957
  #hasSyncedStatic = false;
958
+ /** The visibility the last sync wrote, so toggling `enabled` reaches Lite. */
959
+ #appliedVisible = false;
822
960
  /** The world AABB the last sync computed, as `minX, minY, maxX, maxY` in metres. */
823
961
  #bounds = /* @__PURE__ */ new Float64Array(4);
824
962
  /**
@@ -834,6 +972,7 @@ var SpriteRenderer = class SpriteRenderer extends Component {
834
972
  onAttach() {
835
973
  this.#syncedMatrixVersion = -1;
836
974
  this.#hasSyncedStatic = false;
975
+ this.#appliedVisible = false;
837
976
  this.#isDirty = true;
838
977
  }
839
978
  /**
@@ -851,6 +990,11 @@ var SpriteRenderer = class SpriteRenderer extends Component {
851
990
  get frame() {
852
991
  return this.#frame;
853
992
  }
993
+ /**
994
+ * Sets the atlas frame drawn, marking the sprite for the next sync when it changes.
995
+ *
996
+ * @param value - The frame index.
997
+ */
854
998
  set frame(value) {
855
999
  if (value !== this.#frame) {
856
1000
  this.#frame = value;
@@ -910,6 +1054,7 @@ var SpriteRenderer = class SpriteRenderer extends Component {
910
1054
  */
911
1055
  needsSync(isStatic, matrixVersion) {
912
1056
  if (this.#isDirty) return true;
1057
+ if (this.isEnabledInHierarchy !== this.#appliedVisible) return true;
913
1058
  if (isStatic) return !this.#hasSyncedStatic;
914
1059
  return matrixVersion !== this.#syncedMatrixVersion;
915
1060
  }
@@ -927,6 +1072,7 @@ var SpriteRenderer = class SpriteRenderer extends Component {
927
1072
  */
928
1073
  markSynced(isStatic, matrixVersion, minX, minY, maxX, maxY) {
929
1074
  this.#isDirty = false;
1075
+ this.#appliedVisible = this.isEnabledInHierarchy;
930
1076
  this.#hasSyncedStatic = isStatic;
931
1077
  this.#syncedMatrixVersion = matrixVersion;
932
1078
  this.#bounds[0] = minX;
@@ -1002,15 +1148,35 @@ function spriteRendererSchema() {
1002
1148
  * `SpriteAnimationManager`, so `timeScale`, pause, and frame events behave exactly as they do for
1003
1149
  * 3D animation (ADR-0003).
1004
1150
  */
1005
- /** The `format` discriminator every `.spriteanim.json` document carries. @public */
1151
+ /**
1152
+ * The `format` discriminator every `.spriteanim.json` document carries.
1153
+ *
1154
+ * @public
1155
+ */
1006
1156
  const SPRITE_ANIMATION_FORMAT = "ignifx.spriteanimation";
1007
- /** The document version this build reads and writes. @public */
1157
+ /**
1158
+ * The document version this build reads and writes.
1159
+ *
1160
+ * @public
1161
+ */
1008
1162
  const SPRITE_ANIMATION_FORMAT_VERSION = 1;
1009
- /** The asset type name the loader registers. @public */
1163
+ /**
1164
+ * The asset type name the loader registers.
1165
+ *
1166
+ * @public
1167
+ */
1010
1168
  const SPRITE_ANIMATION_ASSET_TYPE = "spriteanimation";
1011
- /** The address suffixes that select the sprite-animation loader. @public */
1169
+ /**
1170
+ * The address suffixes that select the sprite-animation loader.
1171
+ *
1172
+ * @public
1173
+ */
1012
1174
  const SPRITE_ANIMATION_FILE_EXTENSIONS = Object.freeze([".spriteanim.json"]);
1013
- /** The frames-per-second a clip that declares none plays at. @public */
1175
+ /**
1176
+ * The frames-per-second a clip that declares none plays at.
1177
+ *
1178
+ * @public
1179
+ */
1014
1180
  const DEFAULT_CLIP_FPS = 12;
1015
1181
  /**
1016
1182
  * Fills in the defaults of an animation document and checks the invariants the animator relies on.
@@ -1030,7 +1196,7 @@ function defineSpriteAnimation(input, address = "<inline>") {
1030
1196
  });
1031
1197
  };
1032
1198
  if (input.format !== void 0 && input.format !== "ignifx.spriteanimation") fail(`its format is ${input.format}, not ${SPRITE_ANIMATION_FORMAT}`);
1033
- if (input.version !== void 0 && input.version !== 1) fail(`its version is ${String(input.version)}, and this build reads ${String(1)}`);
1199
+ if (input.formatVersion !== void 0 && input.formatVersion !== 1) fail(`its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(1)}`);
1034
1200
  if (!Array.isArray(input.clips) || input.clips.length === 0) fail("it declares no clips");
1035
1201
  const seen = /* @__PURE__ */ new Set();
1036
1202
  for (let index = 0; index < input.clips.length; index += 1) {
@@ -1048,7 +1214,7 @@ function defineSpriteAnimation(input, address = "<inline>") {
1048
1214
  }
1049
1215
  return {
1050
1216
  format: SPRITE_ANIMATION_FORMAT,
1051
- version: 1,
1217
+ formatVersion: 1,
1052
1218
  atlas: input.atlas ?? "",
1053
1219
  clips: input.clips
1054
1220
  };
@@ -1056,6 +1222,12 @@ function defineSpriteAnimation(input, address = "<inline>") {
1056
1222
  /**
1057
1223
  * Resolves a clip's frame names into atlas frame indices.
1058
1224
  *
1225
+ * @remarks
1226
+ * `frames` resolves name by name and skips what the atlas does not carry. `from`/`to` resolves both
1227
+ * endpoints to atlas **indices** and walks every index between them — ascending or descending — so
1228
+ * a range over non-adjacent frames plays everything the packer put in between
1229
+ * ({@link SpriteClipDefinition}).
1230
+ *
1059
1231
  * @param clip - The clip to resolve.
1060
1232
  * @param indexOf - Maps an atlas frame name to its index, or `-1` when the atlas has no such frame.
1061
1233
  * @returns The indices in play order; empty when the clip names nothing the atlas has.
@@ -1345,15 +1517,15 @@ var SpriteAnimator = class SpriteAnimator extends Component {
1345
1517
  * ```
1346
1518
  */
1347
1519
  play(name, options) {
1348
- const asset = this.asset;
1520
+ const clips = this.asset;
1349
1521
  const atlas = this.#atlas();
1350
- if (asset === null || atlas === null) {
1522
+ if (clips === null || atlas === null) {
1351
1523
  this.defaultClip = name;
1352
1524
  this.playOnAwake = true;
1353
1525
  this.#hasAutoPlayed = false;
1354
1526
  return;
1355
1527
  }
1356
- const clip = asset.requireClip(name, atlas);
1528
+ const clip = clips.requireClip(name, atlas);
1357
1529
  if (this.#clip === clip && this.#isPlaying && options?.restart !== true) return;
1358
1530
  this.#clip = clip;
1359
1531
  this.#elapsed = 0;
@@ -1388,7 +1560,7 @@ var SpriteAnimator = class SpriteAnimator extends Component {
1388
1560
  *
1389
1561
  * @remarks
1390
1562
  * `deltaSeconds` is `ctx.dt` in the `PostUpdate` phase, which is `time.deltaTime` — already
1391
- * multiplied by `time.timeScale` and already zero while the app is paused
1563
+ * multiplied by `time.timeScale`; the 2D animation system skips the call while the app is paused
1392
1564
  * (`docs/architecture/01-lifecycle-and-time.md` §2). The animator does not consult the clock
1393
1565
  * itself, which is what makes it deterministic under `app.step`.
1394
1566
  *
@@ -1430,23 +1602,23 @@ var SpriteAnimator = class SpriteAnimator extends Component {
1430
1602
  */
1431
1603
  #autoPlay() {
1432
1604
  if (this.#hasAutoPlayed || !this.playOnAwake) return;
1433
- const asset = this.asset;
1605
+ const clips = this.asset;
1434
1606
  const atlas = this.#atlas();
1435
- if (asset === null || atlas === null) return;
1436
- const name = this.defaultClip === "" ? asset.defaultClipName : this.defaultClip;
1607
+ if (clips === null || atlas === null) return;
1608
+ const name = this.defaultClip === "" ? clips.defaultClipName : this.defaultClip;
1437
1609
  if (name === "") {
1438
1610
  this.#hasAutoPlayed = true;
1439
1611
  return;
1440
1612
  }
1441
- const clip = asset.resolve(atlas).get(name);
1613
+ const clip = clips.resolve(atlas).get(name);
1442
1614
  if (clip === void 0) {
1443
1615
  this.#hasAutoPlayed = true;
1444
- throw twoDError(TwoDErrorCode.unknownClip, `${asset.address} declares no clip named ${name}.`, {
1616
+ throw twoDError(TwoDErrorCode.unknownClip, `${clips.address} declares no clip named ${name}.`, {
1445
1617
  context: {
1446
- asset: asset.address,
1618
+ asset: clips.address,
1447
1619
  clip: name
1448
1620
  },
1449
- hint: `Known clips: ${asset.clipNames().join(", ")}.`
1621
+ hint: `Known clips: ${clips.clipNames().join(", ")}.`
1450
1622
  });
1451
1623
  }
1452
1624
  this.#hasAutoPlayed = true;
@@ -1466,9 +1638,10 @@ var SpriteAnimator = class SpriteAnimator extends Component {
1466
1638
  */
1467
1639
  #emitEventsBetween(clip, from, toRaw, count) {
1468
1640
  if (clip.events.length === 0) return;
1469
- const steps = Math.min(toRaw - from, count);
1641
+ const reach = clip.loop ? count : count - 1 - from;
1642
+ const steps = Math.min(toRaw - from, reach);
1470
1643
  for (let step = 1; step <= steps; step += 1) {
1471
- const frame = clip.loop ? (from + step) % count : Math.min(from + step, count - 1);
1644
+ const frame = clip.loop ? (from + step) % count : from + step;
1472
1645
  for (let index = 0; index < clip.events.length; index += 1) {
1473
1646
  const event = clip.events[index];
1474
1647
  if (event !== void 0 && event.frame === frame) this.#onEvent.emit(event.name);
@@ -1528,8 +1701,11 @@ function spriteAnimatorSchema() {
1528
1701
  * It runs in `PostUpdate` — after `update`, before `PreRender` — which is where every animation in
1529
1702
  * ignifx advances, so a `lateUpdate` sees the posed frame and the render sync writes it in the same
1530
1703
  * frame it was computed. It advances every `SpriteAnimator` and every animated tile on the same
1531
- * `ctx.dt`, which is `time.deltaTime`: already scaled by `time.timeScale` and already zero while
1532
- * the app is paused.
1704
+ * `ctx.dt`, which is `time.deltaTime`, already scaled by `time.timeScale`. Systems keep running
1705
+ * while the app is paused and `dt` is **not** zeroed then (only scripts are filtered by
1706
+ * `updateWhenPaused`), so the system checks `time.paused` itself: sprite animation does not advance
1707
+ * while paused (`01-lifecycle-and-time.md` §7). Phase 6 shipped without this check and the sprites
1708
+ * kept animating under a pause menu.
1533
1709
  */
1534
1710
  /**
1535
1711
  * The `PostUpdate` order the 2D animation system runs at.
@@ -1564,6 +1740,7 @@ var TwoDAnimationSystem = class {
1564
1740
  * @param ctx - The world, clock, phase, and delta.
1565
1741
  */
1566
1742
  update(ctx) {
1743
+ if (ctx.time.paused) return;
1567
1744
  const animators = ctx.world.components(SpriteAnimator);
1568
1745
  for (let index = 0; index < animators.length; index += 1) {
1569
1746
  const animator = animators[index];
@@ -1589,7 +1766,7 @@ var TwoDAnimationSystem = class {
1589
1766
  * atlas that only breaks later, at load.
1590
1767
  */
1591
1768
  /** The pivot a frame gets when neither the packer nor the caller names one. */
1592
- const CENTRE_PIVOT$1 = Object.freeze({
1769
+ const CENTRE_PIVOT$2 = Object.freeze({
1593
1770
  x: .5,
1594
1771
  y: .5
1595
1772
  });
@@ -1685,7 +1862,7 @@ function readSize(entry, key) {
1685
1862
  * @param key - The field holding the vector.
1686
1863
  * @returns The vector, or `null` when the field is absent or incomplete.
1687
1864
  */
1688
- function readVec2(entry, key) {
1865
+ function readVec2$1(entry, key) {
1689
1866
  const raw = entry[key];
1690
1867
  if (!isObject$1(raw)) return null;
1691
1868
  const x = raw["x"];
@@ -1777,7 +1954,7 @@ function collectSlicePivots(meta) {
1777
1954
  for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {
1778
1955
  const key = keys[keyIndex];
1779
1956
  if (!isObject$1(key)) continue;
1780
- const pivot = readVec2(key, "pivot");
1957
+ const pivot = readVec2$1(key, "pivot");
1781
1958
  const bounds = readRect(key, "bounds");
1782
1959
  if (pivot === null || bounds === null) continue;
1783
1960
  const frame = key["frame"];
@@ -1848,7 +2025,7 @@ function asepriteFrameName(raw) {
1848
2025
  * Cuts an evenly spaced sprite sheet into an `ignifx.spriteatlas` document.
1849
2026
  *
1850
2027
  * Frames come out in reading order — left to right, then top to bottom — named
1851
- * `` `${namePrefix}_${index}` `` with `index` counting from `0` across the whole sheet, so a 4×2
2028
+ * `<namePrefix>_<index>` with `index` counting from `0` across the whole sheet, so a 4×2
1852
2029
  * grid ends at `tile_7`. `columns` and `rows` default to as many whole cells as the image holds
1853
2030
  * (`floor((imageWidth - 2·margin + spacing) / (cellWidth + spacing))`, and likewise for rows) and
1854
2031
  * are clamped to that capacity when given, so an over-large explicit count never produces a frame
@@ -1856,7 +2033,7 @@ function asepriteFrameName(raw) {
1856
2033
  *
1857
2034
  * @remarks
1858
2035
  * `namePrefix` is how a grid atlas lines up with the rest of the toolkit: `@ignifx/2d`'s Tiled
1859
- * importer names a tileset's frames `` `${tilesetName}_${index}` ``, so passing the tileset's name
2036
+ * importer names a tileset's frames `<tilesetName>_<index>`, so passing the tileset's name
1860
2037
  * as `namePrefix` makes a hand-cut grid atlas addressable by exactly the names a tilemap emits.
1861
2038
  *
1862
2039
  * @param options - The sheet's geometry and the frame naming.
@@ -1892,7 +2069,7 @@ function gridAtlas(options) {
1892
2069
  const rows = options.rows === void 0 ? capacityRows : Math.min(clampCount(options.rows), capacityRows);
1893
2070
  if (columns === 0 || rows === 0) failImport$1(importer, `a ${String(imageWidth)}x${String(imageHeight)} image with ${String(cellWidth)}x${String(cellHeight)} cells, margin ${String(margin)} and spacing ${String(spacing)} holds no whole cells`, "Check the image size, the cell size, the margin, and the spacing against the sheet.");
1894
2071
  const prefix = options.namePrefix ?? DEFAULT_GRID_NAME_PREFIX;
1895
- const pivot = options.pivot ?? CENTRE_PIVOT$1;
2072
+ const pivot = options.pivot ?? CENTRE_PIVOT$2;
1896
2073
  const frames = [];
1897
2074
  for (let row = 0; row < rows; row += 1) for (let column = 0; column < columns; column += 1) frames.push({
1898
2075
  name: `${prefix}_${String(row * columns + column)}`,
@@ -1986,7 +2163,7 @@ function importTexturePackerAtlas(json, options) {
1986
2163
  if (item.entry["rotated"] === true) failImport$1(importer, `frame ${item.key} is rotated`, "TexturePacker rotated frames are not supported; disable rotation when packing.");
1987
2164
  const rect = readRect(item.entry, "frame");
1988
2165
  if (rect === null) failImport$1(importer, `frame ${item.key} has no {x, y, w, h} frame rectangle`);
1989
- const pivot = readVec2(item.entry, "pivot") ?? CENTRE_PIVOT$1;
2166
+ const pivot = readVec2$1(item.entry, "pivot") ?? CENTRE_PIVOT$2;
1990
2167
  const sourceSize = item.entry["trimmed"] === true ? readSize(item.entry, "sourceSize") : null;
1991
2168
  frames.push({
1992
2169
  name: keepExtensions ? item.key : stripFileExtension(item.key),
@@ -2077,7 +2254,7 @@ function importAsepriteAtlas(json, options) {
2077
2254
  const trimmed = item.entry["trimmed"] === true;
2078
2255
  const sourceWidth = declaredSource === null ? rect.w : declaredSource.x;
2079
2256
  const sourceHeight = declaredSource === null ? rect.h : declaredSource.y;
2080
- const pivot = slicePivotFor(slicePivots, index, sourceWidth, sourceHeight) ?? CENTRE_PIVOT$1;
2257
+ const pivot = slicePivotFor(slicePivots, index, sourceWidth, sourceHeight) ?? CENTRE_PIVOT$2;
2081
2258
  frames.push({
2082
2259
  name: asepriteFrameName(item.key),
2083
2260
  x: rect.x,
@@ -2416,6 +2593,21 @@ function normalisePath(path) {
2416
2593
  }
2417
2594
  return out.join("/");
2418
2595
  }
2596
+ /**
2597
+ * Whether a reference is a URL in its own right rather than an address: root-relative (`/…`),
2598
+ * protocol-relative (`//…`), or carrying a scheme (`http(s)://`, `blob:`, `data:`).
2599
+ *
2600
+ * @param reference - The reference as written in a document.
2601
+ * @returns `true` when the reference must be fetched verbatim rather than resolved through the manifest.
2602
+ */
2603
+ function isAbsoluteReference(reference) {
2604
+ if (reference.startsWith("/")) return true;
2605
+ for (let index = 0; index < ABSOLUTE_PREFIXES.length; index += 1) {
2606
+ const prefix = ABSOLUTE_PREFIXES[index];
2607
+ if (prefix !== void 0 && reference.startsWith(prefix)) return true;
2608
+ }
2609
+ return false;
2610
+ }
2419
2611
  //#endregion
2420
2612
  //#region src/animation/loader.ts
2421
2613
  /**
@@ -2588,7 +2780,10 @@ function releaseAtlasTexture(texture) {
2588
2780
  /**
2589
2781
  * The centre pivot a frame that declares none uses.
2590
2782
  */
2591
- const CENTRE = .5;
2783
+ const CENTRE_PIVOT$1 = Object.freeze({
2784
+ x: .5,
2785
+ y: .5
2786
+ });
2592
2787
  /**
2593
2788
  * Converts the document's frame rectangles into the adapter's shape.
2594
2789
  *
@@ -2606,10 +2801,16 @@ function toRects(definition) {
2606
2801
  y: frame.y,
2607
2802
  w: frame.w,
2608
2803
  h: frame.h,
2609
- pivotX: frame.pivot?.x ?? CENTRE,
2610
- pivotY: frame.pivot?.y ?? CENTRE,
2611
- sourceW: frame.sourceSize?.x ?? frame.w,
2612
- sourceH: frame.sourceSize?.y ?? frame.h
2804
+ pivotX: readVec2(frame.pivot, CENTRE_PIVOT$1).x,
2805
+ pivotY: readVec2(frame.pivot, CENTRE_PIVOT$1).y,
2806
+ sourceW: readVec2(frame.sourceSize, {
2807
+ x: frame.w,
2808
+ y: frame.h
2809
+ }).x,
2810
+ sourceH: readVec2(frame.sourceSize, {
2811
+ x: frame.w,
2812
+ y: frame.h
2813
+ }).y
2613
2814
  });
2614
2815
  }
2615
2816
  return rects;
@@ -2654,6 +2855,27 @@ function warnUnextrudedFrames(definition, address, log) {
2654
2855
  }
2655
2856
  }
2656
2857
  /**
2858
+ * Resolves an atlas document's `image` reference to the URL to fetch.
2859
+ *
2860
+ * @remarks
2861
+ * A relative reference is an **address** relative to the atlas document's own address and goes
2862
+ * through the asset manifest (`assets.resolveUrl`), so a production build that content-hashes the
2863
+ * asset root still finds the image. A root-relative (`/sheet.png`) or absolute (`https://…`,
2864
+ * `blob:`, `data:`) reference is a URL and is fetched verbatim — the shape a file in Vite's `public/`
2865
+ * directory has. Resolving against the document's *URL* instead broke hashed builds (Phase 6).
2866
+ *
2867
+ * @param assets - The app's asset service, or anything with its `resolveUrl`.
2868
+ * @param atlasAddress - The address of the atlas document.
2869
+ * @param image - The `image` reference as written in the document.
2870
+ * @returns The URL to load the sheet from.
2871
+ *
2872
+ * @internal
2873
+ */
2874
+ function resolveAtlasImageUrl(assets, atlasAddress, image) {
2875
+ const reference = resolveRelative(atlasAddress, image);
2876
+ return isAbsoluteReference(reference) ? reference : assets.resolveUrl(reference);
2877
+ }
2878
+ /**
2657
2879
  * Builds the loader for `.atlas.json` addresses.
2658
2880
  *
2659
2881
  * @returns The loader to register with `ctx.registerAssetLoader`.
@@ -2674,7 +2896,7 @@ function createSpriteAtlasLoader() {
2674
2896
  warnUnextrudedFrames(definition, ctx.address, ctx.app.log);
2675
2897
  if (ctx.app.isHeadless) return new SpriteAtlasAsset(ctx.address, definition, null, null);
2676
2898
  ctx.reportProgress(0);
2677
- const url = resolveRelative(ctx.url, definition.image);
2899
+ const url = resolveAtlasImageUrl(ctx.app.assets, ctx.address, definition.image);
2678
2900
  const texture = await loadAtlasTexture(ctx.lite.engine, url, definition.sampling, definition.premultipliedAlpha);
2679
2901
  ctx.reportProgress(1);
2680
2902
  const atlas = buildAtlas(texture, texture.width, texture.height, toRects(definition), definition.premultipliedAlpha);
@@ -2911,9 +3133,17 @@ function pivotedPositionToRef(anchorXPx, anchorYPx, pivot, widthPx, heightPx, ro
2911
3133
  * together; screen-space layers keep the identity view. The 2D sync system does the writing —
2912
3134
  * this class owns the arithmetic and the public conversions.
2913
3135
  */
2914
- /** The half-height, in metres, a camera that declares none shows. @public */
3136
+ /**
3137
+ * The half-height, in metres, a camera that declares none shows.
3138
+ *
3139
+ * @public
3140
+ */
2915
3141
  const DEFAULT_ORTHOGRAPHIC_SIZE = 5;
2916
- /** The reference resolution a pixel-perfect camera fits an integer zoom to. @public */
3142
+ /**
3143
+ * The reference resolution a pixel-perfect camera fits an integer zoom to.
3144
+ *
3145
+ * @public
3146
+ */
2917
3147
  const DEFAULT_REFERENCE_RESOLUTION = Object.freeze({
2918
3148
  x: 640,
2919
3149
  y: 360
@@ -2954,6 +3184,10 @@ var Camera2D = class Camera2D extends Component {
2954
3184
  #zoom = 1;
2955
3185
  /** The world centre the last sync used, after bounds clamping and pixel snapping. */
2956
3186
  #centre = new Vec2();
3187
+ /** Scratch, so the conversions allocate nothing (coding standards §7). */
3188
+ #scratchA = new Vec2();
3189
+ /** Scratch; see {@link Camera2D.screenToWorld}. */
3190
+ #scratchB = new Vec2();
2957
3191
  /**
2958
3192
  * Builds a camera with the schema's defaults.
2959
3193
  */
@@ -3051,7 +3285,7 @@ var Camera2D = class Camera2D extends Component {
3051
3285
  out.y = this.#centre.y;
3052
3286
  return out;
3053
3287
  }
3054
- const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, SCRATCH_A);
3288
+ const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, this.#scratchA);
3055
3289
  const offsetX = (x - this.#viewportWidthPx * .5) / zoom;
3056
3290
  const offsetY = (y - this.#viewportHeightPx * .5) / zoom;
3057
3291
  const rotation = viewRotationToLite(this.#rotationDegrees());
@@ -3068,8 +3302,8 @@ var Camera2D = class Camera2D extends Component {
3068
3302
  */
3069
3303
  worldToScreen(point, out = new Vec2()) {
3070
3304
  const zoom = this.#zoom;
3071
- const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, SCRATCH_A);
3072
- const pointPx = worldToPixelsToRef(point.x, point.y, this.#pixelsPerUnit, SCRATCH_B);
3305
+ const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, this.#scratchA);
3306
+ const pointPx = worldToPixelsToRef(point.x, point.y, this.#pixelsPerUnit, this.#scratchB);
3073
3307
  const deltaX = pointPx.x - centrePx.x;
3074
3308
  const deltaY = pointPx.y - centrePx.y;
3075
3309
  const rotation = viewRotationToLite(this.#rotationDegrees());
@@ -3088,10 +3322,6 @@ var Camera2D = class Camera2D extends Component {
3088
3322
  return this.entity.transform.rotation2D;
3089
3323
  }
3090
3324
  };
3091
- /** Scratch vectors so the conversions allocate nothing (coding standards §7). */
3092
- const SCRATCH_A = new Vec2();
3093
- /** Scratch vector; see {@link SCRATCH_A}. */
3094
- const SCRATCH_B = new Vec2();
3095
3325
  /**
3096
3326
  * Clamps a camera centre so the viewport stays inside a bound.
3097
3327
  *
@@ -3244,6 +3474,10 @@ function beyond(desired, current, half) {
3244
3474
  * @param clear - Whether the sprite pass clears first. `false` in `"mixed"` mode, so the 3D scene's
3245
3475
  * colour survives underneath.
3246
3476
  * @param clearColor - The clear value used when `clear` is `true`, as straight RGBA in `0` to `1`.
3477
+ * @param clearColor.r - The red channel.
3478
+ * @param clearColor.g - The green channel.
3479
+ * @param clearColor.b - The blue channel.
3480
+ * @param clearColor.a - The alpha channel.
3247
3481
  * @returns The registered renderer.
3248
3482
  *
3249
3483
  * @internal
@@ -3319,48 +3553,273 @@ function enableSpriteDeviceLostRecovery(engine, onRecovered, onFailed) {
3319
3553
  });
3320
3554
  }
3321
3555
  //#endregion
3322
- //#region src/tilemap/definition.ts
3556
+ //#region src/sprite/parallax-layer.ts
3323
3557
  /**
3324
- * The `ignifx.tilemap` document — the `.tilemap.json` file that names tile sizes, tilesets, tile
3325
- * layers and object layers (`docs/architecture/06-serialization-and-scene-format.md` §6,
3326
- * `11-2d-toolkit.md` §2.5).
3327
- *
3328
- * Two coordinate conventions meet in this file and it is worth stating both loudly, because getting
3329
- * them backwards is the single easiest mistake to make in a tilemap pipeline:
3330
- *
3331
- * - **Authoring space** (everything on `TileColliderDefinition` and every editor this package
3332
- * imports from) is cell-normalised `[0, 1]` with the origin at the **top-left** of the cell and
3333
- * +Y pointing **down**. Tiled and LDtk both emit pixels in that orientation, and the importers
3334
- * divide by the tile size rather than flipping.
3335
- * - **Runtime space** (`TileCollisionShape`, `TilemapCollisionData`, and every world coordinate on
3336
- * `TilemapObjectDefinition`) is metres with the origin at the **bottom-left** and +Y pointing
3337
- * **up**, because that is the ignifx 2D world (ADR-0011).
3558
+ * `ParallaxLayer` (`docs/architecture/11-2d-toolkit.md` §2.6): makes one sorting layer scroll at a
3559
+ * fraction of the camera's speed, which is what gives a side-scroller depth.
3338
3560
  *
3339
- * {@link tileCollisionInfo} is the one function that crosses between them, so the flip lives in
3340
- * exactly one place — the same discipline `../math/coords.ts` applies to the render path.
3561
+ * The component owns no sprites. It reaches into the views of every Lite layer belonging to its
3562
+ * sorting layer, after the 2D sync system has written the camera's view onto them, and slides each
3563
+ * one back by `cameraPositionPx × (1 − factor)`. A factor of `1` moves with the camera (no
3564
+ * parallax); `0` is pinned to the world origin, which is what a distant sky wants.
3341
3565
  */
3342
3566
  /**
3343
- * The `format` discriminator every `.tilemap.json` document carries.
3567
+ * A parallax layer.
3568
+ *
3569
+ * @example
3570
+ * ```ts
3571
+ * const sky = app.world.createEntity({ name: "sky" }).addComponent(ParallaxLayer);
3572
+ * sky.sortingLayer = "Background";
3573
+ * sky.factor = { x: 0.2, y: 0.5 };
3574
+ * ```
3344
3575
  *
3345
3576
  * @public
3346
3577
  */
3347
- const TILEMAP_FORMAT = "ignifx.tilemap";
3578
+ var ParallaxLayer = class ParallaxLayer extends Component {
3579
+ /** The registration id the serializer writes into scene files. */
3580
+ static typeId = "ignifx/ParallaxLayer";
3581
+ /** One parallax setting per entity; several entities may each drive a different sorting layer. */
3582
+ static allowMultiple = false;
3583
+ /** The declarative fields (ADR-0004). */
3584
+ static schema = parallaxLayerSchema();
3585
+ /** Scratch, so applying the offset allocates nothing. */
3586
+ #scratch = new Vec2();
3587
+ /**
3588
+ * Builds a parallax layer with the schema's defaults.
3589
+ */
3590
+ constructor() {
3591
+ super();
3592
+ Object.assign(this, createDefaults(ParallaxLayer.schema));
3593
+ }
3594
+ /**
3595
+ * Slides every matching layer's view.
3596
+ *
3597
+ * @remarks
3598
+ * Runs after the camera has written its own view, so the arithmetic is a pure offset:
3599
+ * `view.positionPx -= cameraPx × (1 − factor)`. With `repeatX`/`repeatY` the offset is taken
3600
+ * modulo one repetition, which keeps a tiled backdrop from drifting away from the camera no
3601
+ * matter how far the player walks — and keeps the number in single-precision range.
3602
+ *
3603
+ * @param entries - Every layer, as the registry describes them.
3604
+ * @param camera - The active camera.
3605
+ * @param pixelsPerUnit - The pixels one metre spans.
3606
+ *
3607
+ * @internal
3608
+ */
3609
+ applyTo(entries, camera, pixelsPerUnit) {
3610
+ const cameraPx = worldToPixelsToRef(camera.centre.x, camera.centre.y, pixelsPerUnit, this.#scratch);
3611
+ let offsetX = cameraPx.x * (1 - this.factor.x);
3612
+ let offsetY = cameraPx.y * (1 - this.factor.y);
3613
+ if (this.repeatX && this.repeatWidth > 0) offsetX = wrap(offsetX, this.repeatWidth * pixelsPerUnit);
3614
+ if (this.repeatY && this.repeatHeight > 0) offsetY = wrap(offsetY, this.repeatHeight * pixelsPerUnit);
3615
+ for (let index = 0; index < entries.length; index += 1) {
3616
+ const entry = entries[index];
3617
+ if (entry === void 0 || entry.screenSpace || entry.sortingLayer !== this.sortingLayer) continue;
3618
+ const view = entry.layer.view;
3619
+ view.positionPx[0] -= offsetX;
3620
+ view.positionPx[1] -= offsetY;
3621
+ }
3622
+ }
3623
+ };
3348
3624
  /**
3349
- * The document version this build reads and writes.
3625
+ * Wraps a value into `[0, span)`, keeping the sign of the mathematical modulus.
3350
3626
  *
3351
- * @public
3627
+ * @param value - The value.
3628
+ * @param span - The period; must be greater than zero.
3629
+ * @returns The wrapped value.
3352
3630
  */
3353
- const TILEMAP_FORMAT_VERSION = 1;
3631
+ function wrap(value, span) {
3632
+ const remainder = value % span;
3633
+ return remainder < 0 ? remainder + span : remainder;
3634
+ }
3354
3635
  /**
3355
- * The asset type name the loader registers.
3636
+ * The `ParallaxLayer` schema.
3356
3637
  *
3357
- * @public
3638
+ * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
3358
3639
  */
3359
- const TILEMAP_ASSET_TYPE = "tilemap";
3640
+ function parallaxLayerSchema() {
3641
+ return defineSchema({
3642
+ sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: "Which sorting layer scrolls slowly." }),
3643
+ factor: vec2({
3644
+ x: .5,
3645
+ y: 1
3646
+ }, { tooltip: "Fraction of the camera's motion the layer follows." }),
3647
+ repeatX: bool(false, { tooltip: "Tile the layer horizontally across the camera's view." }),
3648
+ repeatY: bool(false, { tooltip: "Tile the layer vertically." }),
3649
+ repeatWidth: f32(0, {
3650
+ min: 0,
3651
+ tooltip: "World width of one repetition, in metres."
3652
+ }),
3653
+ repeatHeight: f32(0, {
3654
+ min: 0,
3655
+ tooltip: "World height of one repetition, in metres."
3656
+ })
3657
+ });
3658
+ }
3659
+ //#endregion
3660
+ //#region src/sprite/sprite-layer-effect.ts
3360
3661
  /**
3361
- * The address suffixes that select the tilemap loader.
3662
+ * `SpriteLayerEffect` (`docs/architecture/11-2d-toolkit.md` §6): a per-layer custom fragment shader.
3362
3663
  *
3363
- * @public
3664
+ * Lite's 2D path has no lighting model, so effects are what a 2D game reaches for instead: a tint,
3665
+ * a dissolve, water, a heat shimmer. A layer created with a `customShader`
3666
+ * (`Sprite2DLayerOptions.customShader`, `index.d.ts` 11934) runs a WGSL fragment body with a
3667
+ * built-in `fx.time` clock and a `fx.params` vec4 the component writes every frame through
3668
+ * `setSprite2DShaderParams` (`index.d.ts` 11074).
3669
+ *
3670
+ * ## The one-shader-per-layer constraint
3671
+ *
3672
+ * `Sprite2DLayer.customShader` is `readonly` and is only set at creation. A layer's shader
3673
+ * therefore cannot change once sprites are in it, so `SpriteLayerEffect` has to exist **before**
3674
+ * the first sprite on its sorting layer is synced — put it in the scene file, or add it in
3675
+ * `awake`, not halfway through a level.
3676
+ */
3677
+ /**
3678
+ * The built-in effects, in the order an inspector should list them.
3679
+ *
3680
+ * @public
3681
+ */
3682
+ const SPRITE_EFFECT_KINDS = ["tint", "custom"];
3683
+ /**
3684
+ * The WGSL body of the built-in `tint` effect.
3685
+ *
3686
+ * @remarks
3687
+ * Multiplies the sampled texel by `fx.params.rgb` and scales its alpha by `fx.params.a`, which is
3688
+ * a per-layer tint that a per-sprite `color` cannot express — every sprite in the layer fades
3689
+ * together, in one uniform write, rather than in one instance write each.
3690
+ *
3691
+ * @public
3692
+ */
3693
+ const TINT_EFFECT_WGSL = "let texel = textureSample(atlasTex, atlasSamp, uv); return vec4f(texel.rgb * fx.params.rgb, texel.a * fx.params.a);";
3694
+ /**
3695
+ * A per-layer shader effect.
3696
+ *
3697
+ * @example
3698
+ * ```ts
3699
+ * const dusk = app.world.createEntity({ name: "dusk" }).addComponent(SpriteLayerEffect);
3700
+ * dusk.sortingLayer = "Default";
3701
+ * dusk.kind = "tint";
3702
+ * dusk.tint = { r: 0.6, g: 0.6, b: 0.9, a: 1 };
3703
+ * ```
3704
+ *
3705
+ * @public
3706
+ */
3707
+ var SpriteLayerEffect = class SpriteLayerEffect extends Component {
3708
+ /** The registration id the serializer writes into scene files. */
3709
+ static typeId = "ignifx/SpriteLayerEffect";
3710
+ /** One effect per entity; several entities may each drive a different sorting layer. */
3711
+ static allowMultiple = false;
3712
+ /** The declarative fields (ADR-0004). */
3713
+ static schema = spriteLayerEffectSchema();
3714
+ /**
3715
+ * Builds an effect with the schema's defaults.
3716
+ */
3717
+ constructor() {
3718
+ super();
3719
+ Object.assign(this, createDefaults(SpriteLayerEffect.schema));
3720
+ }
3721
+ /**
3722
+ * The WGSL fragment body this effect installs.
3723
+ *
3724
+ * @returns The shader source.
3725
+ * @throws IgnifxError with code `IGX-1113` when `kind` is `"custom"` and `shader` is empty.
3726
+ */
3727
+ source() {
3728
+ if (this.kind === "tint") return TINT_EFFECT_WGSL;
3729
+ if (this.shader === "") throw twoDError(TwoDErrorCode.missingShaderSource, "A custom SpriteLayerEffect needs a WGSL fragment body.", {
3730
+ context: {
3731
+ sortingLayer: this.sortingLayer,
3732
+ entity: this.entity.uid
3733
+ },
3734
+ hint: "Set `effect.shader` to a WGSL body, or use kind: \"tint\"."
3735
+ });
3736
+ return this.shader;
3737
+ }
3738
+ /**
3739
+ * The `fx.params` vec4 to write this frame.
3740
+ *
3741
+ * @param out - The four numbers to fill.
3742
+ * @returns `out`.
3743
+ *
3744
+ * @internal
3745
+ */
3746
+ writeParams(out) {
3747
+ if (this.kind === "tint") {
3748
+ out[0] = this.tint.r;
3749
+ out[1] = this.tint.g;
3750
+ out[2] = this.tint.b;
3751
+ out[3] = this.tint.a;
3752
+ return out;
3753
+ }
3754
+ out[0] = this.params.x;
3755
+ out[1] = this.params.y;
3756
+ out[2] = this.params.z;
3757
+ out[3] = this.params.w;
3758
+ return out;
3759
+ }
3760
+ };
3761
+ /**
3762
+ * The `SpriteLayerEffect` schema.
3763
+ *
3764
+ * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
3765
+ */
3766
+ function spriteLayerEffectSchema() {
3767
+ return defineSchema({
3768
+ sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: "Which sorting layer the effect applies to." }),
3769
+ kind: enumOf(SPRITE_EFFECT_KINDS, "tint", { tooltip: "Which shader to install." }),
3770
+ tint: color("#ffffffff", { tooltip: "The colour the tint effect multiplies by." }),
3771
+ params: vec4({
3772
+ x: 0,
3773
+ y: 0,
3774
+ z: 0,
3775
+ w: 0
3776
+ }, { tooltip: "The fx.params vec4 a custom shader reads." }),
3777
+ shader: str("", { tooltip: "The WGSL fragment body a custom effect installs." })
3778
+ });
3779
+ }
3780
+ //#endregion
3781
+ //#region src/tilemap/definition.ts
3782
+ /**
3783
+ * The `ignifx.tilemap` document — the `.tilemap.json` file that names tile sizes, tilesets, tile
3784
+ * layers and object layers (`docs/architecture/06-serialization-and-scene-format.md` §6,
3785
+ * `11-2d-toolkit.md` §2.5).
3786
+ *
3787
+ * Two coordinate conventions meet in this file and it is worth stating both loudly, because getting
3788
+ * them backwards is the single easiest mistake to make in a tilemap pipeline:
3789
+ *
3790
+ * - **Authoring space** (everything on `TileColliderDefinition` and every editor this package
3791
+ * imports from) is cell-normalised `[0, 1]` with the origin at the **top-left** of the cell and
3792
+ * +Y pointing **down**. Tiled and LDtk both emit pixels in that orientation, and the importers
3793
+ * divide by the tile size rather than flipping.
3794
+ * - **Runtime space** (`TileCollisionShape`, `TilemapCollisionData`, and every world coordinate on
3795
+ * `TilemapObjectDefinition`) is metres with the origin at the **bottom-left** and +Y pointing
3796
+ * **up**, because that is the ignifx 2D world (ADR-0011).
3797
+ *
3798
+ * {@link tileCollisionInfo} is the one function that crosses between them, so the flip lives in
3799
+ * exactly one place — the same discipline `../math/coords.ts` applies to the render path.
3800
+ */
3801
+ /**
3802
+ * The `format` discriminator every `.tilemap.json` document carries.
3803
+ *
3804
+ * @public
3805
+ */
3806
+ const TILEMAP_FORMAT = "ignifx.tilemap";
3807
+ /**
3808
+ * The document version this build reads and writes.
3809
+ *
3810
+ * @public
3811
+ */
3812
+ const TILEMAP_FORMAT_VERSION = 1;
3813
+ /**
3814
+ * The asset type name the loader registers.
3815
+ *
3816
+ * @public
3817
+ */
3818
+ const TILEMAP_ASSET_TYPE = "tilemap";
3819
+ /**
3820
+ * The address suffixes that select the tilemap loader.
3821
+ *
3822
+ * @public
3364
3823
  */
3365
3824
  const TILEMAP_FILE_EXTENSIONS = Object.freeze([".tilemap.json"]);
3366
3825
  /**
@@ -3466,7 +3925,7 @@ function defineTilemap(input, address = "<inline>") {
3466
3925
  });
3467
3926
  };
3468
3927
  if (input.format !== void 0 && input.format !== "ignifx.tilemap") fail(`its format is ${input.format}, not ${TILEMAP_FORMAT}`);
3469
- if (input.version !== void 0 && input.version !== 1) fail(`its version is ${String(input.version)}, and this build reads ${String(1)}`);
3928
+ if (input.formatVersion !== void 0 && input.formatVersion !== 1) fail(`its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(1)}`);
3470
3929
  const tileWidth = input.tileWidth;
3471
3930
  const tileHeight = input.tileHeight ?? input.tileWidth;
3472
3931
  if (!(tileWidth > 0) || !(tileHeight > 0)) fail(`its tile size is ${String(tileWidth)}x${String(tileHeight)} pixels, which is not positive`);
@@ -3510,7 +3969,7 @@ function defineTilemap(input, address = "<inline>") {
3510
3969
  }
3511
3970
  return {
3512
3971
  format: TILEMAP_FORMAT,
3513
- version: 1,
3972
+ formatVersion: 1,
3514
3973
  tileWidth,
3515
3974
  tileHeight,
3516
3975
  cellSize: input.cellSize ?? tileWidth / 100,
@@ -3659,1530 +4118,1735 @@ function tileCollisionInfo(map, tileId) {
3659
4118
  }
3660
4119
  }
3661
4120
  //#endregion
3662
- //#region src/tilemap/collision-merge.ts
3663
- /**
3664
- * Whether a tile's collider fills its whole cell and is not a one-way platform — the only shape the
3665
- * rectangle merge can absorb.
3666
- *
3667
- * @param info - The tile's collision info, in cell-local metres.
3668
- * @param cellSize - The edge length of one cell, in metres.
3669
- * @returns Whether the tile is a plain, full-cell solid.
3670
- *
3671
- * @example
3672
- * ```ts
3673
- * isFullCellSolid({ shape: { kind: "box", x: 0, y: 0, width: 1, height: 1 }, oneWay: false, properties: {} }, 1);
3674
- * // true
3675
- * ```
3676
- *
3677
- * @public
3678
- */
3679
- function isFullCellSolid(info, cellSize) {
3680
- if (info.oneWay) return false;
3681
- const shape = info.shape;
3682
- return shape.kind === "box" && shape.x === 0 && shape.y === 0 && shape.width === cellSize && shape.height === cellSize;
3683
- }
4121
+ //#region src/tilemap/tilemap-renderer.ts
3684
4122
  /**
3685
- * Merges a grid of per-tile collision shapes into chunked, world-space polygons.
3686
- *
3687
- * @remarks
3688
- * **Coordinates.** `infoAt` is called with cell coordinates in which `y = 0` is the **bottom** row,
3689
- * because the ignifx 2D world is +Y up; a caller reading a `TilemapLayerDefinition`, whose rows run
3690
- * top-first, indexes it as `(height - 1 - y) * width + x`. Everything this function emits is world
3691
- * metres relative to the tilemap's origin, so cell `(x, y)` spans
3692
- * `[x·cellSize, (x+1)·cellSize] × [y·cellSize, (y+1)·cellSize]`.
3693
- *
3694
- * **The merge.** Each chunk is handled independently, so a later edit rebuilds one chunk rather than
3695
- * the map. Inside a chunk, cells that {@link isFullCellSolid} accepts go into a boolean grid and are
3696
- * merged in two greedy passes: first every row is cut into maximal horizontal runs, then a run
3697
- * extends upwards for as long as the row above holds a run with exactly the same span, which is
3698
- * marked consumed. Each surviving block is emitted as one counter-clockwise rectangle. It is the
3699
- * classic row-then-column greedy mesher: linear in cells plus a small scan per row, and optimal for
3700
- * rectangles while deliberately not optimal in general — an L-shape comes out as two rectangles, not
3701
- * one six-vertex polygon, and that is the trade the algorithm makes for being O(n).
3702
- *
3703
- * Anything the rectangle pass cannot absorb — a partial box, a slope polygon — is emitted as its own
3704
- * polygon, translated into world metres. Its winding is already counter-clockwise, because
3705
- * `tileCollisionInfo` guarantees it.
3706
- *
3707
- * **One-way platforms.** A one-way tile contributes no polygon at all; it contributes its collider's
3708
- * **top edge** to `oneWayEdges`. The winding follows the same rule as a polygon: the solid material
3709
- * is to the **left** of `from → to`. For a directed edge `d = to − from`, "left" is `d` rotated a
3710
- * quarter turn counter-clockwise, `(−dy, dx)`. An upward-facing platform is solid *below* its
3711
- * surface — that is the half you cannot pass through once you have landed — so we need
3712
- * `(−dy, dx) = (0, −1)`, giving `dy = 0` and `dx = −1`. The edge therefore runs from its **right**
3713
- * end to its **left** end.
3714
- *
3715
- * Chunks that end up with neither a polygon nor a one-way edge are omitted entirely.
3716
- *
3717
- * @param infoAt - The per-cell collision info, in cell coordinates with `y = 0` at the bottom.
3718
- * @param options - The cell size, chunk size, and grid extent.
3719
- * @param version - The version stamp to carry into the result; callers increment it per rebuild.
3720
- * @returns The chunked collision data.
4123
+ * A tilemap renderer.
3721
4124
  *
3722
4125
  * @example
3723
4126
  * ```ts
3724
- * const data = mergeTileCollisions((x, y) => tileCollisionInfo(map, tileAt(x, y)), {
3725
- * cellSize: map.cellSize,
3726
- * chunkSize: 32,
3727
- * width: map.width,
3728
- * height: map.height,
3729
- * }, 1);
4127
+ * const level = app.world.createEntity({ name: "level" });
4128
+ * level.addComponent(Tilemap).map = app.assets.load<TilemapAsset>("2d/level-1.tilemap.json").retain();
4129
+ * const renderer = level.addComponent(TilemapRenderer);
4130
+ * renderer.atlas = app.assets.load<SpriteAtlasAsset>("2d/tiles.atlas.json").retain();
3730
4131
  * ```
3731
4132
  *
3732
4133
  * @public
3733
4134
  */
3734
- function mergeTileCollisions(infoAt, options, version) {
3735
- const { cellSize, chunkSize, width, height } = options;
3736
- const chunks = [];
3737
- if (cellSize <= 0 || chunkSize <= 0 || width <= 0 || height <= 0) return {
3738
- cellSize,
3739
- chunkSize,
3740
- chunks,
3741
- version
3742
- };
3743
- const chunksX = Math.ceil(width / chunkSize);
3744
- const chunksY = Math.ceil(height / chunkSize);
3745
- for (let chunkY = 0; chunkY < chunksY; chunkY += 1) for (let chunkX = 0; chunkX < chunksX; chunkX += 1) {
3746
- const chunk = mergeChunk(infoAt, options, chunkX, chunkY);
3747
- if (chunk !== null) chunks.push(chunk);
3748
- }
3749
- return {
3750
- cellSize,
3751
- chunkSize,
3752
- chunks,
3753
- version
3754
- };
3755
- }
3756
- /**
3757
- * Merges one chunk of the grid.
3758
- *
3759
- * @param infoAt - The per-cell collision info.
3760
- * @param options - The cell size, chunk size, and grid extent.
3761
- * @param chunkX - The chunk's column index.
3762
- * @param chunkY - The chunk's row index.
3763
- * @returns The chunk, or `null` when it carries no geometry.
3764
- */
3765
- function mergeChunk(infoAt, options, chunkX, chunkY) {
3766
- const { cellSize, chunkSize, width, height } = options;
3767
- const originX = chunkX * chunkSize;
3768
- const originY = chunkY * chunkSize;
3769
- const columns = Math.min(chunkSize, width - originX);
3770
- const rows = Math.min(chunkSize, height - originY);
3771
- const polygons = [];
3772
- const oneWayEdges = [];
3773
- const solid = new Uint8Array(columns * rows);
3774
- for (let localY = 0; localY < rows; localY += 1) for (let localX = 0; localX < columns; localX += 1) {
3775
- const cellX = originX + localX;
3776
- const cellY = originY + localY;
3777
- const info = infoAt(cellX, cellY);
3778
- const shape = info.shape;
3779
- if (shape.kind === "none") continue;
3780
- if (info.oneWay) {
3781
- const edge = topEdge(shape, cellX * cellSize, cellY * cellSize);
3782
- if (edge !== null) oneWayEdges.push(edge);
3783
- continue;
4135
+ var TilemapRenderer = class TilemapRenderer extends Component {
4136
+ /** The registration id the serializer writes into scene files. */
4137
+ static typeId = "ignifx/TilemapRenderer";
4138
+ /** One renderer per entity. */
4139
+ static allowMultiple = false;
4140
+ /** The declarative fields (ADR-0004). */
4141
+ static schema = tilemapRendererSchema();
4142
+ /** Chunks currently materialised, keyed by `<chunkX>,<chunkY>`. */
4143
+ #chunks = /* @__PURE__ */ new Map();
4144
+ /** The reusable props record, so building a chunk allocates one object rather than 1024. */
4145
+ #scratch = createSpriteScratch();
4146
+ /** Scratch, so the per-chunk arithmetic allocates nothing. */
4147
+ #pixels = new Vec2();
4148
+ /** How far animated tiles have advanced, in seconds. */
4149
+ #animationClock = 0;
4150
+ /** Whether every chunk must be rebuilt, because the map or the atlas changed. */
4151
+ #isStale = true;
4152
+ /**
4153
+ * Builds a renderer with the schema's defaults.
4154
+ */
4155
+ constructor() {
4156
+ super();
4157
+ Object.assign(this, createDefaults(TilemapRenderer.schema));
4158
+ }
4159
+ /**
4160
+ * Marks every chunk stale, so a recycled component rebuilds.
4161
+ */
4162
+ onAttach() {
4163
+ this.#isStale = true;
4164
+ }
4165
+ /**
4166
+ * Marks every chunk stale; the 2D sync system does the removal, because it owns the layers.
4167
+ */
4168
+ onDetach() {
4169
+ this.#isStale = true;
4170
+ }
4171
+ /**
4172
+ * How many chunks are currently materialised.
4173
+ *
4174
+ * @returns The count.
4175
+ */
4176
+ get chunkCount() {
4177
+ return this.#chunks.size;
4178
+ }
4179
+ /**
4180
+ * How many sprites the materialised chunks hold in total.
4181
+ *
4182
+ * @returns The count.
4183
+ */
4184
+ get spriteCount() {
4185
+ let total = 0;
4186
+ for (const chunk of this.#chunks.values()) total += chunk.sprites.length;
4187
+ return total;
4188
+ }
4189
+ /**
4190
+ * The loaded atlas, or `null`.
4191
+ *
4192
+ * @returns The atlas.
4193
+ */
4194
+ get loadedAtlas() {
4195
+ const handle = this.atlas;
4196
+ return handle?.state === "loaded" ? handle.value : null;
4197
+ }
4198
+ /**
4199
+ * Forces every chunk to be rebuilt on the next sync.
4200
+ *
4201
+ * @remarks
4202
+ * `Tilemap.onTileChanged` is what normally calls this — a rewritten cell has to reach the sprite
4203
+ * that draws it, and rebuilding the chunk is both simpler and, for anything short of a per-frame
4204
+ * rewrite, cheaper than tracking one sprite per cell.
4205
+ *
4206
+ * @internal
4207
+ */
4208
+ invalidate() {
4209
+ this.#isStale = true;
4210
+ }
4211
+ /**
4212
+ * Brings the materialised chunks in line with the camera's visible bounds.
4213
+ *
4214
+ * @param map - The tilemap being drawn.
4215
+ * @param registry - The layer registry that owns the Lite layers.
4216
+ * @param bounds - The camera's visible bounds, in layer pixels, or `null` to build every chunk.
4217
+ * @param pixelsPerUnit - The pixels one metre spans.
4218
+ * @returns How many sprites were written this call; `0` on a steady frame.
4219
+ *
4220
+ * @internal
4221
+ */
4222
+ sync(map, registry, bounds, pixelsPerUnit) {
4223
+ const atlas = this.loadedAtlas;
4224
+ const definition = map.definition;
4225
+ if (atlas === null || atlas.lite.atlas === null || definition === null) return 0;
4226
+ if (this.#isStale) {
4227
+ this.#dropAll(registry);
4228
+ this.#isStale = false;
3784
4229
  }
3785
- if (isFullCellSolid(info, cellSize)) {
3786
- solid[localY * columns + localX] = 1;
3787
- continue;
4230
+ const chunkSize = Math.max(1, map.chunkSize);
4231
+ const cellSize = map.cellSize;
4232
+ if (cellSize <= 0) return 0;
4233
+ const chunksX = Math.ceil(definition.width / chunkSize);
4234
+ const chunksY = Math.ceil(definition.height / chunkSize);
4235
+ const window = this.#chunkWindow(bounds, chunkSize, cellSize, pixelsPerUnit, chunksX, chunksY);
4236
+ let written = 0;
4237
+ for (const [key, chunk] of this.#chunks) if (!inWindow(chunk.chunkX, chunk.chunkY, window)) this.#drop(registry, key, chunk);
4238
+ for (let chunkY = window.minY; chunkY <= window.maxY; chunkY += 1) for (let chunkX = window.minX; chunkX <= window.maxX; chunkX += 1) {
4239
+ const key = `${String(chunkX)},${String(chunkY)}`;
4240
+ if (this.#chunks.has(key)) continue;
4241
+ written += this.#build(map, atlas, registry, chunkX, chunkY, chunkSize, cellSize, pixelsPerUnit);
3788
4242
  }
3789
- polygons.push(translateShape(shape, cellX * cellSize, cellY * cellSize));
4243
+ return written;
3790
4244
  }
3791
- mergeSolidRuns(solid, columns, rows, originX, originY, cellSize, polygons);
3792
- if (polygons.length === 0 && oneWayEdges.length === 0) return null;
3793
- return {
3794
- chunkX,
3795
- chunkY,
3796
- polygons,
3797
- oneWayEdges
3798
- };
3799
- }
3800
- /**
3801
- * Runs the row-then-column greedy merge over the chunk's full-cell solid mask.
3802
- *
3803
- * @param solid - The `columns * rows` mask, row-major with row `0` at the bottom.
3804
- * @param columns - The chunk's width in cells.
3805
- * @param rows - The chunk's height in cells.
3806
- * @param originX - The chunk's first column, in grid cells.
3807
- * @param originY - The chunk's first row, in grid cells.
3808
- * @param cellSize - The edge length of one cell, in metres.
3809
- * @param out - The polygon list to append merged rectangles to.
3810
- */
3811
- function mergeSolidRuns(solid, columns, rows, originX, originY, cellSize, out) {
3812
- const runsByRow = [];
3813
- for (let localY = 0; localY < rows; localY += 1) {
3814
- const runs = [];
3815
- let localX = 0;
3816
- while (localX < columns) {
3817
- if (solid[localY * columns + localX] !== 1) {
3818
- localX += 1;
3819
- continue;
4245
+ /**
4246
+ * Advances animated tiles and rewrites the chunks holding them.
4247
+ *
4248
+ * @param deltaSeconds - The scaled frame delta.
4249
+ * @returns `true` when a tile's frame changed, so the renderer must rebuild.
4250
+ *
4251
+ * @internal
4252
+ */
4253
+ advanceAnimation(deltaSeconds) {
4254
+ const previous = this.#animationClock;
4255
+ this.#animationClock += deltaSeconds;
4256
+ return Math.floor(previous * ANIMATION_TICKS_PER_SECOND) !== Math.floor(this.#animationClock * ANIMATION_TICKS_PER_SECOND);
4257
+ }
4258
+ /**
4259
+ * The animation clock animated tiles are sampled at, in seconds.
4260
+ *
4261
+ * @returns The elapsed time.
4262
+ *
4263
+ * @internal
4264
+ */
4265
+ get animationClock() {
4266
+ return this.#animationClock;
4267
+ }
4268
+ /**
4269
+ * Drops every materialised chunk.
4270
+ *
4271
+ * @param registry - The layer registry.
4272
+ *
4273
+ * @internal
4274
+ */
4275
+ dropAll(registry) {
4276
+ this.#dropAll(registry);
4277
+ }
4278
+ /**
4279
+ * The range of chunks the camera can see.
4280
+ *
4281
+ * @param bounds - The camera's visible bounds, in layer pixels, or `null`.
4282
+ * @param chunkSize - Cells per chunk.
4283
+ * @param cellSize - Metres per cell.
4284
+ * @param pixelsPerUnit - Pixels per metre.
4285
+ * @param chunksX - How many chunk columns the map has.
4286
+ * @param chunksY - How many chunk rows.
4287
+ * @returns The inclusive chunk window.
4288
+ */
4289
+ #chunkWindow(bounds, chunkSize, cellSize, pixelsPerUnit, chunksX, chunksY) {
4290
+ if (bounds === null || !this.cullChunks) return {
4291
+ minX: 0,
4292
+ minY: 0,
4293
+ maxX: chunksX - 1,
4294
+ maxY: chunksY - 1
4295
+ };
4296
+ const matrix = this.entity.transform.worldMatrix;
4297
+ const originX = matrix[12] ?? 0;
4298
+ const originY = matrix[13] ?? 0;
4299
+ const worldMinX = bounds.minX / pixelsPerUnit - originX;
4300
+ const worldMaxX = bounds.maxX / pixelsPerUnit - originX;
4301
+ const worldMinY = -bounds.maxY / pixelsPerUnit - originY;
4302
+ const worldMaxY = -bounds.minY / pixelsPerUnit - originY;
4303
+ const span = chunkSize * cellSize;
4304
+ return {
4305
+ minX: clampIndex(Math.floor(worldMinX / span), chunksX),
4306
+ maxX: clampIndex(Math.floor(worldMaxX / span), chunksX),
4307
+ minY: clampIndex(Math.floor(worldMinY / span), chunksY),
4308
+ maxY: clampIndex(Math.floor(worldMaxY / span), chunksY)
4309
+ };
4310
+ }
4311
+ /**
4312
+ * Materialises one chunk's sprites.
4313
+ *
4314
+ * @param map - The tilemap.
4315
+ * @param atlas - The tile atlas.
4316
+ * @param registry - The layer registry.
4317
+ * @param chunkX - The chunk's column.
4318
+ * @param chunkY - The chunk's row.
4319
+ * @param chunkSize - Cells per chunk.
4320
+ * @param cellSize - Metres per cell.
4321
+ * @param pixelsPerUnit - Pixels per metre.
4322
+ * @returns How many sprites were created.
4323
+ */
4324
+ #build(map, atlas, registry, chunkX, chunkY, chunkSize, cellSize, pixelsPerUnit) {
4325
+ const definition = map.definition;
4326
+ if (definition === null) return 0;
4327
+ const matrix = this.entity.transform.worldMatrix;
4328
+ const originX = matrix[12] ?? 0;
4329
+ const originY = matrix[13] ?? 0;
4330
+ const sizePx = cellSize * pixelsPerUnit;
4331
+ const sprites = [];
4332
+ for (let layerIndex = 0; layerIndex < definition.layers.length; layerIndex += 1) {
4333
+ const layer = definition.layers[layerIndex];
4334
+ if (layer === void 0) continue;
4335
+ const sortingLayer = layer.sortingLayer === "" ? this.sortingLayer : layer.sortingLayer;
4336
+ const alpha = layer.opacity;
4337
+ const endX = Math.min(layer.width, (chunkX + 1) * chunkSize);
4338
+ const endY = Math.min(layer.height, (chunkY + 1) * chunkSize);
4339
+ for (let y = chunkY * chunkSize; y < endY; y += 1) for (let x = chunkX * chunkSize; x < endX; x += 1) {
4340
+ const tileId = map.getTile(layerIndex, x, y);
4341
+ if (tileId === 0) continue;
4342
+ const frameName = tileFrameName(definition, tileId);
4343
+ const frame = frameName === null ? -1 : atlas.frameIndex(frameName);
4344
+ if (frame < 0) continue;
4345
+ const centre = worldToPixelsToRef(originX + (x + .5) * cellSize, originY + (y + .5) * cellSize, pixelsPerUnit, this.#pixels);
4346
+ writeScratch(this.#scratch, centre.x, centre.y, sizePx, sizePx, frame, 0, 1, 1, 1, alpha, false, false, true);
4347
+ sprites.push(registry.placeRaw(sortingLayer, atlas, "alpha", false, this.#scratch));
3820
4348
  }
3821
- const start = localX;
3822
- while (localX + 1 < columns && solid[localY * columns + localX + 1] === 1) localX += 1;
3823
- runs.push({
3824
- start,
3825
- end: localX,
3826
- consumed: false
3827
- });
3828
- localX += 1;
3829
4349
  }
3830
- runsByRow.push(runs);
4350
+ this.#chunks.set(`${String(chunkX)},${String(chunkY)}`, {
4351
+ chunkX,
4352
+ chunkY,
4353
+ sprites
4354
+ });
4355
+ return sprites.length;
3831
4356
  }
3832
- for (let localY = 0; localY < rows; localY += 1) {
3833
- const runs = runsByRow[localY];
3834
- if (runs === void 0) continue;
3835
- for (let index = 0; index < runs.length; index += 1) {
3836
- const run = runs[index];
3837
- if (run === void 0 || run.consumed) continue;
3838
- let top = localY;
3839
- while (top + 1 < rows) {
3840
- const above = findRun(runsByRow[top + 1], run.start, run.end);
3841
- if (above === null) break;
3842
- above.consumed = true;
3843
- top += 1;
3844
- }
3845
- const left = (originX + run.start) * cellSize;
3846
- const right = (originX + run.end + 1) * cellSize;
3847
- const bottom = (originY + localY) * cellSize;
3848
- const ceiling = (originY + top + 1) * cellSize;
3849
- out.push([
3850
- {
3851
- x: left,
3852
- y: bottom
3853
- },
3854
- {
3855
- x: right,
3856
- y: bottom
3857
- },
3858
- {
3859
- x: right,
3860
- y: ceiling
3861
- },
3862
- {
3863
- x: left,
3864
- y: ceiling
3865
- }
3866
- ]);
4357
+ /**
4358
+ * Removes one chunk's sprites.
4359
+ *
4360
+ * @param registry - The layer registry.
4361
+ * @param key - The chunk key.
4362
+ * @param chunk - The chunk record.
4363
+ */
4364
+ #drop(registry, key, chunk) {
4365
+ for (let index = chunk.sprites.length - 1; index >= 0; index -= 1) {
4366
+ const sprite = chunk.sprites[index];
4367
+ if (sprite !== void 0) registry.removeRaw(sprite.key, sprite.handle);
3867
4368
  }
4369
+ this.#chunks.delete(key);
3868
4370
  }
3869
- }
4371
+ /**
4372
+ * Removes every chunk's sprites.
4373
+ *
4374
+ * @param registry - The layer registry.
4375
+ */
4376
+ #dropAll(registry) {
4377
+ for (const [key, chunk] of this.#chunks) this.#drop(registry, key, chunk);
4378
+ this.#chunks.clear();
4379
+ }
4380
+ };
4381
+ /** How often an animated tile's frame is allowed to change, in ticks per second. */
4382
+ const ANIMATION_TICKS_PER_SECOND = 10;
3870
4383
  /**
3871
- * Finds an unconsumed run with exactly the given span.
4384
+ * Whether a chunk is inside a window.
3872
4385
  *
3873
- * @param runs - The candidate row's runs.
3874
- * @param start - The span's first column.
3875
- * @param end - The span's last column.
3876
- * @returns The matching run, or `null`.
4386
+ * @param x - The chunk column.
4387
+ * @param y - The chunk row.
4388
+ * @param window - The window.
4389
+ * @returns `true` when the chunk should stay materialised.
3877
4390
  */
3878
- function findRun(runs, start, end) {
3879
- if (runs === void 0) return null;
3880
- for (let index = 0; index < runs.length; index += 1) {
3881
- const run = runs[index];
3882
- if (run !== void 0 && !run.consumed && run.start === start && run.end === end) return run;
3883
- }
3884
- return null;
4391
+ function inWindow(x, y, window) {
4392
+ return x >= window.minX && x <= window.maxX && y >= window.minY && y <= window.maxY;
3885
4393
  }
3886
4394
  /**
3887
- * Moves a cell-local shape into world metres.
4395
+ * Clamps a chunk index into a map's range.
3888
4396
  *
3889
- * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.
3890
- * @param offsetX - The cell's left edge, in world metres.
3891
- * @param offsetY - The cell's bottom edge, in world metres.
3892
- * @returns The outline, counter-clockwise, in world metres.
4397
+ * @param value - The index.
4398
+ * @param count - How many chunks the map has on this axis.
4399
+ * @returns The clamped index.
3893
4400
  */
3894
- function translateShape(shape, offsetX, offsetY) {
3895
- if (shape.kind === "box") {
3896
- const left = offsetX + shape.x;
3897
- const bottom = offsetY + shape.y;
3898
- const right = left + shape.width;
3899
- const top = bottom + shape.height;
3900
- return [
3901
- {
3902
- x: left,
3903
- y: bottom
3904
- },
3905
- {
3906
- x: right,
3907
- y: bottom
3908
- },
3909
- {
3910
- x: right,
3911
- y: top
3912
- },
3913
- {
3914
- x: left,
3915
- y: top
3916
- }
3917
- ];
3918
- }
3919
- if (shape.kind === "polygon") {
3920
- const points = [];
3921
- for (let index = 0; index < shape.points.length; index += 1) {
3922
- const point = shape.points[index];
3923
- if (point !== void 0) points.push({
3924
- x: offsetX + point.x,
3925
- y: offsetY + point.y
3926
- });
3927
- }
3928
- return points;
3929
- }
3930
- return [];
4401
+ function clampIndex(value, count) {
4402
+ return Math.min(Math.max(value, 0), Math.max(0, count - 1));
3931
4403
  }
3932
4404
  /**
3933
- * The top edge of a one-way tile's collider, wound so the solid side is to the left.
4405
+ * The `TilemapRenderer` schema.
3934
4406
  *
3935
- * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.
3936
- * @param offsetX - The cell's left edge, in world metres.
3937
- * @param offsetY - The cell's bottom edge, in world metres.
3938
- * @returns The `[from, to]` pair, right end first, or `null` when the shape has no width.
4407
+ * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
3939
4408
  */
3940
- function topEdge(shape, offsetX, offsetY) {
3941
- if (shape.kind === "box") {
3942
- if (shape.width <= 0) return null;
3943
- const left = offsetX + shape.x;
3944
- const right = left + shape.width;
3945
- const top = offsetY + shape.y + shape.height;
3946
- return [{
3947
- x: right,
3948
- y: top
3949
- }, {
3950
- x: left,
3951
- y: top
3952
- }];
3953
- }
3954
- if (shape.kind === "polygon") {
3955
- let left = Number.POSITIVE_INFINITY;
3956
- let right = Number.NEGATIVE_INFINITY;
3957
- let top = Number.NEGATIVE_INFINITY;
3958
- for (let index = 0; index < shape.points.length; index += 1) {
3959
- const point = shape.points[index];
3960
- if (point === void 0) continue;
3961
- left = Math.min(left, point.x);
3962
- right = Math.max(right, point.x);
3963
- top = Math.max(top, point.y);
3964
- }
3965
- if (!(right > left)) return null;
3966
- return [{
3967
- x: offsetX + right,
3968
- y: offsetY + top
3969
- }, {
3970
- x: offsetX + left,
3971
- y: offsetY + top
3972
- }];
3973
- }
3974
- return null;
4409
+ function tilemapRendererSchema() {
4410
+ return defineSchema({
4411
+ atlas: asset(SpriteAtlasAsset, { tooltip: "The atlas the tile frames come from." }),
4412
+ sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: "Sorting layer used when a map layer names none." }),
4413
+ cullChunks: bool(true, { tooltip: "Drop chunks outside the camera's visible bounds." })
4414
+ });
3975
4415
  }
3976
4416
  //#endregion
3977
- //#region src/tilemap/tilemap-asset.ts
4417
+ //#region src/service/layer-registry.ts
3978
4418
  /**
3979
- * The `tilemap` asset type and its loader (`docs/architecture/05-assets-and-loading.md` §5,
3980
- * `11-2d-toolkit.md` §2.5).
4419
+ * The pool of Lite sprite layers (`docs/architecture/11-2d-toolkit.md` §1).
3981
4420
  *
3982
- * A `.tilemap.json` document is pure data — tile ids, tilesets, objects — so the loader needs no
3983
- * device and behaves identically under a headless app, which is what lets a headless test assert
3984
- * collision geometry and object spawning. The atlases the tilesets name are loaded by
3985
- * `TilemapRenderer`, not here: a map with six tilesets in a scene that only shows one chunk should
3986
- * not upload six textures at load time.
4421
+ * One `Sprite2DLayer` exists per **(sorting layer, atlas, blend mode, screen-space)** tuple,
4422
+ * because Lite binds a layer to one atlas and one blend mode for its whole life (`index.d.ts` 11885
4423
+ * declares both `readonly`). Layers are created on demand as sprites appear and torn down with the
4424
+ * app; a sprite that changes any part of its key is removed from one layer and added to another,
4425
+ * which replaces its handle.
4426
+ *
4427
+ * The registry also carries the **handle-index to component** map that picking needs. Lite has no
4428
+ * per-sprite metadata slot and removes by swapping the last sprite into the freed index
4429
+ * (`lib/sprite/sprite-2d-handle.js`), so the map is a dense array kept in step by applying the same
4430
+ * swap rule.
3987
4431
  */
4432
+ /** How many sprites a new layer pre-allocates room for. */
4433
+ const INITIAL_LAYER_CAPACITY = 64;
3988
4434
  /**
3989
- * A loaded tilemap document.
4435
+ * Builds the composite key two sprites must share to land in one Lite layer.
3990
4436
  *
3991
- * @example
3992
- * ```ts
3993
- * const map = await app.assets.load<TilemapAsset>("2d/level-1.tilemap.json").promise;
3994
- * map.definition.layers.length; // 2
3995
- * ```
4437
+ * @param sortingLayer - The sorting layer's name.
4438
+ * @param atlasAddress - The atlas's address.
4439
+ * @param blend - The blend mode.
4440
+ * @param screenSpace - Whether the layer ignores the camera.
4441
+ * @returns The key.
3996
4442
  *
3997
4443
  * @public
3998
4444
  */
3999
- var TilemapAsset = class {
4000
- /** The type name the asset service registers tilemaps under. */
4001
- static assetType = TILEMAP_ASSET_TYPE;
4002
- /** The address the document was loaded from. */
4003
- address;
4004
- /** The parsed document, with every tile layer decoded to a dense array. */
4005
- definition;
4006
- /** Each tileset's atlas address, resolved against this document's address. */
4007
- atlasAddresses;
4445
+ function spriteLayerKey(sortingLayer, atlasAddress, blend, screenSpace) {
4446
+ return `${sortingLayer}|${atlasAddress}|${blend}|${screenSpace ? "screen" : "world"}`;
4447
+ }
4448
+ /**
4449
+ * Owns every Lite sprite layer in one app.
4450
+ *
4451
+ * @public
4452
+ */
4453
+ var SpriteLayerRegistry = class {
4454
+ #records = /* @__PURE__ */ new Map();
4455
+ /** Records in draw order, rebuilt whenever a layer is created. */
4456
+ #ordered = [];
4457
+ #sortingLayers;
4458
+ #ySort;
4459
+ #onLayerCreated;
4460
+ #onLayerRemoved;
4461
+ /**
4462
+ * Supplies the compiled custom shader a sorting layer's layers are created with.
4463
+ *
4464
+ * @returns The shader, or `null` when no effect covers the layer.
4465
+ */
4466
+ #shaderFor = () => null;
4467
+ /**
4468
+ * Builds the registry.
4469
+ *
4470
+ * @param sortingLayers - Resolves a sorting-layer name to its draw order.
4471
+ * @param ySort - Which sorting layers draw back-to-front by world Y.
4472
+ * @param onLayerCreated - Called with each new Lite layer, so the sprite renderer can draw it.
4473
+ * @param onLayerRemoved - Called before a layer is dropped.
4474
+ */
4475
+ constructor(sortingLayers, ySort, onLayerCreated, onLayerRemoved) {
4476
+ this.#sortingLayers = sortingLayers;
4477
+ this.#ySort = ySort;
4478
+ this.#onLayerCreated = onLayerCreated;
4479
+ this.#onLayerRemoved = onLayerRemoved;
4480
+ }
4481
+ /**
4482
+ * Installs the source of per-sorting-layer custom shaders.
4483
+ *
4484
+ * @remarks
4485
+ * `Sprite2DLayer.customShader` is `readonly` and is only read at creation, so a
4486
+ * `SpriteLayerEffect` has to be discoverable **before** the first sprite on its sorting layer is
4487
+ * placed. That is why the registry pulls the shader rather than the effect pushing it.
4488
+ *
4489
+ * @param provider - Returns the compiled shader for a sorting layer, or `null`.
4490
+ *
4491
+ * @internal
4492
+ */
4493
+ setShaderProvider(provider) {
4494
+ this.#shaderFor = provider;
4495
+ }
4496
+ /**
4497
+ * Writes a sorting layer's `fx.params` vec4 onto every layer belonging to it.
4498
+ *
4499
+ * @param sortingLayer - The sorting layer's name.
4500
+ * @param params - The four components.
4501
+ *
4502
+ * @internal
4503
+ */
4504
+ writeShaderParams(sortingLayer, params) {
4505
+ for (let index = 0; index < this.#ordered.length; index += 1) {
4506
+ const record = this.#ordered[index];
4507
+ if (record !== void 0 && record.sortingLayer === sortingLayer) setShaderParams(record.layer, params[0] ?? 0, params[1] ?? 0, params[2] ?? 0, params[3] ?? 0);
4508
+ }
4509
+ }
4510
+ /**
4511
+ * Every layer, in draw order.
4512
+ *
4513
+ * @returns A freshly allocated snapshot, for diagnostics.
4514
+ */
4515
+ describe() {
4516
+ const out = [];
4517
+ for (let index = 0; index < this.#ordered.length; index += 1) {
4518
+ const record = this.#ordered[index];
4519
+ if (record !== void 0) out.push({
4520
+ key: record.key,
4521
+ sortingLayer: record.sortingLayer,
4522
+ layer: record.layer,
4523
+ screenSpace: record.screenSpace,
4524
+ count: record.layer.count,
4525
+ ySort: record.ySort
4526
+ });
4527
+ }
4528
+ return out;
4529
+ }
4530
+ /**
4531
+ * The Lite layers, in draw order — what picking tests against.
4532
+ *
4533
+ * @param worldOnly - Whether to skip screen-space layers.
4534
+ * @param out - The array to fill; it is emptied first, so one array serves every frame.
4535
+ * @returns `out`.
4536
+ */
4537
+ collectLayers(worldOnly, out) {
4538
+ out.length = 0;
4539
+ for (let index = 0; index < this.#ordered.length; index += 1) {
4540
+ const record = this.#ordered[index];
4541
+ if (record !== void 0 && !(worldOnly && record.screenSpace)) out.push(record.layer);
4542
+ }
4543
+ return out;
4544
+ }
4545
+ /**
4546
+ * Walks every layer's view, so the camera can write world layers and skip screen-space ones.
4547
+ *
4548
+ * @param visit - Called with each layer and whether it follows the camera.
4549
+ *
4550
+ * @internal
4551
+ */
4552
+ forEachLayer(visit) {
4553
+ for (let index = 0; index < this.#ordered.length; index += 1) {
4554
+ const record = this.#ordered[index];
4555
+ if (record !== void 0) visit(record.layer, record.screenSpace);
4556
+ }
4557
+ }
4558
+ /**
4559
+ * Adds a sprite to the layer its key selects, creating the layer when it is the first of its kind.
4560
+ *
4561
+ * @param component - The sprite component.
4562
+ * @param atlas - Its loaded atlas.
4563
+ * @param scratch - The reusable props record, already written.
4564
+ * @returns The key of the layer the sprite landed in.
4565
+ *
4566
+ * @internal
4567
+ */
4568
+ place(component, atlas, scratch) {
4569
+ const key = spriteLayerKey(component.sortingLayer, atlas.address, component.blend, component.screenSpace);
4570
+ const record = this.#ensure(key, component.sortingLayer, component.blend, component.screenSpace, atlas);
4571
+ const handle = addSprite(record.layer, scratch);
4572
+ const index = spriteIndexOf(handle);
4573
+ if (index >= 0) record.components[index] = component;
4574
+ component.setPlacement(handle, key);
4575
+ return key;
4576
+ }
4577
+ /**
4578
+ * Removes a sprite from whichever layer holds it.
4579
+ *
4580
+ * @param component - The sprite component.
4581
+ *
4582
+ * @internal
4583
+ */
4584
+ remove(component) {
4585
+ const placement = component.placement();
4586
+ if (placement === null) return;
4587
+ const record = this.#records.get(placement.key);
4588
+ const index = spriteIndexOf(placement.handle);
4589
+ if (record !== void 0 && index >= 0) {
4590
+ const last = record.components.length - 1;
4591
+ record.components[index] = record.components[last] ?? null;
4592
+ record.components.length = Math.max(0, last);
4593
+ }
4594
+ removeSprite(placement.handle);
4595
+ component.setPlacement(null, null);
4596
+ }
4597
+ /**
4598
+ * Adds a sprite that no `SpriteRenderer` owns — a tilemap's tiles.
4599
+ *
4600
+ * @remarks
4601
+ * The sprite occupies a slot in the same layers component-owned sprites use, so it sorts and
4602
+ * Y-sorts alongside them, but its slot in the pick map stays empty: `app.twoD.pickAt` resolves
4603
+ * `SpriteRenderer` components, and a tile is not one. Pick a tile with `Tilemap.worldToCell`
4604
+ * instead, which is exact and costs no draw-order search.
4605
+ *
4606
+ * @param sortingLayer - The sorting layer's name.
4607
+ * @param atlas - The atlas the sprite draws from.
4608
+ * @param blend - The blend mode.
4609
+ * @param screenSpace - Whether the layer ignores the camera.
4610
+ * @param scratch - The reusable props record, already written.
4611
+ * @returns The key and the handle.
4612
+ *
4613
+ * @internal
4614
+ */
4615
+ placeRaw(sortingLayer, atlas, blend, screenSpace, scratch) {
4616
+ const key = spriteLayerKey(sortingLayer, atlas.address, blend, screenSpace);
4617
+ const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas);
4618
+ const handle = addSprite(record.layer, scratch);
4619
+ const index = spriteIndexOf(handle);
4620
+ if (index >= 0) record.components[index] = null;
4621
+ return {
4622
+ key,
4623
+ handle
4624
+ };
4625
+ }
4626
+ /**
4627
+ * Removes a sprite added by {@link SpriteLayerRegistry.placeRaw}.
4628
+ *
4629
+ * @param key - The key the sprite was placed under.
4630
+ * @param handle - The handle.
4631
+ *
4632
+ * @internal
4633
+ */
4634
+ removeRaw(key, handle) {
4635
+ const record = this.#records.get(key);
4636
+ const index = spriteIndexOf(handle);
4637
+ if (record !== void 0 && index >= 0) {
4638
+ const last = record.components.length - 1;
4639
+ record.components[index] = record.components[last] ?? null;
4640
+ record.components.length = Math.max(0, last);
4641
+ }
4642
+ removeSprite(handle);
4643
+ }
4644
+ /**
4645
+ * Applies a sprite's `orderInLayer` to the layer holding it.
4646
+ *
4647
+ * @remarks
4648
+ * Lite's Y-sort bias setter **throws** on a layer that has no Y-sort state
4649
+ * (`lib/sprite/sprite-2d-y-sort.js`, `setSprite2DYSortBias`), so the bias is only written to a
4650
+ * layer that is actually sorting. On a layer that is not, `orderInLayer` falls back to ordering
4651
+ * by insertion, which is exactly what `docs/architecture/11-2d-toolkit.md` §1 specifies:
4652
+ * "applied as a Y-sort bias when Y-sort is on, or as sub-ordering by insertion when off"*.
4653
+ *
4654
+ * @param key - The key of the layer holding the sprite.
4655
+ * @param handle - The sprite.
4656
+ * @param orderInLayer - The component's `orderInLayer`.
4657
+ *
4658
+ * @internal
4659
+ */
4660
+ applyOrderInLayer(key, handle, orderInLayer) {
4661
+ if (this.#records.get(key)?.ySort === true) setYSortOrder(handle, orderInLayer);
4662
+ }
4663
+ /**
4664
+ * Resolves a pick hit back to the component that owns the sprite.
4665
+ *
4666
+ * @param layer - The Lite layer the hit is in.
4667
+ * @param spriteIndex - The dense index the hit reports.
4668
+ * @returns The component, or `null` when the slot is unmapped.
4669
+ *
4670
+ * @internal
4671
+ */
4672
+ componentAt(layer, spriteIndex) {
4673
+ for (let index = 0; index < this.#ordered.length; index += 1) {
4674
+ const record = this.#ordered[index];
4675
+ if (record?.layer === layer) return record.components[spriteIndex] ?? null;
4676
+ }
4677
+ return null;
4678
+ }
4008
4679
  /**
4009
- * Wraps a parsed document. The `tilemap` loader constructs these.
4010
- *
4011
- * @param address - The address it was loaded from.
4012
- * @param definition - The parsed document.
4680
+ * Empties every layer and drops them all.
4013
4681
  *
4014
4682
  * @internal
4015
4683
  */
4016
- constructor(address, definition) {
4017
- this.address = address;
4018
- this.definition = definition;
4019
- const atlases = [];
4020
- for (let index = 0; index < definition.tilesets.length; index += 1) {
4021
- const tileset = definition.tilesets[index];
4022
- atlases.push(tileset === void 0 ? "" : resolveRelative(address, tileset.atlas));
4684
+ clear() {
4685
+ for (let index = 0; index < this.#ordered.length; index += 1) {
4686
+ const record = this.#ordered[index];
4687
+ if (record !== void 0) {
4688
+ clearLayer(record.layer);
4689
+ this.#onLayerRemoved(record.layer);
4690
+ }
4023
4691
  }
4024
- this.atlasAddresses = atlases;
4692
+ this.#records.clear();
4693
+ this.#ordered = [];
4025
4694
  }
4026
4695
  /**
4027
- * The atlas address a tileset's tiles come from.
4696
+ * Finds or creates the layer a key names.
4028
4697
  *
4029
- * @param tilesetIndex - The tileset's index in the document.
4030
- * @returns The address, or `""` when the index is out of range.
4698
+ * @param key - The composite key.
4699
+ * @param sortingLayer - The sorting layer's name.
4700
+ * @param blend - The blend mode the layer draws with.
4701
+ * @param screenSpace - Whether the layer ignores the camera.
4702
+ * @param atlas - The atlas to bind the layer to.
4703
+ * @returns The record.
4031
4704
  */
4032
- atlasFor(tilesetIndex) {
4033
- return this.atlasAddresses[tilesetIndex] ?? "";
4705
+ #ensure(key, sortingLayer, blend, screenSpace, atlas) {
4706
+ const existing = this.#records.get(key);
4707
+ if (existing !== void 0) return existing;
4708
+ const liteAtlas = atlas.lite.atlas;
4709
+ if (liteAtlas === null) throw new Error("a sprite layer needs an uploaded atlas; this app is headless");
4710
+ const layer = createLayer(liteAtlas, {
4711
+ blend,
4712
+ order: this.#sortingLayers.orderOf(sortingLayer) + this.#countIn(sortingLayer),
4713
+ capacity: INITIAL_LAYER_CAPACITY,
4714
+ customShader: this.#shaderFor(sortingLayer)
4715
+ });
4716
+ const ySort = !screenSpace && this.#ySort[sortingLayer] === true;
4717
+ if (ySort) setYSort(layer, true);
4718
+ const record = {
4719
+ key,
4720
+ sortingLayer,
4721
+ layer,
4722
+ screenSpace,
4723
+ ySort,
4724
+ components: []
4725
+ };
4726
+ this.#records.set(key, record);
4727
+ this.#ordered.push(record);
4728
+ this.#ordered.sort(byOrder);
4729
+ this.#onLayerCreated(layer);
4730
+ return record;
4731
+ }
4732
+ /**
4733
+ * How many layers a sorting layer already has, so the next one gets the next sub-order.
4734
+ *
4735
+ * @param sortingLayer - The sorting layer's name.
4736
+ * @returns The count.
4737
+ */
4738
+ #countIn(sortingLayer) {
4739
+ let count = 0;
4740
+ for (const record of this.#records.values()) if (record.sortingLayer === sortingLayer) count += 1;
4741
+ return count;
4034
4742
  }
4035
4743
  };
4036
4744
  /**
4037
- * Builds the loader for `.tilemap.json` addresses.
4038
- *
4039
- * @returns The loader to register with `ctx.registerAssetLoader`.
4040
- *
4041
- * @example
4042
- * ```ts
4043
- * ctx.registerAssetLoader(createTilemapLoader());
4044
- * ```
4745
+ * Orders two layer records by their Lite draw order.
4045
4746
  *
4046
- * @public
4747
+ * @param left - One record.
4748
+ * @param right - The other.
4749
+ * @returns The comparison.
4047
4750
  */
4048
- function createTilemapLoader() {
4049
- return {
4050
- type: TILEMAP_ASSET_TYPE,
4051
- extensions: TILEMAP_FILE_EXTENSIONS,
4052
- async load(ctx) {
4053
- const raw = await ctx.fetchJson();
4054
- return new TilemapAsset(ctx.address, defineTilemap(raw, ctx.address));
4055
- }
4056
- };
4751
+ function byOrder(left, right) {
4752
+ return left.layer.order - right.layer.order;
4057
4753
  }
4058
4754
  //#endregion
4059
- //#region src/tilemap/tilemap.ts
4755
+ //#region src/service/runtime.ts
4060
4756
  /**
4061
- * A tilemap.
4062
- *
4063
- * @example
4064
- * ```ts
4065
- * const level = app.world.createEntity({ name: "level" }).addComponent(Tilemap);
4066
- * level.map = app.assets.load<TilemapAsset>("2d/level-1.tilemap.json").retain();
4067
- * level.setTile(0, 3, 2, 0); // carve a hole in the ground layer
4068
- * ```
4757
+ * One app's 2D runtime state.
4069
4758
  *
4070
- * @public
4759
+ * @internal
4071
4760
  */
4072
- var Tilemap = class Tilemap extends Component {
4073
- /** The registration id the serializer writes into scene files. */
4074
- static typeId = "ignifx/Tilemap";
4075
- /** One tilemap per entity. */
4076
- static allowMultiple = false;
4077
- /** The declarative fields (ADR-0004). */
4078
- static schema = tilemapSchema();
4079
- /** The mutable tile grids, bottom row first, one per document layer. */
4080
- #grids = [];
4081
- /** The document the grids were built from, so a swapped asset rebuilds them. */
4082
- #built = null;
4083
- /** The merged collision surface, rebuilt lazily after a change. */
4084
- #collision = EMPTY_COLLISION;
4085
- /** Whether the collision surface needs rebuilding. */
4086
- #collisionDirty = true;
4087
- /** Bumped on every collision rebuild, so a physics backend can skip unchanged frames. */
4088
- #version = 0;
4089
- #onTileChanged = new Signal();
4090
- #onCollisionChanged = new Signal();
4091
- /**
4092
- * Builds a tilemap with the schema's defaults.
4093
- */
4094
- constructor() {
4095
- super();
4096
- Object.assign(this, createDefaults(Tilemap.schema));
4097
- }
4098
- /**
4099
- * Drops the grids, so a recycled component does not inherit the previous one's.
4100
- */
4101
- onAttach() {
4102
- this.#grids = [];
4103
- this.#built = null;
4104
- this.#collision = EMPTY_COLLISION;
4105
- this.#collisionDirty = true;
4106
- }
4761
+ var TwoDRuntime = class {
4762
+ #app;
4763
+ #settings;
4764
+ #sortingLayers;
4765
+ #registry;
4766
+ #options;
4767
+ #renderer = null;
4768
+ #hasTriedRenderer = false;
4769
+ #camera = null;
4770
+ #parallax = [];
4771
+ #syncedThisFrame = 0;
4772
+ #spriteCount = 0;
4773
+ /** Reused by {@link TwoDRuntime.cameraBounds}. */
4774
+ #bounds = {
4775
+ minX: 0,
4776
+ minY: 0,
4777
+ maxX: 0,
4778
+ maxY: 0
4779
+ };
4780
+ /** Reused when collecting layers for a bounds read. */
4781
+ #boundsLayers = [];
4782
+ /** The effects seen this frame, by sorting layer. */
4783
+ #effects = /* @__PURE__ */ new Map();
4784
+ /** Compiled shaders, cached by WGSL body so one source compiles once. */
4785
+ #shaders = /* @__PURE__ */ new Map();
4786
+ /** Reused by {@link TwoDRuntime.writeEffectParams}. */
4787
+ #params = /* @__PURE__ */ new Float32Array(4);
4788
+ /** Applies a scene file's `settings.twoD` block and spawns its tile objects. */
4789
+ #onSceneLoaded = null;
4790
+ /** Detaches the scene hook when the world goes away. */
4791
+ #disconnectScene = null;
4107
4792
  /**
4108
- * Releases the grids.
4793
+ * Builds the runtime.
4794
+ *
4795
+ * @param options - The app, the settings, the sorting layers, and the Lite hooks.
4109
4796
  */
4110
- onDetach() {
4111
- this.#grids = [];
4112
- this.#built = null;
4797
+ constructor(options) {
4798
+ this.#app = options.app;
4799
+ this.#settings = options.settings;
4800
+ this.#options = options;
4801
+ this.#sortingLayers = new SortingLayerTable(options.sortingLayers);
4802
+ this.#registry = new SpriteLayerRegistry(this.#sortingLayers, options.settings.ySort, (layer) => {
4803
+ const renderer = this.#renderer;
4804
+ if (renderer !== null) options.attachLayer(renderer, layer);
4805
+ }, (layer) => {
4806
+ const renderer = this.#renderer;
4807
+ if (renderer !== null) options.detachLayer(renderer, layer);
4808
+ });
4809
+ this.#registry.setShaderProvider((sortingLayer) => this.#shaderFor(sortingLayer));
4113
4810
  }
4114
4811
  /**
4115
- * Emitted whenever `setTile` changes a cell.
4812
+ * The resolved settings.
4116
4813
  *
4117
- * @returns The signal.
4814
+ * @returns The `twoD` settings, after any scene-file override.
4118
4815
  */
4119
- get onTileChanged() {
4120
- return this.#onTileChanged;
4816
+ get settings() {
4817
+ return this.#settings;
4121
4818
  }
4122
4819
  /**
4123
- * Emitted after the merged collision surface has been rebuilt.
4124
- *
4125
- * @remarks
4126
- * `@ignifx/physics-2d` connects to this and rebuilds only the chunks whose geometry moved. The
4127
- * rebuild is lazy: the signal fires on the first read of {@link Tilemap.collisionData} after a
4128
- * change, not on the `setTile` call itself, so a script that rewrites a thousand tiles in one
4129
- * frame pays for one merge.
4820
+ * How many pixels one world metre spans.
4130
4821
  *
4131
- * @returns The signal.
4822
+ * @returns The conversion factor.
4132
4823
  */
4133
- get onCollisionChanged() {
4134
- return this.#onCollisionChanged;
4824
+ get pixelsPerUnit() {
4825
+ return this.#settings.pixelsPerUnit;
4135
4826
  }
4136
4827
  /**
4137
- * The loaded document, or `null` while it is still loading.
4828
+ * The sorting-layer resolver.
4138
4829
  *
4139
- * @returns The asset.
4830
+ * @returns The table.
4140
4831
  */
4141
- get asset() {
4142
- const handle = this.map;
4143
- return handle?.state === "loaded" ? handle.value : null;
4832
+ get sortingLayers() {
4833
+ return this.#sortingLayers;
4144
4834
  }
4145
4835
  /**
4146
- * The parsed document, or `null`.
4836
+ * The layer pool.
4147
4837
  *
4148
- * @returns The definition.
4838
+ * @returns The registry.
4149
4839
  */
4150
- get definition() {
4151
- return this.asset?.definition ?? null;
4840
+ get layers() {
4841
+ return this.#registry;
4152
4842
  }
4153
4843
  /**
4154
- * How many metres one cell spans.
4844
+ * The Lite sprite renderer, or `null`.
4155
4845
  *
4156
- * @returns The cell size; `0` when nothing has loaded.
4846
+ * @returns The renderer, or `null` under a headless app or before the first frame.
4157
4847
  */
4158
- get cellSize() {
4159
- if (this.cellSizeOverride > 0) return this.cellSizeOverride;
4160
- return this.definition?.cellSize ?? 0;
4848
+ get renderer() {
4849
+ return this.#renderer;
4161
4850
  }
4162
4851
  /**
4163
- * How many layers the document has.
4852
+ * The camera the last frame drew through, or `null`.
4164
4853
  *
4165
- * @returns The layer count.
4854
+ * @returns The camera.
4166
4855
  */
4167
- get layerCount() {
4168
- return this.definition?.layers.length ?? 0;
4856
+ get mainCamera() {
4857
+ return this.#camera;
4169
4858
  }
4170
4859
  /**
4171
- * The merged collision surface, rebuilt if a tile changed since the last read.
4172
- *
4173
- * @remarks
4174
- * The shape is the contract `@ignifx/physics-2d` consumes: chunked, in world metres relative to
4175
- * the tilemap entity's origin, with adjacent full-cell tiles merged into as few counter-clockwise
4176
- * rectangles as possible.
4860
+ * How many sprites the last frame actually wrote to Lite.
4177
4861
  *
4178
- * @returns The collision data.
4862
+ * @returns The count.
4179
4863
  */
4180
- get collisionData() {
4181
- if (this.#collisionDirty) this.#rebuildCollision();
4182
- return this.#collision;
4864
+ get syncedLastFrame() {
4865
+ return this.#syncedThisFrame;
4183
4866
  }
4184
4867
  /**
4185
- * Reads a tile.
4186
- *
4187
- * @param layer - The layer's index in the document.
4188
- * @param x - The cell's column, with `0` at the left.
4189
- * @param y - The cell's row, with `0` at the bottom.
4190
- * @returns The tile id, or `0` for an empty or out-of-range cell.
4191
- */
4192
- getTile(layer, x, y) {
4193
- this.#ensureGrids();
4194
- const definition = this.definition;
4195
- const grid = this.#grids[layer];
4196
- const declared = definition?.layers[layer];
4197
- if (grid === void 0 || declared === void 0 || !inRange(x, y, declared.width, declared.height)) return 0;
4198
- return grid[y * declared.width + x] ?? 0;
4868
+ * How many `SpriteRenderer` components the last frame walked.
4869
+ *
4870
+ * @returns The count.
4871
+ */
4872
+ get spriteCount() {
4873
+ return this.#spriteCount;
4199
4874
  }
4200
4875
  /**
4201
- * Writes a tile.
4876
+ * The surface width the views are sized against, in pixels.
4202
4877
  *
4203
- * @param layer - The layer's index in the document.
4204
- * @param x - The cell's column, with `0` at the left.
4205
- * @param y - The cell's row, with `0` at the bottom.
4206
- * @param tileId - The tile id, or `0` to clear the cell.
4207
- * @throws IgnifxError with code `IGX-1111` when the cell is outside the layer.
4878
+ * @returns The width; `0` under a headless app.
4208
4879
  */
4209
- setTile(layer, x, y, tileId) {
4210
- this.#ensureGrids();
4211
- const definition = this.definition;
4212
- const grid = this.#grids[layer];
4213
- const declared = definition?.layers[layer];
4214
- if (grid === void 0 || declared === void 0 || !inRange(x, y, declared.width, declared.height)) throw twoDError(TwoDErrorCode.tileOutOfRange, `Cell ${String(x)},${String(y)} is outside layer ${String(layer)}.`, {
4215
- context: {
4216
- x,
4217
- y,
4218
- layer
4219
- },
4220
- hint: "Check the cell against Tilemap.layerSize; cell (0, 0) is the bottom-left."
4221
- });
4222
- const offset = y * declared.width + x;
4223
- const previous = grid[offset] ?? 0;
4224
- if (previous === tileId) return;
4225
- grid[offset] = tileId;
4226
- if (declared.collision) this.#collisionDirty = true;
4227
- this.#onTileChanged.emit({
4228
- layer,
4229
- x,
4230
- y,
4231
- previous,
4232
- current: tileId
4233
- });
4880
+ get viewportWidthPx() {
4881
+ const surface = this.#app.renderer.surface;
4882
+ return surface === null ? 0 : surface.width;
4234
4883
  }
4235
4884
  /**
4236
- * A layer's size, in cells.
4885
+ * The surface height the views are sized against, in pixels.
4237
4886
  *
4238
- * @param layer - The layer's index.
4239
- * @returns The size, or a zero size for an unknown layer.
4887
+ * @returns The height; `0` under a headless app.
4240
4888
  */
4241
- layerSize(layer) {
4242
- const declared = this.definition?.layers[layer];
4243
- return declared === void 0 ? ZERO : {
4244
- x: declared.width,
4245
- y: declared.height
4246
- };
4889
+ get viewportHeightPx() {
4890
+ const surface = this.#app.renderer.surface;
4891
+ return surface === null ? 0 : surface.height;
4247
4892
  }
4248
4893
  /**
4249
- * Converts a world point into the cell containing it.
4894
+ * Installs the callback that reacts to a scene load.
4250
4895
  *
4251
4896
  * @remarks
4252
- * The point is in world metres; the map's own origin is the tilemap entity's position, so a moved
4253
- * or scaled tilemap still answers correctly. The result is floored, so a point exactly on a cell
4254
- * boundary belongs to the cell above and to the right of it.
4897
+ * The extension cannot connect `world.onSceneLoaded` itself: `register` runs before the world
4898
+ * exists, and `onStart` runs only when a game calls `app.start()` — which a headless tool or a
4899
+ * test may never do. `System.onWorldCreated` is the one hook that fires for every world, started
4900
+ * or not, so the sync system routes it here.
4255
4901
  *
4256
- * @param point - The world point, in metres.
4257
- * @param out - The vector to write.
4258
- * @returns `out`, holding integer cell coordinates that may be outside the map.
4902
+ * @param handler - What to run for each loaded scene.
4259
4903
  */
4260
- worldToCell(point, out) {
4261
- const size = this.cellSize;
4262
- const matrix = this.entity.transform.worldMatrix;
4263
- const originX = matrix[12] ?? 0;
4264
- const originY = matrix[13] ?? 0;
4265
- if (size <= 0) {
4266
- out.x = 0;
4267
- out.y = 0;
4268
- return out;
4269
- }
4270
- out.x = Math.floor((point.x - originX) / size);
4271
- out.y = Math.floor((point.y - originY) / size);
4272
- return out;
4904
+ setSceneHandler(handler) {
4905
+ this.#onSceneLoaded = handler;
4273
4906
  }
4274
4907
  /**
4275
- * Converts a cell into the world point at its **centre**.
4908
+ * Connects the scene hook to a world.
4276
4909
  *
4277
- * @param x - The cell's column.
4278
- * @param y - The cell's row, with `0` at the bottom.
4279
- * @param out - The vector to write.
4280
- * @returns `out`, in world metres.
4910
+ * @param world - The world that was just created.
4281
4911
  */
4282
- cellToWorld(x, y, out) {
4283
- const size = this.cellSize;
4284
- const matrix = this.entity.transform.worldMatrix;
4285
- out.x = (matrix[12] ?? 0) + (x + .5) * size;
4286
- out.y = (matrix[13] ?? 0) + (y + .5) * size;
4287
- return out;
4912
+ attachWorld(world) {
4913
+ this.#disconnectScene?.();
4914
+ this.#disconnectScene = world.onSceneLoaded.connect((scene) => {
4915
+ this.#onSceneLoaded?.(scene);
4916
+ });
4288
4917
  }
4289
4918
  /**
4290
- * The collision footprint of whatever is at a cell, across every collision layer.
4919
+ * Disconnects the scene hook.
4920
+ */
4921
+ detachWorld() {
4922
+ this.#disconnectScene?.();
4923
+ this.#disconnectScene = null;
4924
+ }
4925
+ /**
4926
+ * Replaces the settings, which a scene file's `settings.twoD` block does at load time.
4291
4927
  *
4292
- * @param x - The cell's column.
4293
- * @param y - The cell's row, with `0` at the bottom.
4294
- * @returns The topmost non-empty collider, or a `"none"` shape.
4928
+ * @param settings - The new settings.
4295
4929
  */
4296
- collisionAt(x, y) {
4297
- const definition = this.definition;
4298
- if (definition === null) return NO_COLLISION;
4299
- for (let layer = definition.layers.length - 1; layer >= 0; layer -= 1) {
4300
- const declared = definition.layers[layer];
4301
- if (declared === void 0 || !declared.collision) continue;
4302
- const info = tileCollisionInfo(definition, this.getTile(layer, x, y));
4303
- if (info.shape.kind !== "none") return info;
4304
- }
4305
- return NO_COLLISION;
4930
+ applySettings(settings) {
4931
+ this.#settings = settings;
4306
4932
  }
4307
4933
  /**
4308
- * Forces the collision surface to be rebuilt on the next read.
4934
+ * Records the frame's camera.
4309
4935
  *
4310
- * @internal
4936
+ * @param camera - The camera, or `null`.
4311
4937
  */
4312
- invalidateCollision() {
4313
- this.#collisionDirty = true;
4938
+ setMainCamera(camera) {
4939
+ this.#camera = camera;
4314
4940
  }
4315
4941
  /**
4316
- * Builds the mutable grids from the document, flipping each layer bottom-row-first.
4942
+ * Records the parallax components the sync system should offset views for.
4943
+ *
4944
+ * @param layers - The components.
4317
4945
  */
4318
- #ensureGrids() {
4319
- const asset = this.asset;
4320
- if (asset === null || asset === this.#built) return;
4321
- this.#built = asset;
4322
- this.#collisionDirty = true;
4323
- const grids = [];
4324
- const layers = asset.definition.layers;
4325
- for (let index = 0; index < layers.length; index += 1) {
4326
- const layer = layers[index];
4327
- if (layer === void 0) {
4328
- grids.push(/* @__PURE__ */ new Int32Array(0));
4329
- continue;
4330
- }
4331
- const grid = new Int32Array(layer.width * layer.height);
4332
- for (let row = 0; row < layer.height; row += 1) {
4333
- const source = (layer.height - 1 - row) * layer.width;
4334
- for (let column = 0; column < layer.width; column += 1) grid[row * layer.width + column] = layer.tiles[source + column] ?? 0;
4335
- }
4336
- grids.push(grid);
4337
- }
4338
- this.#grids = grids;
4946
+ setParallaxLayers(layers) {
4947
+ this.#parallax = layers;
4339
4948
  }
4340
4949
  /**
4341
- * Merges every collision layer's tiles into chunked polygons.
4950
+ * Offsets each parallax layer's view by the camera's motion times `1 - factor`
4951
+ * (`docs/architecture/11-2d-toolkit.md` §2.6).
4342
4952
  */
4343
- #rebuildCollision() {
4344
- this.#ensureGrids();
4345
- this.#collisionDirty = false;
4346
- const definition = this.definition;
4347
- const size = this.cellSize;
4348
- if (definition === null || size <= 0) {
4349
- this.#collision = EMPTY_COLLISION;
4350
- return;
4953
+ applyParallax() {
4954
+ const camera = this.#camera;
4955
+ if (camera === null || this.#parallax.length === 0) return;
4956
+ const entries = this.#registry.describe();
4957
+ for (let index = 0; index < this.#parallax.length; index += 1) {
4958
+ const layer = this.#parallax[index];
4959
+ if (layer === void 0 || !layer.isEnabledInHierarchy) continue;
4960
+ layer.applyTo(entries, camera, this.#settings.pixelsPerUnit);
4351
4961
  }
4352
- this.#version += 1;
4353
- this.#collision = mergeTileCollisions((x, y) => this.collisionAt(x, y), {
4354
- cellSize: size,
4355
- chunkSize: Math.max(1, this.chunkSize),
4356
- width: definition.width,
4357
- height: definition.height
4358
- }, this.#version);
4359
- this.#onCollisionChanged.emit();
4360
4962
  }
4361
- };
4362
- /** The cell size a tilemap with nothing loaded reports. */
4363
- const ZERO = Object.freeze({
4364
- x: 0,
4365
- y: 0
4366
- });
4367
- /** The collision surface of a tilemap with nothing loaded. */
4368
- const EMPTY_COLLISION = Object.freeze({
4369
- cellSize: 0,
4370
- chunkSize: 0,
4371
- chunks: Object.freeze([]),
4372
- version: 0
4373
- });
4374
- /** The answer for a cell that carries no collider. */
4375
- const NO_COLLISION = Object.freeze({
4376
- shape: Object.freeze({ kind: "none" }),
4377
- oneWay: false,
4378
- properties: Object.freeze({})
4379
- });
4380
- /** How many cells one chunk spans by default (`docs/architecture/11-2d-toolkit.md` §2.5). */
4381
- const DEFAULT_CHUNK_SIZE = 32;
4382
- /**
4383
- * Whether a cell is inside a layer.
4384
- *
4385
- * @param x - The column.
4386
- * @param y - The row.
4387
- * @param width - The layer width, in cells.
4388
- * @param height - The layer height, in cells.
4389
- * @returns `true` when the cell exists.
4390
- */
4391
- function inRange(x, y, width, height) {
4392
- return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < width && y < height;
4393
- }
4394
- /**
4395
- * The `Tilemap` schema.
4396
- *
4397
- * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
4398
- */
4399
- function tilemapSchema() {
4400
- return defineSchema({
4401
- map: asset(TilemapAsset, { tooltip: "The .tilemap.json document." }),
4402
- chunkSize: u32(32, {
4403
- min: 1,
4404
- tooltip: "How many cells one render and collision chunk spans."
4405
- }),
4406
- cellSizeOverride: f32(0, {
4407
- min: 0,
4408
- tooltip: "Metres per cell, overriding the document's own; 0 uses it."
4409
- })
4410
- });
4411
- }
4412
- //#endregion
4413
- //#region src/tilemap/tilemap-renderer.ts
4414
- /**
4415
- * A tilemap renderer.
4416
- *
4417
- * @example
4418
- * ```ts
4419
- * const level = app.world.createEntity({ name: "level" });
4420
- * level.addComponent(Tilemap).map = app.assets.load<TilemapAsset>("2d/level-1.tilemap.json").retain();
4421
- * const renderer = level.addComponent(TilemapRenderer);
4422
- * renderer.atlas = app.assets.load<SpriteAtlasAsset>("2d/tiles.atlas.json").retain();
4423
- * ```
4424
- *
4425
- * @public
4426
- */
4427
- var TilemapRenderer = class TilemapRenderer extends Component {
4428
- /** The registration id the serializer writes into scene files. */
4429
- static typeId = "ignifx/TilemapRenderer";
4430
- /** One renderer per entity. */
4431
- static allowMultiple = false;
4432
- /** The declarative fields (ADR-0004). */
4433
- static schema = tilemapRendererSchema();
4434
- /** Chunks currently materialised, keyed by `` `${chunkX},${chunkY}` ``. */
4435
- #chunks = /* @__PURE__ */ new Map();
4436
- /** The reusable props record, so building a chunk allocates one object rather than 1024. */
4437
- #scratch = createSpriteScratch();
4438
- /** Scratch, so the per-chunk arithmetic allocates nothing. */
4439
- #pixels = new Vec2();
4440
- /** How far animated tiles have advanced, in seconds. */
4441
- #animationClock = 0;
4442
- /** Whether every chunk must be rebuilt, because the map or the atlas changed. */
4443
- #isStale = true;
4444
4963
  /**
4445
- * Builds a renderer with the schema's defaults.
4446
- */
4447
- constructor() {
4448
- super();
4449
- Object.assign(this, createDefaults(TilemapRenderer.schema));
4964
+ * The layer-pixel rectangle the camera can currently see, for chunk culling.
4965
+ *
4966
+ * @remarks
4967
+ * Read off the first world layer's view, which the sync system has already written this frame.
4968
+ * Every world layer carries the same view, so any of them answers; `null` means there is no world
4969
+ * layer yet, in which case a tilemap builds every chunk and culls from the next frame on.
4970
+ *
4971
+ * @returns The bounds, or `null`.
4972
+ */
4973
+ cameraBounds() {
4974
+ const first = this.#registry.collectLayers(true, this.#boundsLayers)[0];
4975
+ if (first === void 0 || this.viewportWidthPx === 0) return null;
4976
+ return visibleBounds(first.view, this.viewportWidthPx, this.viewportHeightPx, this.#bounds);
4450
4977
  }
4451
4978
  /**
4452
- * Marks every chunk stale, so a recycled component rebuilds.
4979
+ * Advances every animated tile on the 2D animation clock.
4980
+ *
4981
+ * @remarks
4982
+ * Implements `AnimatedTilemapSink`, which is what lets the animation system drive tilemaps
4983
+ * without importing the renderer.
4984
+ *
4985
+ * @param world - The world holding the tilemaps.
4986
+ * @param deltaSeconds - The scaled frame delta.
4453
4987
  */
4454
- onAttach() {
4455
- this.#isStale = true;
4988
+ advanceAnimatedTiles(world, deltaSeconds) {
4989
+ const renderers = world.components(TilemapRenderer);
4990
+ for (let index = 0; index < renderers.length; index += 1) {
4991
+ const renderer = renderers[index];
4992
+ if (renderer !== void 0 && renderer.isEnabledInHierarchy && renderer.advanceAnimation(deltaSeconds)) renderer.invalidate();
4993
+ }
4456
4994
  }
4457
4995
  /**
4458
- * Marks every chunk stale; the 2D sync system does the removal, because it owns the layers.
4996
+ * Records the enabled `SpriteLayerEffect` of each sorting layer, so the registry can reach one
4997
+ * when it creates a layer.
4998
+ *
4999
+ * @param world - The world to walk.
4459
5000
  */
4460
- onDetach() {
4461
- this.#isStale = true;
5001
+ collectEffects(world) {
5002
+ const effects = world.components(SpriteLayerEffect);
5003
+ this.#effects.clear();
5004
+ for (let index = 0; index < effects.length; index += 1) {
5005
+ const effect = effects[index];
5006
+ if (effect !== void 0 && effect.isEnabledInHierarchy) this.#effects.set(effect.sortingLayer, effect);
5007
+ }
5008
+ const parallax = [];
5009
+ const layers = world.components(ParallaxLayer);
5010
+ for (let index = 0; index < layers.length; index += 1) {
5011
+ const layer = layers[index];
5012
+ if (layer !== void 0) parallax.push(layer);
5013
+ }
5014
+ this.setParallaxLayers(parallax);
4462
5015
  }
4463
5016
  /**
4464
- * How many chunks are currently materialised.
4465
- *
4466
- * @returns The count.
5017
+ * Writes every effect's `fx.params` vec4 onto its sorting layer's Lite layers.
4467
5018
  */
4468
- get chunkCount() {
4469
- return this.#chunks.size;
5019
+ writeEffectParams() {
5020
+ for (const [sortingLayer, effect] of this.#effects) {
5021
+ effect.writeParams(this.#params);
5022
+ this.#registry.writeShaderParams(sortingLayer, this.#params);
5023
+ }
4470
5024
  }
4471
5025
  /**
4472
- * How many sprites the materialised chunks hold in total.
5026
+ * The compiled custom shader a sorting layer's Lite layers are created with.
4473
5027
  *
4474
- * @returns The count.
5028
+ * @param sortingLayer - The sorting layer's name.
5029
+ * @returns The shader, or `null` when no effect covers the layer.
4475
5030
  */
4476
- get spriteCount() {
4477
- let total = 0;
4478
- for (const chunk of this.#chunks.values()) total += chunk.sprites.length;
4479
- return total;
5031
+ #shaderFor(sortingLayer) {
5032
+ const effect = this.#effects.get(sortingLayer);
5033
+ if (effect === void 0) return null;
5034
+ const source = effect.source();
5035
+ const cached = this.#shaders.get(source);
5036
+ if (cached !== void 0) return cached;
5037
+ const compiled = compileLayerShader(source);
5038
+ this.#shaders.set(source, compiled);
5039
+ return compiled;
4480
5040
  }
4481
5041
  /**
4482
- * The loaded atlas, or `null`.
5042
+ * Publishes the frame's sync counters.
4483
5043
  *
4484
- * @returns The atlas.
5044
+ * @param synced - How many sprites were written.
5045
+ * @param total - How many sprite components were walked.
4485
5046
  */
4486
- get loadedAtlas() {
4487
- const handle = this.atlas;
4488
- return handle?.state === "loaded" ? handle.value : null;
5047
+ reportSynced(synced, total) {
5048
+ this.#syncedThisFrame = synced;
5049
+ this.#spriteCount = total;
4489
5050
  }
4490
5051
  /**
4491
- * Forces every chunk to be rebuilt on the next sync.
5052
+ * Creates and registers the Lite sprite renderer, once, on the first frame that can.
4492
5053
  *
4493
5054
  * @remarks
4494
- * `Tilemap.onTileChanged` is what normally calls this — a rewritten cell has to reach the sprite
4495
- * that draws it, and rebuilding the chunk is both simpler and, for anything short of a per-frame
4496
- * rewrite, cheaper than tracking one sprite per cell.
4497
- *
4498
- * @internal
5055
+ * Idempotent, and a no-op under a headless app or once a first attempt has failed. See the
5056
+ * module's own remarks for why this cannot happen in `onStart`.
4499
5057
  */
4500
- invalidate() {
4501
- this.#isStale = true;
5058
+ ensureRenderer() {
5059
+ if (this.#hasTriedRenderer || this.#options.createRenderer === null) return;
5060
+ this.#hasTriedRenderer = true;
5061
+ const renderer = this.#options.createRenderer();
5062
+ this.#renderer = renderer;
5063
+ const entries = this.#registry.describe();
5064
+ for (let index = 0; index < entries.length; index += 1) {
5065
+ const entry = entries[index];
5066
+ if (entry !== void 0) this.#options.attachLayer(renderer, entry.layer);
5067
+ }
4502
5068
  }
4503
5069
  /**
4504
- * Brings the materialised chunks in line with the camera's visible bounds.
4505
- *
4506
- * @param map - The tilemap being drawn.
4507
- * @param registry - The layer registry that owns the Lite layers.
4508
- * @param bounds - The camera's visible bounds, in layer pixels, or `null` to build every chunk.
4509
- * @param pixelsPerUnit - The pixels one metre spans.
4510
- * @returns How many sprites were written this call; `0` on a steady frame.
4511
- *
4512
- * @internal
5070
+ * Drops every layer and the renderer.
4513
5071
  */
4514
- sync(map, registry, bounds, pixelsPerUnit) {
4515
- const atlas = this.loadedAtlas;
4516
- const definition = map.definition;
4517
- if (atlas === null || atlas.lite.atlas === null || definition === null) return 0;
4518
- if (this.#isStale) {
4519
- this.#dropAll(registry);
4520
- this.#isStale = false;
5072
+ dispose() {
5073
+ this.detachWorld();
5074
+ this.#registry.clear();
5075
+ const renderer = this.#renderer;
5076
+ this.#renderer = null;
5077
+ if (renderer !== null) this.#options.destroyRenderer(renderer);
5078
+ }
5079
+ };
5080
+ //#endregion
5081
+ //#region src/tilemap/collision-merge.ts
5082
+ /**
5083
+ * Whether a tile's collider fills its whole cell and is not a one-way platform — the only shape the
5084
+ * rectangle merge can absorb.
5085
+ *
5086
+ * @param info - The tile's collision info, in cell-local metres.
5087
+ * @param cellSize - The edge length of one cell, in metres.
5088
+ * @returns Whether the tile is a plain, full-cell solid.
5089
+ *
5090
+ * @example
5091
+ * ```ts
5092
+ * isFullCellSolid({ shape: { kind: "box", x: 0, y: 0, width: 1, height: 1 }, oneWay: false, properties: {} }, 1);
5093
+ * // true
5094
+ * ```
5095
+ *
5096
+ * @public
5097
+ */
5098
+ function isFullCellSolid(info, cellSize) {
5099
+ if (info.oneWay) return false;
5100
+ const shape = info.shape;
5101
+ return shape.kind === "box" && shape.x === 0 && shape.y === 0 && shape.width === cellSize && shape.height === cellSize;
5102
+ }
5103
+ /**
5104
+ * Merges a grid of per-tile collision shapes into chunked, world-space polygons.
5105
+ *
5106
+ * @remarks
5107
+ * **Coordinates.** `infoAt` is called with cell coordinates in which `y = 0` is the **bottom** row,
5108
+ * because the ignifx 2D world is +Y up; a caller reading a `TilemapLayerDefinition`, whose rows run
5109
+ * top-first, indexes it as `(height - 1 - y) * width + x`. Everything this function emits is world
5110
+ * metres relative to the tilemap's origin, so cell `(x, y)` spans
5111
+ * `[x·cellSize, (x+1)·cellSize] × [y·cellSize, (y+1)·cellSize]`.
5112
+ *
5113
+ * **The merge.** Each chunk is handled independently, so a later edit rebuilds one chunk rather than
5114
+ * the map. Inside a chunk, cells that {@link isFullCellSolid} accepts go into a boolean grid and are
5115
+ * merged in two greedy passes: first every row is cut into maximal horizontal runs, then a run
5116
+ * extends upwards for as long as the row above holds a run with exactly the same span, which is
5117
+ * marked consumed. Each surviving block is emitted as one counter-clockwise rectangle. It is the
5118
+ * classic row-then-column greedy mesher: linear in cells plus a small scan per row, and optimal for
5119
+ * rectangles while deliberately not optimal in general — an L-shape comes out as two rectangles, not
5120
+ * one six-vertex polygon, and that is the trade the algorithm makes for being O(n).
5121
+ *
5122
+ * Anything the rectangle pass cannot absorb — a partial box, a slope polygon — is emitted as its own
5123
+ * polygon, translated into world metres. Its winding is already counter-clockwise, because
5124
+ * `tileCollisionInfo` guarantees it.
5125
+ *
5126
+ * **One-way platforms.** A one-way tile contributes no polygon at all; it contributes its collider's
5127
+ * **top edge** to `oneWayEdges`. The winding follows the same rule as a polygon: the solid material
5128
+ * is to the **left** of `from → to`. For a directed edge `d = to − from`, "left" is `d` rotated a
5129
+ * quarter turn counter-clockwise, `(−dy, dx)`. An upward-facing platform is solid *below* its
5130
+ * surface — that is the half you cannot pass through once you have landed — so we need
5131
+ * `(−dy, dx) = (0, −1)`, giving `dy = 0` and `dx = −1`. The edge therefore runs from its **right**
5132
+ * end to its **left** end.
5133
+ *
5134
+ * Chunks that end up with neither a polygon nor a one-way edge are omitted entirely.
5135
+ *
5136
+ * @param infoAt - The per-cell collision info, in cell coordinates with `y = 0` at the bottom.
5137
+ * @param options - The cell size, chunk size, and grid extent.
5138
+ * @param version - The version stamp to carry into the result; callers increment it per rebuild.
5139
+ * @returns The chunked collision data.
5140
+ *
5141
+ * @example
5142
+ * ```ts
5143
+ * const data = mergeTileCollisions((x, y) => tileCollisionInfo(map, tileAt(x, y)), {
5144
+ * cellSize: map.cellSize,
5145
+ * chunkSize: 32,
5146
+ * width: map.width,
5147
+ * height: map.height,
5148
+ * }, 1);
5149
+ * ```
5150
+ *
5151
+ * @public
5152
+ */
5153
+ function mergeTileCollisions(infoAt, options, version) {
5154
+ const { cellSize, chunkSize, width, height } = options;
5155
+ const chunks = [];
5156
+ if (cellSize <= 0 || chunkSize <= 0 || width <= 0 || height <= 0) return {
5157
+ cellSize,
5158
+ chunkSize,
5159
+ chunks,
5160
+ version
5161
+ };
5162
+ const chunksX = Math.ceil(width / chunkSize);
5163
+ const chunksY = Math.ceil(height / chunkSize);
5164
+ for (let chunkY = 0; chunkY < chunksY; chunkY += 1) for (let chunkX = 0; chunkX < chunksX; chunkX += 1) {
5165
+ const chunk = mergeChunk(infoAt, options, chunkX, chunkY);
5166
+ if (chunk !== null) chunks.push(chunk);
5167
+ }
5168
+ return {
5169
+ cellSize,
5170
+ chunkSize,
5171
+ chunks,
5172
+ version
5173
+ };
5174
+ }
5175
+ /**
5176
+ * Merges one chunk of the grid.
5177
+ *
5178
+ * @param infoAt - The per-cell collision info.
5179
+ * @param options - The cell size, chunk size, and grid extent.
5180
+ * @param chunkX - The chunk's column index.
5181
+ * @param chunkY - The chunk's row index.
5182
+ * @returns The chunk, or `null` when it carries no geometry.
5183
+ */
5184
+ function mergeChunk(infoAt, options, chunkX, chunkY) {
5185
+ const { cellSize, chunkSize, width, height } = options;
5186
+ const originX = chunkX * chunkSize;
5187
+ const originY = chunkY * chunkSize;
5188
+ const columns = Math.min(chunkSize, width - originX);
5189
+ const rows = Math.min(chunkSize, height - originY);
5190
+ const polygons = [];
5191
+ const oneWayEdges = [];
5192
+ const solid = new Uint8Array(columns * rows);
5193
+ for (let localY = 0; localY < rows; localY += 1) for (let localX = 0; localX < columns; localX += 1) {
5194
+ const cellX = originX + localX;
5195
+ const cellY = originY + localY;
5196
+ const info = infoAt(cellX, cellY);
5197
+ const shape = info.shape;
5198
+ if (shape.kind === "none") continue;
5199
+ if (info.oneWay) {
5200
+ const edge = topEdge(shape, cellX * cellSize, cellY * cellSize);
5201
+ if (edge !== null) oneWayEdges.push(edge);
5202
+ continue;
5203
+ }
5204
+ if (isFullCellSolid(info, cellSize)) {
5205
+ solid[localY * columns + localX] = 1;
5206
+ continue;
5207
+ }
5208
+ polygons.push(translateShape(shape, cellX * cellSize, cellY * cellSize));
5209
+ }
5210
+ mergeSolidRuns(solid, columns, rows, originX, originY, cellSize, polygons);
5211
+ if (polygons.length === 0 && oneWayEdges.length === 0) return null;
5212
+ return {
5213
+ chunkX,
5214
+ chunkY,
5215
+ polygons,
5216
+ oneWayEdges
5217
+ };
5218
+ }
5219
+ /**
5220
+ * Runs the row-then-column greedy merge over the chunk's full-cell solid mask.
5221
+ *
5222
+ * @param solid - The `columns * rows` mask, row-major with row `0` at the bottom.
5223
+ * @param columns - The chunk's width in cells.
5224
+ * @param rows - The chunk's height in cells.
5225
+ * @param originX - The chunk's first column, in grid cells.
5226
+ * @param originY - The chunk's first row, in grid cells.
5227
+ * @param cellSize - The edge length of one cell, in metres.
5228
+ * @param out - The polygon list to append merged rectangles to.
5229
+ */
5230
+ function mergeSolidRuns(solid, columns, rows, originX, originY, cellSize, out) {
5231
+ const runsByRow = [];
5232
+ for (let localY = 0; localY < rows; localY += 1) {
5233
+ const runs = [];
5234
+ let localX = 0;
5235
+ while (localX < columns) {
5236
+ if (solid[localY * columns + localX] !== 1) {
5237
+ localX += 1;
5238
+ continue;
5239
+ }
5240
+ const start = localX;
5241
+ while (localX + 1 < columns && solid[localY * columns + localX + 1] === 1) localX += 1;
5242
+ runs.push({
5243
+ start,
5244
+ end: localX,
5245
+ consumed: false
5246
+ });
5247
+ localX += 1;
4521
5248
  }
4522
- const chunkSize = Math.max(1, map.chunkSize);
4523
- const cellSize = map.cellSize;
4524
- if (cellSize <= 0) return 0;
4525
- const chunksX = Math.ceil(definition.width / chunkSize);
4526
- const chunksY = Math.ceil(definition.height / chunkSize);
4527
- const window = this.#chunkWindow(bounds, chunkSize, cellSize, pixelsPerUnit, chunksX, chunksY);
4528
- let written = 0;
4529
- for (const [key, chunk] of this.#chunks) if (!inWindow(chunk.chunkX, chunk.chunkY, window)) this.#drop(registry, key, chunk);
4530
- for (let chunkY = window.minY; chunkY <= window.maxY; chunkY += 1) for (let chunkX = window.minX; chunkX <= window.maxX; chunkX += 1) {
4531
- const key = `${String(chunkX)},${String(chunkY)}`;
4532
- if (this.#chunks.has(key)) continue;
4533
- written += this.#build(map, atlas, registry, chunkX, chunkY, chunkSize, cellSize, pixelsPerUnit);
5249
+ runsByRow.push(runs);
5250
+ }
5251
+ for (let localY = 0; localY < rows; localY += 1) {
5252
+ const runs = runsByRow[localY];
5253
+ if (runs === void 0) continue;
5254
+ for (let index = 0; index < runs.length; index += 1) {
5255
+ const run = runs[index];
5256
+ if (run === void 0 || run.consumed) continue;
5257
+ let top = localY;
5258
+ while (top + 1 < rows) {
5259
+ const above = findRun(runsByRow[top + 1], run.start, run.end);
5260
+ if (above === null) break;
5261
+ above.consumed = true;
5262
+ top += 1;
5263
+ }
5264
+ const left = (originX + run.start) * cellSize;
5265
+ const right = (originX + run.end + 1) * cellSize;
5266
+ const bottom = (originY + localY) * cellSize;
5267
+ const ceiling = (originY + top + 1) * cellSize;
5268
+ out.push([
5269
+ {
5270
+ x: left,
5271
+ y: bottom
5272
+ },
5273
+ {
5274
+ x: right,
5275
+ y: bottom
5276
+ },
5277
+ {
5278
+ x: right,
5279
+ y: ceiling
5280
+ },
5281
+ {
5282
+ x: left,
5283
+ y: ceiling
5284
+ }
5285
+ ]);
4534
5286
  }
4535
- return written;
4536
5287
  }
4537
- /**
4538
- * Advances animated tiles and rewrites the chunks holding them.
4539
- *
4540
- * @param deltaSeconds - The scaled frame delta.
4541
- * @returns `true` when a tile's frame changed, so the renderer must rebuild.
4542
- *
4543
- * @internal
4544
- */
4545
- advanceAnimation(deltaSeconds) {
4546
- const previous = this.#animationClock;
4547
- this.#animationClock += deltaSeconds;
4548
- return Math.floor(previous * ANIMATION_TICKS_PER_SECOND) !== Math.floor(this.#animationClock * ANIMATION_TICKS_PER_SECOND);
5288
+ }
5289
+ /**
5290
+ * Finds an unconsumed run with exactly the given span.
5291
+ *
5292
+ * @param runs - The candidate row's runs.
5293
+ * @param start - The span's first column.
5294
+ * @param end - The span's last column.
5295
+ * @returns The matching run, or `null`.
5296
+ */
5297
+ function findRun(runs, start, end) {
5298
+ if (runs === void 0) return null;
5299
+ for (let index = 0; index < runs.length; index += 1) {
5300
+ const run = runs[index];
5301
+ if (run !== void 0 && !run.consumed && run.start === start && run.end === end) return run;
4549
5302
  }
4550
- /**
4551
- * The animation clock animated tiles are sampled at, in seconds.
4552
- *
4553
- * @returns The elapsed time.
4554
- *
4555
- * @internal
4556
- */
4557
- get animationClock() {
4558
- return this.#animationClock;
5303
+ return null;
5304
+ }
5305
+ /**
5306
+ * Moves a cell-local shape into world metres.
5307
+ *
5308
+ * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.
5309
+ * @param offsetX - The cell's left edge, in world metres.
5310
+ * @param offsetY - The cell's bottom edge, in world metres.
5311
+ * @returns The outline, counter-clockwise, in world metres.
5312
+ */
5313
+ function translateShape(shape, offsetX, offsetY) {
5314
+ if (shape.kind === "box") {
5315
+ const left = offsetX + shape.x;
5316
+ const bottom = offsetY + shape.y;
5317
+ const right = left + shape.width;
5318
+ const top = bottom + shape.height;
5319
+ return [
5320
+ {
5321
+ x: left,
5322
+ y: bottom
5323
+ },
5324
+ {
5325
+ x: right,
5326
+ y: bottom
5327
+ },
5328
+ {
5329
+ x: right,
5330
+ y: top
5331
+ },
5332
+ {
5333
+ x: left,
5334
+ y: top
5335
+ }
5336
+ ];
4559
5337
  }
4560
- /**
4561
- * Drops every materialised chunk.
4562
- *
4563
- * @param registry - The layer registry.
4564
- *
4565
- * @internal
4566
- */
4567
- dropAll(registry) {
4568
- this.#dropAll(registry);
5338
+ if (shape.kind === "polygon") {
5339
+ const points = [];
5340
+ for (let index = 0; index < shape.points.length; index += 1) {
5341
+ const point = shape.points[index];
5342
+ if (point !== void 0) points.push({
5343
+ x: offsetX + point.x,
5344
+ y: offsetY + point.y
5345
+ });
5346
+ }
5347
+ return points;
4569
5348
  }
4570
- /**
4571
- * The range of chunks the camera can see.
4572
- *
4573
- * @param bounds - The camera's visible bounds, in layer pixels, or `null`.
4574
- * @param chunkSize - Cells per chunk.
4575
- * @param cellSize - Metres per cell.
4576
- * @param pixelsPerUnit - Pixels per metre.
4577
- * @param chunksX - How many chunk columns the map has.
4578
- * @param chunksY - How many chunk rows.
4579
- * @returns The inclusive chunk window.
4580
- */
4581
- #chunkWindow(bounds, chunkSize, cellSize, pixelsPerUnit, chunksX, chunksY) {
4582
- if (bounds === null || !this.cullChunks) return {
4583
- minX: 0,
4584
- minY: 0,
4585
- maxX: chunksX - 1,
4586
- maxY: chunksY - 1
4587
- };
4588
- const matrix = this.entity.transform.worldMatrix;
4589
- const originX = matrix[12] ?? 0;
4590
- const originY = matrix[13] ?? 0;
4591
- const worldMinX = bounds.minX / pixelsPerUnit - originX;
4592
- const worldMaxX = bounds.maxX / pixelsPerUnit - originX;
4593
- const worldMinY = -bounds.maxY / pixelsPerUnit - originY;
4594
- const worldMaxY = -bounds.minY / pixelsPerUnit - originY;
4595
- const span = chunkSize * cellSize;
4596
- return {
4597
- minX: clampIndex(Math.floor(worldMinX / span), chunksX),
4598
- maxX: clampIndex(Math.floor(worldMaxX / span), chunksX),
4599
- minY: clampIndex(Math.floor(worldMinY / span), chunksY),
4600
- maxY: clampIndex(Math.floor(worldMaxY / span), chunksY)
4601
- };
5349
+ return [];
5350
+ }
5351
+ /**
5352
+ * The top edge of a one-way tile's collider, wound so the solid side is to the left.
5353
+ *
5354
+ * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.
5355
+ * @param offsetX - The cell's left edge, in world metres.
5356
+ * @param offsetY - The cell's bottom edge, in world metres.
5357
+ * @returns The `[from, to]` pair, right end first, or `null` when the shape has no width.
5358
+ */
5359
+ function topEdge(shape, offsetX, offsetY) {
5360
+ if (shape.kind === "box") {
5361
+ if (shape.width <= 0) return null;
5362
+ const left = offsetX + shape.x;
5363
+ const right = left + shape.width;
5364
+ const top = offsetY + shape.y + shape.height;
5365
+ return [{
5366
+ x: right,
5367
+ y: top
5368
+ }, {
5369
+ x: left,
5370
+ y: top
5371
+ }];
4602
5372
  }
4603
- /**
4604
- * Materialises one chunk's sprites.
4605
- *
4606
- * @param map - The tilemap.
4607
- * @param atlas - The tile atlas.
4608
- * @param registry - The layer registry.
4609
- * @param chunkX - The chunk's column.
4610
- * @param chunkY - The chunk's row.
4611
- * @param chunkSize - Cells per chunk.
4612
- * @param cellSize - Metres per cell.
4613
- * @param pixelsPerUnit - Pixels per metre.
4614
- * @returns How many sprites were created.
4615
- */
4616
- #build(map, atlas, registry, chunkX, chunkY, chunkSize, cellSize, pixelsPerUnit) {
4617
- const definition = map.definition;
4618
- if (definition === null) return 0;
4619
- const matrix = this.entity.transform.worldMatrix;
4620
- const originX = matrix[12] ?? 0;
4621
- const originY = matrix[13] ?? 0;
4622
- const sizePx = cellSize * pixelsPerUnit;
4623
- const sprites = [];
4624
- for (let layerIndex = 0; layerIndex < definition.layers.length; layerIndex += 1) {
4625
- const layer = definition.layers[layerIndex];
4626
- if (layer === void 0) continue;
4627
- const sortingLayer = layer.sortingLayer === "" ? this.sortingLayer : layer.sortingLayer;
4628
- const alpha = layer.opacity;
4629
- const endX = Math.min(layer.width, (chunkX + 1) * chunkSize);
4630
- const endY = Math.min(layer.height, (chunkY + 1) * chunkSize);
4631
- for (let y = chunkY * chunkSize; y < endY; y += 1) for (let x = chunkX * chunkSize; x < endX; x += 1) {
4632
- const tileId = map.getTile(layerIndex, x, y);
4633
- if (tileId === 0) continue;
4634
- const frameName = tileFrameName(definition, tileId);
4635
- const frame = frameName === null ? -1 : atlas.frameIndex(frameName);
4636
- if (frame < 0) continue;
4637
- const centre = worldToPixelsToRef(originX + (x + .5) * cellSize, originY + (y + .5) * cellSize, pixelsPerUnit, this.#pixels);
4638
- writeScratch(this.#scratch, centre.x, centre.y, sizePx, sizePx, frame, 0, 1, 1, 1, alpha, false, false, true);
4639
- sprites.push(registry.placeRaw(sortingLayer, atlas, "alpha", false, this.#scratch));
4640
- }
4641
- }
4642
- this.#chunks.set(`${String(chunkX)},${String(chunkY)}`, {
4643
- chunkX,
4644
- chunkY,
4645
- sprites
4646
- });
4647
- return sprites.length;
5373
+ if (shape.kind === "polygon") {
5374
+ let left = Number.POSITIVE_INFINITY;
5375
+ let right = Number.NEGATIVE_INFINITY;
5376
+ let top = Number.NEGATIVE_INFINITY;
5377
+ for (let index = 0; index < shape.points.length; index += 1) {
5378
+ const point = shape.points[index];
5379
+ if (point === void 0) continue;
5380
+ left = Math.min(left, point.x);
5381
+ right = Math.max(right, point.x);
5382
+ top = Math.max(top, point.y);
5383
+ }
5384
+ if (!(right > left)) return null;
5385
+ return [{
5386
+ x: offsetX + right,
5387
+ y: offsetY + top
5388
+ }, {
5389
+ x: offsetX + left,
5390
+ y: offsetY + top
5391
+ }];
4648
5392
  }
5393
+ return null;
5394
+ }
5395
+ //#endregion
5396
+ //#region src/tilemap/tilemap-asset.ts
5397
+ /**
5398
+ * The `tilemap` asset type and its loader (`docs/architecture/05-assets-and-loading.md` §5,
5399
+ * `11-2d-toolkit.md` §2.5).
5400
+ *
5401
+ * A `.tilemap.json` document is pure data — tile ids, tilesets, objects — so the loader needs no
5402
+ * device and behaves identically under a headless app, which is what lets a headless test assert
5403
+ * collision geometry and object spawning. The atlases the tilesets name are loaded by
5404
+ * `TilemapRenderer`, not here: a map with six tilesets in a scene that only shows one chunk should
5405
+ * not upload six textures at load time.
5406
+ */
5407
+ /**
5408
+ * A loaded tilemap document.
5409
+ *
5410
+ * @example
5411
+ * ```ts
5412
+ * const map = await app.assets.load<TilemapAsset>("2d/level-1.tilemap.json").promise;
5413
+ * map.definition.layers.length; // 2
5414
+ * ```
5415
+ *
5416
+ * @public
5417
+ */
5418
+ var TilemapAsset = class {
5419
+ /** The type name the asset service registers tilemaps under. */
5420
+ static assetType = TILEMAP_ASSET_TYPE;
5421
+ /** The address the document was loaded from. */
5422
+ address;
5423
+ /** The parsed document, with every tile layer decoded to a dense array. */
5424
+ definition;
5425
+ /** Each tileset's atlas address, resolved against this document's address. */
5426
+ atlasAddresses;
4649
5427
  /**
4650
- * Removes one chunk's sprites.
5428
+ * Wraps a parsed document. The `tilemap` loader constructs these.
4651
5429
  *
4652
- * @param registry - The layer registry.
4653
- * @param key - The chunk key.
4654
- * @param chunk - The chunk record.
5430
+ * @param address - The address it was loaded from.
5431
+ * @param definition - The parsed document.
5432
+ *
5433
+ * @internal
4655
5434
  */
4656
- #drop(registry, key, chunk) {
4657
- for (let index = chunk.sprites.length - 1; index >= 0; index -= 1) {
4658
- const sprite = chunk.sprites[index];
4659
- if (sprite !== void 0) registry.removeRaw(sprite.key, sprite.handle);
5435
+ constructor(address, definition) {
5436
+ this.address = address;
5437
+ this.definition = definition;
5438
+ const atlases = [];
5439
+ for (let index = 0; index < definition.tilesets.length; index += 1) {
5440
+ const tileset = definition.tilesets[index];
5441
+ atlases.push(tileset === void 0 ? "" : resolveRelative(address, tileset.atlas));
4660
5442
  }
4661
- this.#chunks.delete(key);
5443
+ this.atlasAddresses = atlases;
4662
5444
  }
4663
5445
  /**
4664
- * Removes every chunk's sprites.
5446
+ * The atlas address a tileset's tiles come from.
4665
5447
  *
4666
- * @param registry - The layer registry.
5448
+ * @param tilesetIndex - The tileset's index in the document.
5449
+ * @returns The address, or `""` when the index is out of range.
4667
5450
  */
4668
- #dropAll(registry) {
4669
- for (const [key, chunk] of this.#chunks) this.#drop(registry, key, chunk);
4670
- this.#chunks.clear();
5451
+ atlasFor(tilesetIndex) {
5452
+ return this.atlasAddresses[tilesetIndex] ?? "";
4671
5453
  }
4672
5454
  };
4673
- /** How often an animated tile's frame is allowed to change, in ticks per second. */
4674
- const ANIMATION_TICKS_PER_SECOND = 10;
4675
5455
  /**
4676
- * Whether a chunk is inside a window.
5456
+ * Builds the loader for `.tilemap.json` addresses.
4677
5457
  *
4678
- * @param x - The chunk column.
4679
- * @param y - The chunk row.
4680
- * @param window - The window.
4681
- * @returns `true` when the chunk should stay materialised.
4682
- */
4683
- function inWindow(x, y, window) {
4684
- return x >= window.minX && x <= window.maxX && y >= window.minY && y <= window.maxY;
4685
- }
4686
- /**
4687
- * Clamps a chunk index into a map's range.
5458
+ * @returns The loader to register with `ctx.registerAssetLoader`.
4688
5459
  *
4689
- * @param value - The index.
4690
- * @param count - How many chunks the map has on this axis.
4691
- * @returns The clamped index.
4692
- */
4693
- function clampIndex(value, count) {
4694
- return Math.min(Math.max(value, 0), Math.max(0, count - 1));
4695
- }
4696
- /**
4697
- * The `TilemapRenderer` schema.
5460
+ * @example
5461
+ * ```ts
5462
+ * ctx.registerAssetLoader(createTilemapLoader());
5463
+ * ```
4698
5464
  *
4699
- * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
5465
+ * @public
4700
5466
  */
4701
- function tilemapRendererSchema() {
4702
- return defineSchema({
4703
- atlas: asset(SpriteAtlasAsset, { tooltip: "The atlas the tile frames come from." }),
4704
- sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: "Sorting layer used when a map layer names none." }),
4705
- cullChunks: bool(true, { tooltip: "Drop chunks outside the camera's visible bounds." })
4706
- });
5467
+ function createTilemapLoader() {
5468
+ return {
5469
+ type: TILEMAP_ASSET_TYPE,
5470
+ extensions: TILEMAP_FILE_EXTENSIONS,
5471
+ async load(ctx) {
5472
+ const raw = await ctx.fetchJson();
5473
+ return new TilemapAsset(ctx.address, defineTilemap(raw, ctx.address));
5474
+ }
5475
+ };
4707
5476
  }
4708
5477
  //#endregion
4709
- //#region src/service/layer-registry.ts
5478
+ //#region src/tilemap/tilemap.ts
4710
5479
  /**
4711
- * The pool of Lite sprite layers (`docs/architecture/11-2d-toolkit.md` §1).
5480
+ * `Tilemap` (`docs/architecture/11-2d-toolkit.md` §2.5): the grid of tile ids a level is built
5481
+ * from, its cell arithmetic, and the merged collision geometry `@ignifx/physics-2d` consumes.
4712
5482
  *
4713
- * One `Sprite2DLayer` exists per **(sorting layer, atlas, blend mode, screen-space)** tuple,
4714
- * because Lite binds a layer to one atlas and one blend mode for its whole life (`index.d.ts` 11885
4715
- * declares both `readonly`). Layers are created on demand as sprites appear and torn down with the
4716
- * app; a sprite that changes any part of its key is removed from one layer and added to another,
4717
- * which replaces its handle.
5483
+ * The component holds no Lite object — `TilemapRenderer` draws it — so a headless app carries the
5484
+ * full grid and the full collision surface. That is what makes a level's collision testable
5485
+ * without a GPU, and what lets a server run the same map the client draws.
4718
5486
  *
4719
- * The registry also carries the **handle-index to component** map that picking needs. Lite has no
4720
- * per-sprite metadata slot and removes by swapping the last sprite into the freed index
4721
- * (`lib/sprite/sprite-2d-handle.js`), so the map is a dense array kept in step by applying the same
4722
- * swap rule.
5487
+ * ## Coordinates
5488
+ *
5489
+ * Cell `(0, 0)` is the **bottom-left** of the map, because ignifx 2D is +Y up (ADR-0011). The
5490
+ * document's own layers are stored top row first, as every editor writes them, and the component
5491
+ * flips on the way in. `worldToCell`/`cellToWorld` are relative to the tilemap entity's own
5492
+ * transform, so moving the entity moves the whole map.
4723
5493
  */
4724
- /** How many sprites a new layer pre-allocates room for. */
4725
- const INITIAL_LAYER_CAPACITY = 64;
4726
5494
  /**
4727
- * Builds the composite key two sprites must share to land in one Lite layer.
4728
- *
4729
- * @param sortingLayer - The sorting layer's name.
4730
- * @param atlasAddress - The atlas's address.
4731
- * @param blend - The blend mode.
4732
- * @param screenSpace - Whether the layer ignores the camera.
4733
- * @returns The key.
5495
+ * How many cells one chunk spans by default (`docs/architecture/11-2d-toolkit.md` §2.5).
4734
5496
  *
4735
5497
  * @public
4736
5498
  */
4737
- function spriteLayerKey(sortingLayer, atlasAddress, blend, screenSpace) {
4738
- return `${sortingLayer}|${atlasAddress}|${blend}|${screenSpace ? "screen" : "world"}`;
4739
- }
5499
+ const DEFAULT_CHUNK_SIZE = 32;
4740
5500
  /**
4741
- * Owns every Lite sprite layer in one app.
5501
+ * A tilemap.
5502
+ *
5503
+ * @example
5504
+ * ```ts
5505
+ * const level = app.world.createEntity({ name: "level" }).addComponent(Tilemap);
5506
+ * level.map = app.assets.load<TilemapAsset>("2d/level-1.tilemap.json").retain();
5507
+ * level.setTile(0, 3, 2, 0); // carve a hole in the ground layer
5508
+ * ```
4742
5509
  *
4743
5510
  * @public
4744
5511
  */
4745
- var SpriteLayerRegistry = class {
4746
- #records = /* @__PURE__ */ new Map();
4747
- /** Records in draw order, rebuilt whenever a layer is created. */
4748
- #ordered = [];
4749
- #sortingLayers;
4750
- #ySort;
4751
- #onLayerCreated;
4752
- #onLayerRemoved;
4753
- /**
4754
- * Builds the registry.
4755
- *
4756
- * @param sortingLayers - Resolves a sorting-layer name to its draw order.
4757
- * @param ySort - Which sorting layers draw back-to-front by world Y.
4758
- * @param onLayerCreated - Called with each new Lite layer, so the sprite renderer can draw it.
4759
- * @param onLayerRemoved - Called before a layer is dropped.
4760
- */
4761
- constructor(sortingLayers, ySort, onLayerCreated, onLayerRemoved) {
4762
- this.#sortingLayers = sortingLayers;
4763
- this.#ySort = ySort;
4764
- this.#onLayerCreated = onLayerCreated;
4765
- this.#onLayerRemoved = onLayerRemoved;
4766
- }
4767
- /**
4768
- * Every layer, in draw order.
4769
- *
4770
- * @returns A freshly allocated snapshot, for diagnostics.
4771
- */
4772
- describe() {
4773
- const out = [];
4774
- for (let index = 0; index < this.#ordered.length; index += 1) {
4775
- const record = this.#ordered[index];
4776
- if (record !== void 0) out.push({
4777
- key: record.key,
4778
- sortingLayer: record.sortingLayer,
4779
- layer: record.layer,
4780
- screenSpace: record.screenSpace,
4781
- count: record.layer.count,
4782
- ySort: record.ySort
4783
- });
4784
- }
4785
- return out;
4786
- }
4787
- /**
4788
- * The Lite layers, in draw order — what picking tests against.
4789
- *
4790
- * @param worldOnly - Whether to skip screen-space layers.
4791
- * @param out - The array to fill; it is emptied first, so one array serves every frame.
4792
- * @returns `out`.
4793
- */
4794
- collectLayers(worldOnly, out) {
4795
- out.length = 0;
4796
- for (let index = 0; index < this.#ordered.length; index += 1) {
4797
- const record = this.#ordered[index];
4798
- if (record !== void 0 && !(worldOnly && record.screenSpace)) out.push(record.layer);
4799
- }
4800
- return out;
4801
- }
4802
- /**
4803
- * Walks every layer's view, so the camera can write world layers and skip screen-space ones.
4804
- *
4805
- * @param visit - Called with each layer and whether it follows the camera.
4806
- *
4807
- * @internal
4808
- */
4809
- forEachLayer(visit) {
4810
- for (let index = 0; index < this.#ordered.length; index += 1) {
4811
- const record = this.#ordered[index];
4812
- if (record !== void 0) visit(record.layer, record.screenSpace);
4813
- }
4814
- }
5512
+ var Tilemap = class Tilemap extends Component {
5513
+ /** The registration id the serializer writes into scene files. */
5514
+ static typeId = "ignifx/Tilemap";
5515
+ /** One tilemap per entity. */
5516
+ static allowMultiple = false;
5517
+ /** The declarative fields (ADR-0004). */
5518
+ static schema = tilemapSchema();
5519
+ /** The mutable tile grids, bottom row first, one per document layer. */
5520
+ #grids = [];
5521
+ /** The document the grids were built from, so a swapped asset rebuilds them. */
5522
+ #built = null;
5523
+ /** The merged collision surface, rebuilt lazily after a change. */
5524
+ #collision = EMPTY_COLLISION;
5525
+ /** Whether the collision surface needs rebuilding. */
5526
+ #collisionDirty = true;
5527
+ /** Bumped on every collision rebuild, so a physics backend can skip unchanged frames. */
5528
+ #version = 0;
5529
+ #onTileChanged = new Signal();
5530
+ #onCollisionChanged = new Signal();
4815
5531
  /**
4816
- * Adds a sprite to the layer its key selects, creating the layer when it is the first of its kind.
4817
- *
4818
- * @param component - The sprite component.
4819
- * @param atlas - Its loaded atlas.
4820
- * @param scratch - The reusable props record, already written.
4821
- * @returns The key of the layer the sprite landed in.
4822
- *
4823
- * @internal
5532
+ * Builds a tilemap with the schema's defaults.
4824
5533
  */
4825
- place(component, atlas, scratch) {
4826
- const key = spriteLayerKey(component.sortingLayer, atlas.address, component.blend, component.screenSpace);
4827
- const record = this.#ensure(key, component.sortingLayer, component.blend, component.screenSpace, atlas);
4828
- const handle = addSprite(record.layer, scratch);
4829
- const index = spriteIndexOf(handle);
4830
- if (index >= 0) record.components[index] = component;
4831
- component.setPlacement(handle, key);
4832
- return key;
5534
+ constructor() {
5535
+ super();
5536
+ Object.assign(this, createDefaults(Tilemap.schema));
4833
5537
  }
4834
5538
  /**
4835
- * Removes a sprite from whichever layer holds it.
4836
- *
4837
- * @param component - The sprite component.
4838
- *
4839
- * @internal
5539
+ * Drops the grids, so a recycled component does not inherit the previous one's.
4840
5540
  */
4841
- remove(component) {
4842
- const placement = component.placement();
4843
- if (placement === null) return;
4844
- const record = this.#records.get(placement.key);
4845
- const index = spriteIndexOf(placement.handle);
4846
- if (record !== void 0 && index >= 0) {
4847
- const last = record.components.length - 1;
4848
- record.components[index] = record.components[last] ?? null;
4849
- record.components.length = Math.max(0, last);
4850
- }
4851
- removeSprite(placement.handle);
4852
- component.setPlacement(null, null);
5541
+ onAttach() {
5542
+ this.#grids = [];
5543
+ this.#built = null;
5544
+ this.#collision = EMPTY_COLLISION;
5545
+ this.#collisionDirty = true;
4853
5546
  }
4854
5547
  /**
4855
- * Adds a sprite that no `SpriteRenderer` owns — a tilemap's tiles.
4856
- *
4857
- * @remarks
4858
- * The sprite occupies a slot in the same layers component-owned sprites use, so it sorts and
4859
- * Y-sorts alongside them, but its slot in the pick map stays empty: `app.twoD.pickAt` resolves
4860
- * `SpriteRenderer` components, and a tile is not one. Pick a tile with `Tilemap.worldToCell`
4861
- * instead, which is exact and costs no draw-order search.
4862
- *
4863
- * @param sortingLayer - The sorting layer's name.
4864
- * @param atlas - The atlas the sprite draws from.
4865
- * @param blend - The blend mode.
4866
- * @param screenSpace - Whether the layer ignores the camera.
4867
- * @param scratch - The reusable props record, already written.
4868
- * @returns The key and the handle.
4869
- *
4870
- * @internal
5548
+ * Releases the grids.
4871
5549
  */
4872
- placeRaw(sortingLayer, atlas, blend, screenSpace, scratch) {
4873
- const key = spriteLayerKey(sortingLayer, atlas.address, blend, screenSpace);
4874
- const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas);
4875
- const handle = addSprite(record.layer, scratch);
4876
- const index = spriteIndexOf(handle);
4877
- if (index >= 0) record.components[index] = null;
4878
- return {
4879
- key,
4880
- handle
4881
- };
5550
+ onDetach() {
5551
+ this.#grids = [];
5552
+ this.#built = null;
4882
5553
  }
4883
5554
  /**
4884
- * Removes a sprite added by {@link SpriteLayerRegistry.placeRaw}.
4885
- *
4886
- * @param key - The key the sprite was placed under.
4887
- * @param handle - The handle.
5555
+ * Emitted whenever `setTile` changes a cell.
4888
5556
  *
4889
- * @internal
5557
+ * @returns The signal.
4890
5558
  */
4891
- removeRaw(key, handle) {
4892
- const record = this.#records.get(key);
4893
- const index = spriteIndexOf(handle);
4894
- if (record !== void 0 && index >= 0) {
4895
- const last = record.components.length - 1;
4896
- record.components[index] = record.components[last] ?? null;
4897
- record.components.length = Math.max(0, last);
4898
- }
4899
- removeSprite(handle);
5559
+ get onTileChanged() {
5560
+ return this.#onTileChanged;
4900
5561
  }
4901
5562
  /**
4902
- * Resolves a pick hit back to the component that owns the sprite.
5563
+ * Emitted after the merged collision surface has been rebuilt.
4903
5564
  *
4904
- * @param layer - The Lite layer the hit is in.
4905
- * @param spriteIndex - The dense index the hit reports.
4906
- * @returns The component, or `null` when the slot is unmapped.
5565
+ * @remarks
5566
+ * `@ignifx/physics-2d` connects to this and rebuilds only the chunks whose geometry moved. The
5567
+ * rebuild is lazy: the signal fires on the first read of {@link Tilemap.collisionData} after a
5568
+ * change, not on the `setTile` call itself, so a script that rewrites a thousand tiles in one
5569
+ * frame pays for one merge.
4907
5570
  *
4908
- * @internal
5571
+ * @returns The signal.
4909
5572
  */
4910
- componentAt(layer, spriteIndex) {
4911
- for (let index = 0; index < this.#ordered.length; index += 1) {
4912
- const record = this.#ordered[index];
4913
- if (record?.layer === layer) return record.components[spriteIndex] ?? null;
4914
- }
4915
- return null;
5573
+ get onCollisionChanged() {
5574
+ return this.#onCollisionChanged;
4916
5575
  }
4917
5576
  /**
4918
- * Empties every layer and drops them all.
5577
+ * The loaded document, or `null` while it is still loading.
4919
5578
  *
4920
- * @internal
5579
+ * @returns The asset.
4921
5580
  */
4922
- clear() {
4923
- for (let index = 0; index < this.#ordered.length; index += 1) {
4924
- const record = this.#ordered[index];
4925
- if (record !== void 0) {
4926
- clearLayer(record.layer);
4927
- this.#onLayerRemoved(record.layer);
4928
- }
4929
- }
4930
- this.#records.clear();
4931
- this.#ordered = [];
5581
+ get asset() {
5582
+ const handle = this.map;
5583
+ return handle?.state === "loaded" ? handle.value : null;
4932
5584
  }
4933
5585
  /**
4934
- * Finds or creates the layer a key names.
5586
+ * The parsed document, or `null`.
4935
5587
  *
4936
- * @param key - The composite key.
4937
- * @param component - The sprite whose fields describe the layer.
4938
- * @param atlas - The atlas to bind the layer to.
4939
- * @returns The record.
5588
+ * @returns The definition.
4940
5589
  */
4941
- #ensure(key, sortingLayer, blend, screenSpace, atlas) {
4942
- const existing = this.#records.get(key);
4943
- if (existing !== void 0) return existing;
4944
- const liteAtlas = atlas.lite.atlas;
4945
- if (liteAtlas === null) throw new Error("a sprite layer needs an uploaded atlas; this app is headless");
4946
- const layer = createLayer(liteAtlas, {
4947
- blend,
4948
- order: this.#sortingLayers.orderOf(sortingLayer) + this.#countIn(sortingLayer),
4949
- capacity: INITIAL_LAYER_CAPACITY,
4950
- customShader: null
4951
- });
4952
- const ySort = !screenSpace && this.#ySort[sortingLayer] === true;
4953
- if (ySort) setYSort(layer, true);
4954
- const record = {
4955
- key,
4956
- sortingLayer,
4957
- layer,
4958
- screenSpace,
4959
- ySort,
4960
- components: []
4961
- };
4962
- this.#records.set(key, record);
4963
- this.#ordered.push(record);
4964
- this.#ordered.sort(byOrder);
4965
- this.#onLayerCreated(layer);
4966
- return record;
5590
+ get definition() {
5591
+ return this.asset?.definition ?? null;
4967
5592
  }
4968
5593
  /**
4969
- * How many layers a sorting layer already has, so the next one gets the next sub-order.
5594
+ * How many metres one cell spans.
4970
5595
  *
4971
- * @param sortingLayer - The sorting layer's name.
4972
- * @returns The count.
5596
+ * @returns The cell size; `0` when nothing has loaded.
4973
5597
  */
4974
- #countIn(sortingLayer) {
4975
- let count = 0;
4976
- for (const record of this.#records.values()) if (record.sortingLayer === sortingLayer) count += 1;
4977
- return count;
5598
+ get cellSize() {
5599
+ if (this.cellSizeOverride > 0) return this.cellSizeOverride;
5600
+ return this.definition?.cellSize ?? 0;
4978
5601
  }
4979
- };
4980
- /**
4981
- * Orders two layer records by their Lite draw order.
4982
- *
4983
- * @param left - One record.
4984
- * @param right - The other.
4985
- * @returns The comparison.
4986
- */
4987
- function byOrder(left, right) {
4988
- return left.layer.order - right.layer.order;
4989
- }
4990
- //#endregion
4991
- //#region src/service/runtime.ts
4992
- /**
4993
- * One app's 2D runtime state.
4994
- *
4995
- * @internal
4996
- */
4997
- var TwoDRuntime = class {
4998
- #app;
4999
- #settings;
5000
- #sortingLayers;
5001
- #registry;
5002
- #options;
5003
- #renderer = null;
5004
- #hasTriedRenderer = false;
5005
- #camera = null;
5006
- #parallax = [];
5007
- #syncedThisFrame = 0;
5008
- #spriteCount = 0;
5009
- /** Reused by {@link TwoDRuntime.cameraBounds}. */
5010
- #bounds = {
5011
- minX: 0,
5012
- minY: 0,
5013
- maxX: 0,
5014
- maxY: 0
5015
- };
5016
- /** Reused when collecting layers for a bounds read. */
5017
- #boundsLayers = [];
5018
5602
  /**
5019
- * Builds the runtime.
5603
+ * How many layers the document has.
5020
5604
  *
5021
- * @param options - The app, the settings, the sorting layers, and the Lite hooks.
5605
+ * @returns The layer count.
5022
5606
  */
5023
- constructor(options) {
5024
- this.#app = options.app;
5025
- this.#settings = options.settings;
5026
- this.#options = options;
5027
- this.#sortingLayers = new SortingLayerTable(options.sortingLayers);
5028
- this.#registry = new SpriteLayerRegistry(this.#sortingLayers, options.settings.ySort, (layer) => {
5029
- const renderer = this.#renderer;
5030
- if (renderer !== null) options.attachLayer(renderer, layer);
5031
- }, (layer) => {
5032
- const renderer = this.#renderer;
5033
- if (renderer !== null) options.detachLayer(renderer, layer);
5034
- });
5035
- }
5036
- /** The resolved settings. */
5037
- get settings() {
5038
- return this.#settings;
5039
- }
5040
- /** How many pixels one world metre spans. */
5041
- get pixelsPerUnit() {
5042
- return this.#settings.pixelsPerUnit;
5043
- }
5044
- /** The sorting-layer resolver. */
5045
- get sortingLayers() {
5046
- return this.#sortingLayers;
5047
- }
5048
- /** The layer pool. */
5049
- get layers() {
5050
- return this.#registry;
5051
- }
5052
- /** The Lite sprite renderer, or `null`. */
5053
- get renderer() {
5054
- return this.#renderer;
5055
- }
5056
- /** The camera the last frame drew through, or `null`. */
5057
- get mainCamera() {
5058
- return this.#camera;
5059
- }
5060
- /** How many sprites the last frame actually wrote to Lite. */
5061
- get syncedLastFrame() {
5062
- return this.#syncedThisFrame;
5063
- }
5064
- /** How many `SpriteRenderer` components the last frame walked. */
5065
- get spriteCount() {
5066
- return this.#spriteCount;
5067
- }
5068
- /** The surface width the views are sized against, in pixels. */
5069
- get viewportWidthPx() {
5070
- const surface = this.#app.renderer.surface;
5071
- return surface === null ? 0 : surface.width;
5072
- }
5073
- /** The surface height the views are sized against, in pixels. */
5074
- get viewportHeightPx() {
5075
- const surface = this.#app.renderer.surface;
5076
- return surface === null ? 0 : surface.height;
5607
+ get layerCount() {
5608
+ return this.definition?.layers.length ?? 0;
5077
5609
  }
5078
5610
  /**
5079
- * Replaces the settings, which a scene file's `settings.twoD` block does at load time.
5611
+ * The merged collision surface, rebuilt if a tile changed since the last read.
5080
5612
  *
5081
- * @param settings - The new settings.
5613
+ * @remarks
5614
+ * The shape is the contract `@ignifx/physics-2d` consumes: chunked, in world metres relative to
5615
+ * the tilemap entity's origin, with adjacent full-cell tiles merged into as few counter-clockwise
5616
+ * rectangles as possible.
5617
+ *
5618
+ * @returns The collision data.
5082
5619
  */
5083
- applySettings(settings) {
5084
- this.#settings = settings;
5620
+ get collisionData() {
5621
+ if (this.#collisionDirty) this.#rebuildCollision();
5622
+ return this.#collision;
5085
5623
  }
5086
5624
  /**
5087
- * Records the frame's camera.
5625
+ * Reads a tile.
5088
5626
  *
5089
- * @param camera - The camera, or `null`.
5627
+ * @param layer - The layer's index in the document.
5628
+ * @param x - The cell's column, with `0` at the left.
5629
+ * @param y - The cell's row, with `0` at the bottom.
5630
+ * @returns The tile id, or `0` for an empty or out-of-range cell.
5090
5631
  */
5091
- setMainCamera(camera) {
5092
- this.#camera = camera;
5632
+ getTile(layer, x, y) {
5633
+ this.#ensureGrids();
5634
+ const definition = this.definition;
5635
+ const grid = this.#grids[layer];
5636
+ const declared = definition?.layers[layer];
5637
+ if (grid === void 0 || declared === void 0 || !inRange(x, y, declared.width, declared.height)) return 0;
5638
+ return grid[y * declared.width + x] ?? 0;
5093
5639
  }
5094
5640
  /**
5095
- * Records the parallax components the sync system should offset views for.
5641
+ * Writes a tile.
5096
5642
  *
5097
- * @param layers - The components.
5643
+ * @param layer - The layer's index in the document.
5644
+ * @param x - The cell's column, with `0` at the left.
5645
+ * @param y - The cell's row, with `0` at the bottom.
5646
+ * @param tileId - The tile id, or `0` to clear the cell.
5647
+ * @throws IgnifxError with code `IGX-1111` when the cell is outside the layer.
5098
5648
  */
5099
- setParallaxLayers(layers) {
5100
- this.#parallax = layers;
5649
+ setTile(layer, x, y, tileId) {
5650
+ this.#ensureGrids();
5651
+ const definition = this.definition;
5652
+ const grid = this.#grids[layer];
5653
+ const declared = definition?.layers[layer];
5654
+ if (grid === void 0 || declared === void 0 || !inRange(x, y, declared.width, declared.height)) throw twoDError(TwoDErrorCode.tileOutOfRange, `Cell ${String(x)},${String(y)} is outside layer ${String(layer)}.`, {
5655
+ context: {
5656
+ x,
5657
+ y,
5658
+ layer
5659
+ },
5660
+ hint: "Check the cell against Tilemap.layerSize; cell (0, 0) is the bottom-left."
5661
+ });
5662
+ const offset = y * declared.width + x;
5663
+ const previous = grid[offset] ?? 0;
5664
+ if (previous === tileId) return;
5665
+ grid[offset] = tileId;
5666
+ if (declared.collision) this.#collisionDirty = true;
5667
+ this.#onTileChanged.emit({
5668
+ layer,
5669
+ x,
5670
+ y,
5671
+ previous,
5672
+ current: tileId
5673
+ });
5101
5674
  }
5102
5675
  /**
5103
- * Offsets each parallax layer's view by the camera's motion times `1 - factor`
5104
- * (`docs/architecture/11-2d-toolkit.md` §2.6).
5676
+ * A layer's size, in cells.
5677
+ *
5678
+ * @param layer - The layer's index.
5679
+ * @returns The size, or a zero size for an unknown layer.
5105
5680
  */
5106
- applyParallax() {
5107
- const camera = this.#camera;
5108
- if (camera === null || this.#parallax.length === 0) return;
5109
- const entries = this.#registry.describe();
5110
- for (let index = 0; index < this.#parallax.length; index += 1) {
5111
- const layer = this.#parallax[index];
5112
- if (layer === void 0 || !layer.isEnabledInHierarchy) continue;
5113
- layer.applyTo(entries, camera, this.#settings.pixelsPerUnit);
5114
- }
5681
+ layerSize(layer) {
5682
+ const declared = this.definition?.layers[layer];
5683
+ return declared === void 0 ? ZERO : {
5684
+ x: declared.width,
5685
+ y: declared.height
5686
+ };
5115
5687
  }
5116
5688
  /**
5117
- * The layer-pixel rectangle the camera can currently see, for chunk culling.
5689
+ * Converts a world point into the cell containing it.
5118
5690
  *
5119
5691
  * @remarks
5120
- * Read off the first world layer's view, which the sync system has already written this frame.
5121
- * Every world layer carries the same view, so any of them answers; `null` means there is no world
5122
- * layer yet, in which case a tilemap builds every chunk and culls from the next frame on.
5692
+ * The point is in world metres; the map's own origin is the tilemap entity's position, so a moved
5693
+ * or scaled tilemap still answers correctly. The result is floored, so a point exactly on a cell
5694
+ * boundary belongs to the cell above and to the right of it.
5123
5695
  *
5124
- * @returns The bounds, or `null`.
5696
+ * @param point - The world point, in metres.
5697
+ * @param out - The vector to write.
5698
+ * @returns `out`, holding integer cell coordinates that may be outside the map.
5125
5699
  */
5126
- cameraBounds() {
5127
- const first = this.#registry.collectLayers(true, this.#boundsLayers)[0];
5128
- if (first === void 0 || this.viewportWidthPx === 0) return null;
5129
- return visibleBounds(first.view, this.viewportWidthPx, this.viewportHeightPx, this.#bounds);
5700
+ worldToCell(point, out) {
5701
+ const size = this.cellSize;
5702
+ const matrix = this.entity.transform.worldMatrix;
5703
+ const originX = matrix[12] ?? 0;
5704
+ const originY = matrix[13] ?? 0;
5705
+ if (size <= 0) {
5706
+ out.x = 0;
5707
+ out.y = 0;
5708
+ return out;
5709
+ }
5710
+ out.x = Math.floor((point.x - originX) / size);
5711
+ out.y = Math.floor((point.y - originY) / size);
5712
+ return out;
5130
5713
  }
5131
5714
  /**
5132
- * Advances every animated tile on the 2D animation clock.
5715
+ * Converts a cell into the world point at its **centre**.
5133
5716
  *
5134
- * @remarks
5135
- * Implements `AnimatedTilemapSink`, which is what lets the animation system drive tilemaps
5136
- * without importing the renderer.
5717
+ * @param x - The cell's column.
5718
+ * @param y - The cell's row, with `0` at the bottom.
5719
+ * @param out - The vector to write.
5720
+ * @returns `out`, in world metres.
5721
+ */
5722
+ cellToWorld(x, y, out) {
5723
+ const size = this.cellSize;
5724
+ const matrix = this.entity.transform.worldMatrix;
5725
+ out.x = (matrix[12] ?? 0) + (x + .5) * size;
5726
+ out.y = (matrix[13] ?? 0) + (y + .5) * size;
5727
+ return out;
5728
+ }
5729
+ /**
5730
+ * The collision footprint of whatever is at a cell, across every collision layer.
5137
5731
  *
5138
- * @param world - The world holding the tilemaps.
5139
- * @param deltaSeconds - The scaled frame delta.
5732
+ * @param x - The cell's column.
5733
+ * @param y - The cell's row, with `0` at the bottom.
5734
+ * @returns The topmost non-empty collider, or a `"none"` shape.
5140
5735
  */
5141
- advanceAnimatedTiles(world, deltaSeconds) {
5142
- const renderers = world.components(TilemapRenderer);
5143
- for (let index = 0; index < renderers.length; index += 1) {
5144
- const renderer = renderers[index];
5145
- if (renderer !== void 0 && renderer.isEnabledInHierarchy && renderer.advanceAnimation(deltaSeconds)) renderer.invalidate();
5736
+ collisionAt(x, y) {
5737
+ const definition = this.definition;
5738
+ if (definition === null) return NO_COLLISION;
5739
+ for (let layer = definition.layers.length - 1; layer >= 0; layer -= 1) {
5740
+ const declared = definition.layers[layer];
5741
+ if (declared === void 0 || !declared.collision) continue;
5742
+ const info = tileCollisionInfo(definition, this.getTile(layer, x, y));
5743
+ if (info.shape.kind !== "none") return info;
5146
5744
  }
5745
+ return NO_COLLISION;
5147
5746
  }
5148
5747
  /**
5149
- * Publishes the frame's sync counters.
5748
+ * Forces the collision surface to be rebuilt on the next read.
5150
5749
  *
5151
- * @param synced - How many sprites were written.
5152
- * @param total - How many sprite components were walked.
5750
+ * @internal
5153
5751
  */
5154
- reportSynced(synced, total) {
5155
- this.#syncedThisFrame = synced;
5156
- this.#spriteCount = total;
5752
+ invalidateCollision() {
5753
+ this.#collisionDirty = true;
5157
5754
  }
5158
5755
  /**
5159
- * Creates and registers the Lite sprite renderer, once, on the first frame that can.
5160
- *
5161
- * @remarks
5162
- * Idempotent, and a no-op under a headless app or once a first attempt has failed. See the
5163
- * module's own remarks for why this cannot happen in `onStart`.
5756
+ * Builds the mutable grids from the document, flipping each layer bottom-row-first.
5164
5757
  */
5165
- ensureRenderer() {
5166
- if (this.#hasTriedRenderer || this.#options.createRenderer === null) return;
5167
- this.#hasTriedRenderer = true;
5168
- const renderer = this.#options.createRenderer();
5169
- this.#renderer = renderer;
5170
- const entries = this.#registry.describe();
5171
- for (let index = 0; index < entries.length; index += 1) {
5172
- const entry = entries[index];
5173
- if (entry !== void 0) this.#options.attachLayer(renderer, entry.layer);
5758
+ #ensureGrids() {
5759
+ const loaded = this.asset;
5760
+ if (loaded === null || loaded === this.#built) return;
5761
+ this.#built = loaded;
5762
+ this.#collisionDirty = true;
5763
+ const grids = [];
5764
+ const layers = loaded.definition.layers;
5765
+ for (let index = 0; index < layers.length; index += 1) {
5766
+ const layer = layers[index];
5767
+ if (layer === void 0) {
5768
+ grids.push(/* @__PURE__ */ new Int32Array(0));
5769
+ continue;
5770
+ }
5771
+ const grid = new Int32Array(layer.width * layer.height);
5772
+ for (let row = 0; row < layer.height; row += 1) {
5773
+ const source = (layer.height - 1 - row) * layer.width;
5774
+ for (let column = 0; column < layer.width; column += 1) grid[row * layer.width + column] = layer.tiles[source + column] ?? 0;
5775
+ }
5776
+ grids.push(grid);
5174
5777
  }
5778
+ this.#grids = grids;
5175
5779
  }
5176
5780
  /**
5177
- * Drops every layer and the renderer.
5781
+ * Merges every collision layer's tiles into chunked polygons.
5178
5782
  */
5179
- dispose() {
5180
- this.#registry.clear();
5181
- const renderer = this.#renderer;
5182
- this.#renderer = null;
5183
- if (renderer !== null) this.#options.destroyRenderer(renderer);
5783
+ #rebuildCollision() {
5784
+ this.#ensureGrids();
5785
+ this.#collisionDirty = false;
5786
+ const definition = this.definition;
5787
+ const size = this.cellSize;
5788
+ if (definition === null || size <= 0) {
5789
+ this.#collision = EMPTY_COLLISION;
5790
+ return;
5791
+ }
5792
+ this.#version += 1;
5793
+ this.#collision = mergeTileCollisions((x, y) => this.collisionAt(x, y), {
5794
+ cellSize: size,
5795
+ chunkSize: Math.max(1, this.chunkSize),
5796
+ width: definition.width,
5797
+ height: definition.height
5798
+ }, this.#version);
5799
+ this.#onCollisionChanged.emit();
5184
5800
  }
5185
5801
  };
5802
+ /** The cell size a tilemap with nothing loaded reports. */
5803
+ const ZERO = Object.freeze({
5804
+ x: 0,
5805
+ y: 0
5806
+ });
5807
+ /** The collision surface of a tilemap with nothing loaded. */
5808
+ const EMPTY_COLLISION = Object.freeze({
5809
+ cellSize: 0,
5810
+ chunkSize: 0,
5811
+ chunks: Object.freeze([]),
5812
+ version: 0
5813
+ });
5814
+ /** The answer for a cell that carries no collider. */
5815
+ const NO_COLLISION = Object.freeze({
5816
+ shape: Object.freeze({ kind: "none" }),
5817
+ oneWay: false,
5818
+ properties: Object.freeze({})
5819
+ });
5820
+ /**
5821
+ * Whether a cell is inside a layer.
5822
+ *
5823
+ * @param x - The column.
5824
+ * @param y - The row.
5825
+ * @param width - The layer width, in cells.
5826
+ * @param height - The layer height, in cells.
5827
+ * @returns `true` when the cell exists.
5828
+ */
5829
+ function inRange(x, y, width, height) {
5830
+ return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < width && y < height;
5831
+ }
5832
+ /**
5833
+ * The `Tilemap` schema.
5834
+ *
5835
+ * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
5836
+ */
5837
+ function tilemapSchema() {
5838
+ return defineSchema({
5839
+ map: asset(TilemapAsset, { tooltip: "The .tilemap.json document." }),
5840
+ chunkSize: u32(32, {
5841
+ min: 1,
5842
+ tooltip: "How many cells one render and collision chunk spans."
5843
+ }),
5844
+ cellSizeOverride: f32(0, {
5845
+ min: 0,
5846
+ tooltip: "Metres per cell, overriding the document's own; 0 uses it."
5847
+ })
5848
+ });
5849
+ }
5186
5850
  //#endregion
5187
5851
  //#region src/service/sync-system.ts
5188
5852
  /**
@@ -5238,9 +5902,11 @@ var TwoDSyncSystem = class {
5238
5902
  /** Sprites that were placed in a layer on a previous frame. */
5239
5903
  #placed = /* @__PURE__ */ new Set();
5240
5904
  /**
5241
- * Builds the system.
5905
+ * Builds the system. The extension does this; a game never constructs one.
5242
5906
  *
5243
5907
  * @param runtime - The 2D runtime state: settings, the layer registry, and the Lite renderer.
5908
+ *
5909
+ * @internal
5244
5910
  */
5245
5911
  constructor(runtime) {
5246
5912
  this.#runtime = runtime;
@@ -5252,11 +5918,26 @@ var TwoDSyncSystem = class {
5252
5918
  */
5253
5919
  update(ctx) {
5254
5920
  this.#runtime.ensureRenderer();
5921
+ this.#runtime.collectEffects(ctx.world);
5255
5922
  const camera = selectCamera(ctx.world);
5256
5923
  this.#runtime.setMainCamera(camera);
5257
5924
  this.#syncSprites(ctx.world);
5258
5925
  this.#syncViews(camera);
5259
5926
  this.#syncTilemaps(ctx.world);
5927
+ this.#runtime.writeEffectParams();
5928
+ }
5929
+ /**
5930
+ * Connects the scene hook to a new world.
5931
+ *
5932
+ * @remarks
5933
+ * This is the only hook that fires for every world. `register` runs before the world exists and
5934
+ * `onStart` runs only when a game calls `app.start()`, so a headless tool that loads a scene
5935
+ * without ever starting a loop would otherwise never see its `settings.twoD` block.
5936
+ *
5937
+ * @param world - The new world.
5938
+ */
5939
+ onWorldCreated(world) {
5940
+ this.#runtime.attachWorld(world);
5260
5941
  }
5261
5942
  /**
5262
5943
  * Drops every layer when the world goes away.
@@ -5264,6 +5945,7 @@ var TwoDSyncSystem = class {
5264
5945
  * @param _world - The world being disposed.
5265
5946
  */
5266
5947
  onWorldDisposed(_world) {
5948
+ this.#runtime.detachWorld();
5267
5949
  this.#placed.clear();
5268
5950
  this.#seen.clear();
5269
5951
  }
@@ -5324,10 +6006,10 @@ var TwoDSyncSystem = class {
5324
6006
  registry.place(sprite, atlas, this.#scratch);
5325
6007
  this.#placed.add(sprite);
5326
6008
  const placed = sprite.placement();
5327
- if (placed !== null) setYSortOrder(placed.handle, sprite.orderInLayer);
6009
+ if (placed !== null) registry.applyOrderInLayer(placed.key, placed.handle, sprite.orderInLayer);
5328
6010
  } else {
5329
6011
  updateSprite(current.handle, this.#scratch);
5330
- setYSortOrder(current.handle, sprite.orderInLayer);
6012
+ registry.applyOrderInLayer(current.key, current.handle, sprite.orderInLayer);
5331
6013
  }
5332
6014
  sprite.markSynced(isStatic, matrixVersion, this.#boundsMin.x, this.#boundsMin.y, this.#boundsMax.x, this.#boundsMax.y);
5333
6015
  synced += 1;
@@ -5437,6 +6119,8 @@ function layerKeyOf(sprite, atlasAddress) {
5437
6119
  *
5438
6120
  * @param world - The world to search.
5439
6121
  * @returns The camera, or `null` when the world has none enabled.
6122
+ *
6123
+ * @public
5440
6124
  */
5441
6125
  function selectCamera(world) {
5442
6126
  const cameras = world.components(Camera2D);
@@ -5475,6 +6159,13 @@ var TwoDService = class {
5475
6159
  maxX: 0,
5476
6160
  maxY: 0
5477
6161
  };
6162
+ /** Reused by `pickAt`, so picking allocates nothing. */
6163
+ #pickPoint = {
6164
+ x: 0,
6165
+ y: 0
6166
+ };
6167
+ /** A one-element array reused by `pickAt`, because Lite's picker takes a list. */
6168
+ #oneLayer = [];
5478
6169
  /**
5479
6170
  * Builds the service.
5480
6171
  *
@@ -5579,21 +6270,28 @@ var TwoDService = class {
5579
6270
  * @returns The hit, or `null` for a miss.
5580
6271
  */
5581
6272
  pickAt(xPx, yPx) {
5582
- const hit = pickSprite(this.#runtime.layers.collectLayers(false, this.#pickLayers), xPx, yPx);
5583
- if (hit === null) return null;
5584
- const component = this.#runtime.layers.componentAt(hit.layer, hit.spriteIndex);
5585
- if (component === null || !component.pickable || component.isDestroyed) return null;
5586
- return {
5587
- entity: component.entity,
5588
- component,
5589
- u: hit.u,
5590
- v: hit.v
5591
- };
6273
+ const layers = this.#runtime.layers.collectLayers(false, this.#pickLayers);
6274
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
6275
+ const layer = layers[index];
6276
+ if (layer === void 0) continue;
6277
+ const point = screenToLayer(layer.view, xPx, yPx, this.#pickPoint);
6278
+ this.#oneLayer[0] = layer;
6279
+ const hit = pickSprite(this.#oneLayer, point.x, point.y);
6280
+ if (hit === null) continue;
6281
+ const component = this.#runtime.layers.componentAt(hit.layer, hit.spriteIndex);
6282
+ if (component !== null && component.pickable && !component.isDestroyed) return {
6283
+ entity: component.entity,
6284
+ component,
6285
+ u: hit.u,
6286
+ v: hit.v
6287
+ };
6288
+ }
6289
+ return null;
5592
6290
  }
5593
6291
  /**
5594
6292
  * The world-space rectangle the camera can currently see.
5595
6293
  *
5596
- * @param out - The vectors to write.
6294
+ * @param out - The box to write: its `min` takes the lower corner and its `max` the upper.
5597
6295
  * @returns `true` when a camera and a layer existed to measure against.
5598
6296
  */
5599
6297
  visibleWorldBounds(out) {
@@ -5733,226 +6431,36 @@ function twoDSettingsSchema() {
5733
6431
  ySort: map(bool(false))
5734
6432
  });
5735
6433
  }
5736
- //#endregion
5737
- //#region src/sprite/parallax-layer.ts
5738
- /**
5739
- * `ParallaxLayer` (`docs/architecture/11-2d-toolkit.md` §2.6): makes one sorting layer scroll at a
5740
- * fraction of the camera's speed, which is what gives a side-scroller depth.
5741
- *
5742
- * The component owns no sprites. It reaches into the views of every Lite layer belonging to its
5743
- * sorting layer, after the 2D sync system has written the camera's view onto them, and slides each
5744
- * one back by `cameraPositionPx × (1 − factor)`. A factor of `1` moves with the camera (no
5745
- * parallax); `0` is pinned to the world origin, which is what a distant sky wants.
5746
- */
5747
- /**
5748
- * A parallax layer.
5749
- *
5750
- * @example
5751
- * ```ts
5752
- * const sky = app.world.createEntity({ name: "sky" }).addComponent(ParallaxLayer);
5753
- * sky.sortingLayer = "Background";
5754
- * sky.factor = { x: 0.2, y: 0.5 };
5755
- * ```
5756
- *
5757
- * @public
5758
- */
5759
- var ParallaxLayer = class ParallaxLayer extends Component {
5760
- /** The registration id the serializer writes into scene files. */
5761
- static typeId = "ignifx/ParallaxLayer";
5762
- /** One parallax setting per entity; several entities may each drive a different sorting layer. */
5763
- static allowMultiple = false;
5764
- /** The declarative fields (ADR-0004). */
5765
- static schema = parallaxLayerSchema();
5766
- /** Scratch, so applying the offset allocates nothing. */
5767
- #scratch = new Vec2();
5768
- /**
5769
- * Builds a parallax layer with the schema's defaults.
5770
- */
5771
- constructor() {
5772
- super();
5773
- Object.assign(this, createDefaults(ParallaxLayer.schema));
5774
- }
5775
- /**
5776
- * Slides every matching layer's view.
5777
- *
5778
- * @remarks
5779
- * Runs after the camera has written its own view, so the arithmetic is a pure offset:
5780
- * `view.positionPx -= cameraPx × (1 − factor)`. With `repeatX`/`repeatY` the offset is taken
5781
- * modulo one repetition, which keeps a tiled backdrop from drifting away from the camera no
5782
- * matter how far the player walks — and keeps the number in single-precision range.
5783
- *
5784
- * @param entries - Every layer, as the registry describes them.
5785
- * @param camera - The active camera.
5786
- * @param pixelsPerUnit - The pixels one metre spans.
5787
- *
5788
- * @internal
5789
- */
5790
- applyTo(entries, camera, pixelsPerUnit) {
5791
- const cameraPx = worldToPixelsToRef(camera.centre.x, camera.centre.y, pixelsPerUnit, this.#scratch);
5792
- let offsetX = cameraPx.x * (1 - this.factor.x);
5793
- let offsetY = cameraPx.y * (1 - this.factor.y);
5794
- if (this.repeatX && this.repeatWidth > 0) offsetX = wrap(offsetX, this.repeatWidth * pixelsPerUnit);
5795
- if (this.repeatY && this.repeatHeight > 0) offsetY = wrap(offsetY, this.repeatHeight * pixelsPerUnit);
5796
- for (let index = 0; index < entries.length; index += 1) {
5797
- const entry = entries[index];
5798
- if (entry === void 0 || entry.screenSpace || entry.sortingLayer !== this.sortingLayer) continue;
5799
- const view = entry.layer.view;
5800
- view.positionPx[0] -= offsetX;
5801
- view.positionPx[1] -= offsetY;
5802
- }
5803
- }
5804
- };
5805
- /**
5806
- * Wraps a value into `[0, span)`, keeping the sign of the mathematical modulus.
5807
- *
5808
- * @param value - The value.
5809
- * @param span - The period; must be greater than zero.
5810
- * @returns The wrapped value.
5811
- */
5812
- function wrap(value, span) {
5813
- const remainder = value % span;
5814
- return remainder < 0 ? remainder + span : remainder;
5815
- }
5816
- /**
5817
- * The `ParallaxLayer` schema.
5818
- *
5819
- * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
5820
- */
5821
- function parallaxLayerSchema() {
5822
- return defineSchema({
5823
- sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: "Which sorting layer scrolls slowly." }),
5824
- factor: vec2({
5825
- x: .5,
5826
- y: 1
5827
- }, { tooltip: "Fraction of the camera's motion the layer follows." }),
5828
- repeatX: bool(false, { tooltip: "Tile the layer horizontally across the camera's view." }),
5829
- repeatY: bool(false, { tooltip: "Tile the layer vertically." }),
5830
- repeatWidth: f32(0, {
5831
- min: 0,
5832
- tooltip: "World width of one repetition, in metres."
5833
- }),
5834
- repeatHeight: f32(0, {
5835
- min: 0,
5836
- tooltip: "World height of one repetition, in metres."
5837
- })
5838
- });
5839
- }
5840
- //#endregion
5841
- //#region src/sprite/sprite-layer-effect.ts
5842
- /**
5843
- * `SpriteLayerEffect` (`docs/architecture/11-2d-toolkit.md` §6): a per-layer custom fragment shader.
5844
- *
5845
- * Lite's 2D path has no lighting model, so effects are what a 2D game reaches for instead: a tint,
5846
- * a dissolve, water, a heat shimmer. A layer created with a `customShader`
5847
- * (`Sprite2DLayerOptions.customShader`, `index.d.ts` 11934) runs a WGSL fragment body with a
5848
- * built-in `fx.time` clock and a `fx.params` vec4 the component writes every frame through
5849
- * `setSprite2DShaderParams` (`index.d.ts` 11074).
5850
- *
5851
- * ## The one-shader-per-layer constraint
5852
- *
5853
- * `Sprite2DLayer.customShader` is `readonly` and is only set at creation. A layer's shader
5854
- * therefore cannot change once sprites are in it, so `SpriteLayerEffect` has to exist **before**
5855
- * the first sprite on its sorting layer is synced — put it in the scene file, or add it in
5856
- * `awake`, not halfway through a level.
5857
- */
5858
- /** The built-in effects, in the order an inspector should list them. @public */
5859
- const SPRITE_EFFECT_KINDS = ["tint", "custom"];
5860
6434
  /**
5861
- * The WGSL body of the built-in `tint` effect.
6435
+ * The value a `"sprite"`-mode frame is cleared to, read from the **core** `rendering.clearColor`
6436
+ * setting and decoded the way the 3D path decodes it.
5862
6437
  *
5863
6438
  * @remarks
5864
- * Multiplies the sampled texel by `fx.params.rgb` and scales its alpha by `fx.params.a`, which is
5865
- * a per-layer tint that a per-sprite `color` cannot express — every sprite in the layer fades
5866
- * together, in one uniform write, rather than in one instance write each.
5867
- *
5868
- * @public
5869
- */
5870
- const TINT_EFFECT_WGSL = "let texel = textureSample(atlasTex, atlasSamp, uv); return vec4f(texel.rgb * fx.params.rgb, texel.a * fx.params.a);";
5871
- /**
5872
- * A per-layer shader effect.
6439
+ * A `"sprite"`-mode sprite pass owns the frame: it clears the swapchain itself and nothing the
6440
+ * render scene did survives underneath, so `rendering.clearColor` would otherwise have no effect at
6441
+ * all in a 2D game. The precedence the 3D path documents —
6442
+ * `Camera.clearColor`, then `Environment.clearColor`, then the setting
6443
+ * (`docs/architecture/07-rendering.md` §2.1) — has only its last rung here: neither of those two
6444
+ * components exists in a 2D scene, and `Camera2D` has no `clearColor` field of its own.
5873
6445
  *
5874
- * @example
5875
- * ```ts
5876
- * const dusk = app.world.createEntity({ name: "dusk" }).addComponent(SpriteLayerEffect);
5877
- * dusk.sortingLayer = "Default";
5878
- * dusk.kind = "tint";
5879
- * dusk.tint = { r: 0.6, g: 0.6, b: 0.9, a: 1 };
5880
- * ```
6446
+ * Colours are sRGB everywhere in ignifx and Lite's clear values are linear, so the setting is
6447
+ * decoded on the way through exactly as `RendererImpl.applyClearColor` decodes it. That is what
6448
+ * makes a `"sprite"` frame and a `"mixed"` frame with the same setting the same colour on screen,
6449
+ * and it is also why a literal `#14181F` presents darker than its hex suggests.
5881
6450
  *
5882
- * @public
5883
- */
5884
- var SpriteLayerEffect = class SpriteLayerEffect extends Component {
5885
- /** The registration id the serializer writes into scene files. */
5886
- static typeId = "ignifx/SpriteLayerEffect";
5887
- /** One effect per entity; several entities may each drive a different sorting layer. */
5888
- static allowMultiple = false;
5889
- /** The declarative fields (ADR-0004). */
5890
- static schema = spriteLayerEffectSchema();
5891
- /**
5892
- * Builds an effect with the schema's defaults.
5893
- */
5894
- constructor() {
5895
- super();
5896
- Object.assign(this, createDefaults(SpriteLayerEffect.schema));
5897
- }
5898
- /**
5899
- * The WGSL fragment body this effect installs.
5900
- *
5901
- * @returns The shader source.
5902
- * @throws IgnifxError with code `IGX-1113` when `kind` is `"custom"` and `shader` is empty.
5903
- */
5904
- source() {
5905
- if (this.kind === "tint") return TINT_EFFECT_WGSL;
5906
- if (this.shader === "") throw twoDError(TwoDErrorCode.missingShaderSource, "A custom SpriteLayerEffect needs a WGSL fragment body.", {
5907
- context: {
5908
- sortingLayer: this.sortingLayer,
5909
- entity: this.entity.uid
5910
- },
5911
- hint: "Set `effect.shader` to a WGSL body, or use kind: \"tint\"."
5912
- });
5913
- return this.shader;
5914
- }
5915
- /**
5916
- * The `fx.params` vec4 to write this frame.
5917
- *
5918
- * @param out - The four numbers to fill.
5919
- * @returns `out`.
5920
- *
5921
- * @internal
5922
- */
5923
- writeParams(out) {
5924
- if (this.kind === "tint") {
5925
- out[0] = this.tint.r;
5926
- out[1] = this.tint.g;
5927
- out[2] = this.tint.b;
5928
- out[3] = this.tint.a;
5929
- return out;
5930
- }
5931
- out[0] = this.params.x;
5932
- out[1] = this.params.y;
5933
- out[2] = this.params.z;
5934
- out[3] = this.params.w;
5935
- return out;
5936
- }
5937
- };
5938
- /**
5939
- * The `SpriteLayerEffect` schema.
6451
+ * @param app - The app whose settings are read.
6452
+ * @returns The clear value, as straight linear RGBA in `0` to `1`.
5940
6453
  *
5941
- * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).
6454
+ * @internal
5942
6455
  */
5943
- function spriteLayerEffectSchema() {
5944
- return defineSchema({
5945
- sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: "Which sorting layer the effect applies to." }),
5946
- kind: enumOf(SPRITE_EFFECT_KINDS, "tint", { tooltip: "Which shader to install." }),
5947
- tint: color("#ffffffff", { tooltip: "The colour the tint effect multiplies by." }),
5948
- params: vec4({
5949
- x: 0,
5950
- y: 0,
5951
- z: 0,
5952
- w: 0
5953
- }, { tooltip: "The fx.params vec4 a custom shader reads." }),
5954
- shader: str("", { tooltip: "The WGSL fragment body a custom effect installs." })
5955
- });
6456
+ function spriteClearColor(app) {
6457
+ const { clearColor } = app.settings.section(RENDERING_SETTINGS_SECTION);
6458
+ return {
6459
+ r: Color.srgbToLinear(clearColor.r),
6460
+ g: Color.srgbToLinear(clearColor.g),
6461
+ b: Color.srgbToLinear(clearColor.b),
6462
+ a: clearColor.a
6463
+ };
5956
6464
  }
5957
6465
  //#endregion
5958
6466
  //#region src/tilemap/spawn-objects.ts
@@ -6105,6 +6613,15 @@ function components() {
6105
6613
  ];
6106
6614
  }
6107
6615
  /**
6616
+ * Whether a JSON value is an object rather than an array, a primitive, or absent.
6617
+ *
6618
+ * @param value - The value read out of the scene file.
6619
+ * @returns `true` when the value can be decoded as a settings block.
6620
+ */
6621
+ function isJsonObject(value) {
6622
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6623
+ }
6624
+ /**
6108
6625
  * Reads a scene file's `settings.twoD` block over the project's own settings.
6109
6626
  *
6110
6627
  * @remarks
@@ -6123,7 +6640,7 @@ function components() {
6123
6640
  */
6124
6641
  function applySceneSettings(app, runtime, base, scene) {
6125
6642
  const block = scene.settings?.[TWO_D_SETTINGS_SECTION];
6126
- if (block === void 0 || block === null || typeof block !== "object" || Array.isArray(block)) return;
6643
+ if (!isJsonObject(block)) return;
6127
6644
  const decoded = decodeProps(twoDSettingsSchema(), block, {
6128
6645
  entity: () => null,
6129
6646
  component: () => null,
@@ -6141,9 +6658,9 @@ function applySceneSettings(app, runtime, base, scene) {
6141
6658
  }
6142
6659
  const value = decoded.value;
6143
6660
  runtime.applySettings({
6144
- mode: value.mode ?? base.mode,
6145
- pixelsPerUnit: value.pixelsPerUnit ?? base.pixelsPerUnit,
6146
- ySort: value.ySort ?? base.ySort
6661
+ mode: Object.hasOwn(block, "mode") && value.mode !== void 0 ? value.mode : base.mode,
6662
+ pixelsPerUnit: Object.hasOwn(block, "pixelsPerUnit") && value.pixelsPerUnit !== void 0 ? value.pixelsPerUnit : base.pixelsPerUnit,
6663
+ ySort: Object.hasOwn(block, "ySort") && value.ySort !== void 0 ? value.ySort : base.ySort
6147
6664
  });
6148
6665
  }
6149
6666
  /**
@@ -6151,7 +6668,6 @@ function applySceneSettings(app, runtime, base, scene) {
6151
6668
  *
6152
6669
  * @param ctx - The registration surface.
6153
6670
  * @param options - What the game passed to `twoD(...)`.
6154
- * @returns The runtime and the service, so `onStart` can reach them without a second lookup.
6155
6671
  */
6156
6672
  function registerTwoD(ctx, options) {
6157
6673
  ctx.registerErrorCodes(TWO_D_ERROR_MESSAGES);
@@ -6164,7 +6680,7 @@ function registerTwoD(ctx, options) {
6164
6680
  app,
6165
6681
  settings,
6166
6682
  sortingLayers: sorting,
6167
- createRenderer: isHeadless ? null : () => createRegisteredSpriteRenderer(app.lite.engine, settings.mode === "sprite", BLACK),
6683
+ createRenderer: isHeadless ? null : () => createRegisteredSpriteRenderer(app.lite.engine, settings.mode === "sprite", spriteClearColor(app)),
6168
6684
  attachLayer,
6169
6685
  detachLayer,
6170
6686
  destroyRenderer: destroySpriteRenderer
@@ -6184,23 +6700,18 @@ function registerTwoD(ctx, options) {
6184
6700
  ctx.registerAssetLoader(createSpriteAnimationLoader());
6185
6701
  ctx.registerAssetLoader(createTilemapLoader());
6186
6702
  ctx.registerComponents(components());
6703
+ runtime.setSceneHandler((scene) => {
6704
+ applySceneSettings(app, runtime, settings, scene);
6705
+ spawnTileObjects(app, service, scene);
6706
+ });
6707
+ const removeCameraSource = app.renderer.addCameraSource((world) => selectCamera(world) !== null);
6187
6708
  ctx.onDispose(() => {
6709
+ removeCameraSource();
6188
6710
  runtime.dispose();
6189
6711
  });
6190
- return {
6191
- runtime,
6192
- service
6193
- };
6194
6712
  }
6195
- /** The clear colour a `"sprite"`-mode frame starts from. */
6196
- const BLACK = Object.freeze({
6197
- r: 0,
6198
- g: 0,
6199
- b: 0,
6200
- a: 1
6201
- });
6202
6713
  /**
6203
- * Connects the scene hooks and turns on device-lost recovery.
6714
+ * Turns on device-lost recovery.
6204
6715
  *
6205
6716
  * @remarks
6206
6717
  * Recovery is enabled here, in `onStart`, and **before any atlas or layer exists**, because Lite
@@ -6209,11 +6720,8 @@ const BLACK = Object.freeze({
6209
6720
  * the engine exists, but before the first frame — the only window where both conditions hold.
6210
6721
  *
6211
6722
  * @param app - The app being started.
6212
- * @param runtime - The 2D runtime.
6213
- * @param service - The 2D service.
6214
- * @param base - The project's resolved settings, which a scene block is applied over.
6215
6723
  */
6216
- function startTwoD(app, runtime, service, base) {
6724
+ function startTwoD(app) {
6217
6725
  if (!app.isHeadless && app.renderer.features.deviceLostRecovery) enableSpriteDeviceLostRecovery(app.lite.engine, () => {
6218
6726
  app.log.info("2D sprite resources recovered after device loss.");
6219
6727
  }, (error) => {
@@ -6225,10 +6733,6 @@ function startTwoD(app, runtime, service, base) {
6225
6733
  component: null
6226
6734
  });
6227
6735
  });
6228
- app.world.onSceneLoaded.connect((scene) => {
6229
- applySceneSettings(app, runtime, base, scene);
6230
- spawnTileObjects(app, service, scene);
6231
- });
6232
6736
  }
6233
6737
  /**
6234
6738
  * The `@ignifx/2d` extension factory.
@@ -6248,20 +6752,16 @@ function startTwoD(app, runtime, service, base) {
6248
6752
  */
6249
6753
  const twoD = defineExtension((raw) => {
6250
6754
  const options = raw ?? {};
6251
- let runtime = null;
6252
- let service = null;
6253
6755
  return {
6254
6756
  name: "@ignifx/2d",
6255
6757
  version: VERSION,
6256
6758
  engine: ">=0.0.0 <1.0.0",
6257
6759
  requires: ["@ignifx/core"],
6258
6760
  register(ctx) {
6259
- const built = registerTwoD(ctx, options);
6260
- runtime = built.runtime;
6261
- service = built.service;
6761
+ registerTwoD(ctx, options);
6262
6762
  },
6263
6763
  onStart(app) {
6264
- if (runtime !== null && service !== null) startTwoD(app, runtime, service, runtime.settings);
6764
+ startTwoD(app);
6265
6765
  }
6266
6766
  };
6267
6767
  });
@@ -6289,7 +6789,7 @@ const twoD = defineExtension((raw) => {
6289
6789
  function spriteAtlasFileSchema() {
6290
6790
  return defineSchema({
6291
6791
  format: str(SPRITE_ATLAS_FORMAT, { tooltip: "Always ignifx.spriteatlas." }),
6292
- version: u32(1, { tooltip: "The document version this build reads." }),
6792
+ formatVersion: u32(1, { tooltip: "The document version this build reads." }),
6293
6793
  image: str("", { tooltip: "The image address, relative to this document." }),
6294
6794
  sampling: enumOf(["linear", "nearest"], "linear", { tooltip: "Min/mag filter; nearest for pixel art." }),
6295
6795
  premultipliedAlpha: bool(false, { tooltip: "Whether the image's RGB is already multiplied by its alpha." }),
@@ -6319,7 +6819,7 @@ function spriteAtlasFileSchema() {
6319
6819
  x: 0,
6320
6820
  y: 0
6321
6821
  }, { tooltip: "The untrimmed size, when the packer trimmed the frame." })
6322
- }), [], { tooltip: "The frames, in the order they are indexed." })
6822
+ }), [], { tooltip: "The frames, in the order they are indexed. Each is a record of name (str, what #frame: addresses), x/y (f32, the top-left corner in image pixels), w/h (f32, the size in image pixels), pivot (vec2 in [0,1] of the frame; [0,0] is top-left) and sourceSize (vec2, the untrimmed size when the packer trimmed the frame)." })
6323
6823
  });
6324
6824
  }
6325
6825
  /**
@@ -6332,13 +6832,13 @@ function spriteAtlasFileSchema() {
6332
6832
  function spriteAnimationFileSchema() {
6333
6833
  return defineSchema({
6334
6834
  format: str(SPRITE_ANIMATION_FORMAT, { tooltip: "Always ignifx.spriteanimation." }),
6335
- version: u32(1, { tooltip: "The document version this build reads." }),
6835
+ formatVersion: u32(1, { tooltip: "The document version this build reads." }),
6336
6836
  atlas: str("", { tooltip: "The .atlas.json address, relative to this document." }),
6337
6837
  clips: array(record({
6338
6838
  name: str("", { tooltip: "The clip's name; what SpriteAnimator.play takes." }),
6339
- frames: array(str(), [], { tooltip: "Atlas frame names, in play order." }),
6340
- from: str("", { tooltip: "The first frame of a contiguous atlas range, when frames is empty." }),
6341
- to: str("", { tooltip: "The last frame of the range, inclusive." }),
6839
+ frames: array(str(), [], { tooltip: "Atlas frame names, in play order; they need not be adjacent in the atlas." }),
6840
+ from: str("", { tooltip: "The atlas frame whose INDEX starts the range, when frames is empty. Every atlas index between from and to is played, so the two must bracket a contiguous run." }),
6841
+ to: str("", { tooltip: "The atlas frame whose INDEX ends the range, inclusive; an index below from plays it backwards." }),
6342
6842
  fps: f32(12, {
6343
6843
  min: Number.EPSILON,
6344
6844
  tooltip: "Frames per second."
@@ -6348,7 +6848,7 @@ function spriteAnimationFileSchema() {
6348
6848
  frame: u32(0, { tooltip: "The zero-based index within the clip, not the atlas." }),
6349
6849
  name: str("", { tooltip: "The name emitted on SpriteAnimator.onEvent." })
6350
6850
  }), [], { tooltip: "Events fired as the clip passes a frame." })
6351
- }), [], { tooltip: "The clips; the first is the default." })
6851
+ }), [], { tooltip: "The clips; the first is the default. Each is a record of name (str, what SpriteAnimator.play takes), frames (array of atlas frame names in play order, which need not be adjacent), from/to (str: an INCLUSIVE range over atlas INDICES used when frames is empty — every index between the two endpoints is played, in atlas order, so a range over non-adjacent frames plays everything in between; to before from plays it backwards), fps (f32, default 12), loop (bool, default true) and events (array of { frame: u32 index within the clip, not the atlas; name: str })." })
6352
6852
  });
6353
6853
  }
6354
6854
  /**
@@ -6361,7 +6861,7 @@ function spriteAnimationFileSchema() {
6361
6861
  function tilemapFileSchema() {
6362
6862
  return defineSchema({
6363
6863
  format: str(TILEMAP_FORMAT, { tooltip: "Always ignifx.tilemap." }),
6364
- version: u32(1, { tooltip: "The document version this build reads." }),
6864
+ formatVersion: u32(1, { tooltip: "The document version this build reads." }),
6365
6865
  tileWidth: f32(32, {
6366
6866
  min: Number.EPSILON,
6367
6867
  tooltip: "One cell's width, in pixels."
@@ -6455,7 +6955,7 @@ function describeSpriteAnimationFormat() {
6455
6955
  return describeSchema("ignifx/spriteanimation-file", spriteAnimationFileSchema(), {
6456
6956
  title: "Sprite animation",
6457
6957
  format: SPRITE_ANIMATION_FORMAT,
6458
- description: "Clips of atlas frames with a rate, a loop flag, and frame events."
6958
+ description: "Clips of atlas frames with a rate, a loop flag, and frame events. A clip names its frames either as an explicit `frames` list of atlas frame names, played in the order written and free to skip around the sheet, or as a `from`/`to` pair — and that pair is an **inclusive range over atlas indices**, not two endpoints joined by name: every index between the two is played, in atlas order, so a range whose endpoints are not adjacent in the sheet plays whatever the packer put between them. Use `frames` for a run that is not contiguous."
6459
6959
  });
6460
6960
  }
6461
6961
  /**
@@ -7150,7 +7650,7 @@ function tiledPropertiesToRecord(properties) {
7150
7650
  * global tile id. ignifx has no per-cell flip yet, so those bits are **masked off** and the tile
7151
7651
  * draws unflipped; without the mask a flipped tile would resolve to a nonsensical tileset.
7152
7652
  *
7153
- * The frame names this importer emits are `` `${tilesetName}_${localTileIndex}` `` — the same names
7653
+ * The frame names this importer emits are `<tilesetName>_<localTileIndex>` — the same names
7154
7654
  * the grid-atlas generator gives the frames it cuts out of the tileset image, which is the contract
7155
7655
  * that lets `TilemapRenderer` look a tile's sprite up without a side table.
7156
7656
  *
@@ -7494,6 +7994,6 @@ function readArray(source, key) {
7494
7994
  return isUnknownArray(value) ? value : [];
7495
7995
  }
7496
7996
  //#endregion
7497
- export { Camera2D, Camera2DFollow, DEFAULT_CHUNK_SIZE, DEFAULT_CLIP_FPS, DEFAULT_ORTHOGRAPHIC_SIZE, DEFAULT_PIXELS_PER_UNIT, DEFAULT_REFERENCE_RESOLUTION, DEFAULT_SORTING_LAYER, EMPTY_TILE_ID, LDTK_DEFAULT_INTGRID_COLLIDERS, LDTK_INTGRID_TILESET_NAME, ParallaxLayer, SORTING_LAYER_ORDER_STEP, SPRITE_ANIMATION_ASSET_TYPE, SPRITE_ANIMATION_FILE_EXTENSIONS, SPRITE_ANIMATION_FORMAT, SPRITE_ANIMATION_FORMAT_VERSION, SPRITE_ATLAS_ASSET_TYPE, SPRITE_ATLAS_FILE_EXTENSIONS, SPRITE_ATLAS_FORMAT, SPRITE_ATLAS_FORMAT_VERSION, SPRITE_BLEND_MODES, SPRITE_EFFECT_KINDS, SPRITE_FRAME_FRAGMENT_PREFIX, SortingLayerTable, SpriteAnimationAsset, SpriteAnimator, SpriteAtlasAsset, SpriteLayerEffect, SpriteLayerRegistry, SpriteRenderer, TILEMAP_ASSET_TYPE, TILEMAP_FILE_EXTENSIONS, TILEMAP_FORMAT, TILEMAP_FORMAT_VERSION, TINT_EFFECT_WGSL, TWO_D_ANIMATION_ORDER, TWO_D_ERROR_MESSAGES, TWO_D_MODES, TWO_D_SETTINGS_SECTION, TWO_D_SYNC_ORDER, Tilemap, TilemapAsset, TilemapRenderer, TwoDAnimationSystem, TwoDErrorCode, TwoDService, TwoDSyncSystem, VERSION, asepriteFrameName, createSpriteAnimationLoader, createSpriteAtlasLoader, createTilemapLoader, decodeTileRle, defaultTwoDSettings, defineSpriteAnimation, defineSpriteAtlas, defineTilemap, describeSchemas, describeSpriteAnimationFormat, describeSpriteAtlasFormat, describeTilemapFormat, describeTwoDSchemas, encodeTileRle, fieldInstancesToRecord, findTileset, gridAtlas, importAsepriteAnimations, importAsepriteAtlas, importLdtkLevel, importTexturePackerAtlas, importTiledMap, isFullCellSolid, mergeTileCollisions, normalisePath, parseSpriteFragment, pivotedPositionToRef, pixelsToWorldToRef, resolveClipFrames, resolveRelative, selectCamera, sizeForZoom, snapPixel, snapZoomToInteger, spawnTilemapObjects, spriteAnimationFileSchema, spriteAnimationJsonSchema, spriteAtlasFileSchema, spriteAtlasJsonSchema, spriteLayerKey, spriteRotationFromLite, spriteRotationToLite, tileCollisionInfo, tileFrameName, tiledPropertiesToRecord, tilemapFileSchema, tilemapJsonSchema, twoD, twoDError, twoDSettingsSchema, viewRotationToLite, worldToPixelsToRef, zoomForSize };
7997
+ export { Camera2D, Camera2DFollow, DEFAULT_CHUNK_SIZE, DEFAULT_CLIP_FPS, DEFAULT_ORTHOGRAPHIC_SIZE, DEFAULT_PIXELS_PER_UNIT, DEFAULT_REFERENCE_RESOLUTION, DEFAULT_SORTING_LAYER, EMPTY_TILE_ID, LDTK_DEFAULT_INTGRID_COLLIDERS, LDTK_INTGRID_TILESET_NAME, ParallaxLayer, SORTING_LAYER_ORDER_STEP, SPRITE_ANIMATION_ASSET_TYPE, SPRITE_ANIMATION_FILE_EXTENSIONS, SPRITE_ANIMATION_FORMAT, SPRITE_ANIMATION_FORMAT_VERSION, SPRITE_ATLAS_ASSET_TYPE, SPRITE_ATLAS_FILE_EXTENSIONS, SPRITE_ATLAS_FORMAT, SPRITE_ATLAS_FORMAT_VERSION, SPRITE_BLEND_MODES, SPRITE_EFFECT_KINDS, SPRITE_FRAME_FRAGMENT_PREFIX, SortingLayerTable, SpriteAnimationAsset, SpriteAnimator, SpriteAtlasAsset, SpriteLayerEffect, SpriteLayerRegistry, SpriteRenderer, TILEMAP_ASSET_TYPE, TILEMAP_FILE_EXTENSIONS, TILEMAP_FORMAT, TILEMAP_FORMAT_VERSION, TINT_EFFECT_WGSL, TWO_D_ANIMATION_ORDER, TWO_D_ERROR_MESSAGES, TWO_D_MODES, TWO_D_SETTINGS_SECTION, TWO_D_SYNC_ORDER, Tilemap, TilemapAsset, TilemapRenderer, TwoDAnimationSystem, TwoDErrorCode, TwoDService, TwoDSyncSystem, VERSION, asepriteFrameName, createSpriteAnimationLoader, createSpriteAtlasLoader, createTilemapLoader, decodeTileRle, defaultTwoDSettings, defineSpriteAnimation, defineSpriteAtlas, defineTilemap, describeSchemas, describeSpriteAnimationFormat, describeSpriteAtlasFormat, describeTilemapFormat, describeTwoDSchemas, encodeTileRle, fieldInstancesToRecord, findTileset, gridAtlas, importAsepriteAnimations, importAsepriteAtlas, importLdtkLevel, importTexturePackerAtlas, importTiledMap, isFullCellSolid, mergeTileCollisions, normalisePath, parseSpriteFragment, pivotedPositionToRef, pixelsToWorldToRef, readVec2, resolveClipFrames, resolveRelative, selectCamera, sizeForZoom, snapPixel, snapZoomToInteger, spawnTilemapObjects, spriteAnimationFileSchema, spriteAnimationJsonSchema, spriteAtlasFileSchema, spriteAtlasJsonSchema, spriteLayerKey, spriteRotationFromLite, spriteRotationToLite, tileCollisionInfo, tileFrameName, tiledPropertiesToRecord, tilemapFileSchema, tilemapJsonSchema, twoD, twoDError, twoDSettingsSchema, viewRotationToLite, worldToPixelsToRef, zoomForSize };
7498
7998
 
7499
7999
  //# sourceMappingURL=index.js.map