@ignifx/2d 0.1.0 → 0.2.1

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["CENTRE_PIVOT","CENTRE_PIVOT","failImport","isObject","isUnknownArray","isFiniteNumber","readVec2","isUnknownArray","CENTRE_PIVOT","RAD_TO_DEG","IMPORTER_NAME","isRecord","readArray","defaultAtlasFor","readString","readNumber","readTileset","isUnknownArray"],"sources":["../src/augmentation.ts","../src/errors.ts","../src/atlas/definition.ts","../src/atlas/sprite-atlas-asset.ts","../src/lite/sprite-layer.ts","../src/service/sorting-layers.ts","../src/sprite/sprite-renderer.ts","../src/animation/definition.ts","../src/animation/sprite-animation-asset.ts","../src/animation/sprite-animator.ts","../src/animation/animation-system.ts","../src/atlas/importers.ts","../src/animation/importers.ts","../src/assets/relative.ts","../src/animation/loader.ts","../src/lite/atlas.ts","../src/lite/gpu/texture.ts","../src/atlas/loader.ts","../src/math/coords.ts","../src/camera/camera-2d.ts","../src/camera/camera-2d-follow.ts","../src/lite/gpu/sprite-renderer.ts","../src/sprite/parallax-layer.ts","../src/sprite/sprite-layer-effect.ts","../src/tilemap/definition.ts","../src/tilemap/tilemap-renderer.ts","../src/service/layer-registry.ts","../src/service/runtime.ts","../src/tilemap/collision-merge.ts","../src/tilemap/tilemap-asset.ts","../src/tilemap/tilemap.ts","../src/service/sync-system.ts","../src/service/two-d-service.ts","../src/settings.ts","../src/tilemap/spawn-objects.ts","../src/version.ts","../src/extension.ts","../src/file-schemas.ts","../src/schemas.ts","../src/tilemap/importers/ldtk.ts","../src/tilemap/importers/tiled.ts"],"sourcesContent":["import type { TwoDService } from \"./service/two-d-service.js\";\nimport type { ExtensionContext } from \"@ignifx/core\";\n\n/**\n * The typed entry point (`docs/architecture/03-scripting-and-components.md` §7). Declaration\n * merging is what makes `this.app.twoD` fully typed when `@ignifx/2d` is installed and a compile\n * error when it is not.\n *\n * Two mechanics carry over from `@ignifx/input`, both measured rather than assumed:\n *\n * - The module **must** import something from `@ignifx/core`. A `declare module \"@ignifx/core\"`\n * block in a file that never imports the module is `TS2664: Invalid module name in augmentation`\n * under both `tsc --build` and TypeDoc; importing the `ExtensionContext` type used below is\n * enough to bring the module into the program.\n * - The barrel **must** name this module in a bare `import \"./augmentation.js\"`. Declaration\n * bundling drops a module whose only exports are unreferenced from the public surface, which\n * silently takes the augmentation out of `dist/index.d.ts` with it. The bare import is a\n * type-only side effect: the emitted JavaScript keeps no statement for it, so `sideEffects: false`\n * stays honest.\n */\n\ndeclare module \"@ignifx/core\" {\n interface App {\n /**\n * The 2D service (`docs/architecture/11-2d-toolkit.md` §1): the pixels-per-unit conversion, the\n * active `Camera2D`, sprite picking, the sprite-layer diagnostics, and the Lite escape hatch.\n */\n readonly twoD: TwoDService;\n }\n}\n\n/**\n * Defines `app.twoD`, pairing with the augmentation above.\n *\n * @param ctx - The extension registration surface.\n * @param service - The service the property returns.\n * @throws IgnifxError with code `IGX-0401` when something already defined `app.twoD`.\n *\n * @internal\n */\nexport function defineTwoDAppProperty(ctx: ExtensionContext, service: TwoDService): void {\n ctx.defineAppProperty(\"twoD\", (): unknown => service);\n}\n","import { IgnifxError } from \"@ignifx/core\";\nimport type { ErrorContext } from \"@ignifx/core\";\n\n/**\n * The diagnostic codes `@ignifx/2d` owns. The 2D subsystem sits in the `11` range of\n * `docs/architecture/15-devtools-and-diagnostics.md` §1, so every code reads `IGX-11##`.\n *\n * The `11` range is shared with `@ignifx/physics-2d`, which owns `IGX-1101` (registering both\n * `physics()` and `physics2d()` on one world — `docs/architecture/11-2d-toolkit.md` §8) and the\n * codes from `IGX-1130` up. The 2D toolkit owns `IGX-1102` through `IGX-1129`.\n *\n * The table lives here rather than in `@ignifx/core`'s `CoreErrorCode`: an extension owns its own\n * codes and hands them to the app through `ExtensionContext.registerErrorCodes`\n * (`docs/architecture/04-extensions.md` §3).\n */\n\n/**\n * Every diagnostic code `@ignifx/2d` can throw or log, keyed by an intention-revealing name so call\n * sites read as prose and the compiler catches typos (coding standards §5.2).\n *\n * @example\n * ```ts\n * throw twoDError(TwoDErrorCode.unknownSortingLayer, \"Foreground is not a declared sorting layer.\", {\n * context: { sortingLayer: \"Foreground\" },\n * });\n * ```\n *\n * @public\n */\nexport const TwoDErrorCode = {\n /** An atlas frame has no one-pixel extruded border, which a pixel-perfect camera will bleed. */\n atlasFrameNotExtruded: \"IGX-1102\",\n /** A `.atlas.json` file is not an `ignifx.spriteatlas` document this build can read. */\n invalidAtlasFile: \"IGX-1103\",\n /** A `.spriteanim.json` file is not an `ignifx.spriteanimation` document this build can read. */\n invalidAnimationFile: \"IGX-1104\",\n /** A `.tilemap.json` file is not an `ignifx.tilemap` document this build can read. */\n invalidTilemapFile: \"IGX-1105\",\n /** A sprite address names a frame the atlas does not declare. */\n unknownFrame: \"IGX-1106\",\n /** A component named a sorting layer the `sortingLayers` settings section does not declare. */\n unknownSortingLayer: \"IGX-1107\",\n /** `SpriteAnimator.play` named a clip the animation asset does not declare. */\n unknownClip: \"IGX-1108\",\n /** A tilemap importer was handed a document it cannot read, or an unsupported projection. */\n unsupportedImport: \"IGX-1109\",\n /** `app.twoD.registerTileObjectFactory` was called twice for one object type. */\n duplicateObjectFactory: \"IGX-1110\",\n /** A tile coordinate is outside the tilemap layer's bounds. */\n tileOutOfRange: \"IGX-1111\",\n /** A second `twoD()` extension was registered on one app. */\n duplicateExtension: \"IGX-1112\",\n /** A `SpriteLayerEffect` declared the `custom` kind without a WGSL fragment body. */\n missingShaderSource: \"IGX-1113\",\n} as const;\n\n/**\n * The union of the codes the `TwoDErrorCode` table declares.\n *\n * @public\n */\nexport type TwoDErrorCode = (typeof TwoDErrorCode)[keyof typeof TwoDErrorCode];\n\n/**\n * The one-line message template of every code, as `ExtensionContext.registerErrorCodes` wants it.\n * Context keys appear in braces, matching the core table's convention.\n *\n * @public\n */\nexport const TWO_D_ERROR_MESSAGES: Readonly<Record<string, string>> = Object.freeze({\n \"IGX-1102\": \"Atlas frame {frame} has no 1-px extruded border; a pixel-perfect camera will bleed it.\",\n \"IGX-1103\": \"{file} is not an ignifx.spriteatlas document this build can read.\",\n \"IGX-1104\": \"{file} is not an ignifx.spriteanimation document this build can read.\",\n \"IGX-1105\": \"{file} is not an ignifx.tilemap document this build can read.\",\n \"IGX-1106\": \"{atlas} declares no frame named {frame}.\",\n \"IGX-1107\": \"{sortingLayer} is not a sorting layer declared by the sortingLayers settings section.\",\n \"IGX-1108\": \"{asset} declares no clip named {clip}.\",\n \"IGX-1109\": \"{importer} cannot read this document: {reason}.\",\n \"IGX-1110\": \"A tile object factory for {type} is already registered.\",\n \"IGX-1111\": \"Cell {x},{y} is outside layer {layer}.\",\n \"IGX-1112\": \"The twoD() extension is already registered on this app.\",\n \"IGX-1113\": \"A custom SpriteLayerEffect needs a WGSL fragment body in its shader field.\",\n});\n\n/**\n * Options accepted by {@link twoDError}: the same subset of `IgnifxErrorOptions` this package uses.\n *\n * @public\n */\nexport interface TwoDErrorOptions {\n /** Identifiers that locate the failure. */\n readonly context?: ErrorContext;\n /** One sentence telling the developer what to do about it. */\n readonly hint?: string;\n /** The failure being wrapped, when there is one. */\n readonly cause?: unknown;\n}\n\n/**\n * Builds an `IgnifxError` carrying one of this package's codes.\n *\n * @param code - The code from the `TwoDErrorCode` table.\n * @param message - The actionable development sentence.\n * @param options - Context identifiers, a remedy hint, and the wrapped cause.\n * @returns The error to throw or to reject with.\n *\n * @example\n * ```ts\n * throw twoDError(TwoDErrorCode.unknownClip, \"hero.spriteanim.json declares no clip named jump.\", {\n * context: { asset: \"hero.spriteanim.json\", clip: \"jump\" },\n * });\n * ```\n *\n * @public\n */\nexport function twoDError(code: TwoDErrorCode, message: string, options?: TwoDErrorOptions): IgnifxError {\n return new IgnifxError(code, message, {\n ...(options?.context === undefined ? {} : { context: options.context }),\n ...(options?.hint === undefined ? {} : { hint: options.hint }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The `ignifx.spriteatlas` document — the `.atlas.json` file that names an image and the frame\n * rectangles inside it (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `11-2d-toolkit.md` §2.3).\n *\n * Frames are in **image pixels with a top-left origin**, which is what every atlas packer emits.\n * The conversion into Lite's normalised UVs happens in the loader, once.\n */\n\n/**\n * The `format` discriminator every `.atlas.json` document carries.\n *\n * @public\n */\nexport const SPRITE_ATLAS_FORMAT = \"ignifx.spriteatlas\";\n\n/**\n * The document version this build reads and writes.\n *\n * @public\n */\nexport const SPRITE_ATLAS_FORMAT_VERSION = 1;\n\n/**\n * The asset type name the loader registers.\n *\n * @public\n */\nexport const SPRITE_ATLAS_ASSET_TYPE = \"spriteatlas\";\n\n/**\n * The address suffixes that select the sprite-atlas loader.\n *\n * @public\n */\nexport const SPRITE_ATLAS_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".atlas.json\"]);\n\n/**\n * The fragment prefix that addresses one frame: `\"sprites/hero.atlas.json#frame:idle_0\"`.\n *\n * @public\n */\nexport const SPRITE_FRAME_FRAGMENT_PREFIX = \"frame:\";\n\n/**\n * A 2D value as a document may write it: `[x, y]`, the form `@ignifx/core` encodes every `vec2`\n * field into a file as (`schema/encode.ts` line 393), or `{ x, y }`, the form an importer emits.\n *\n * @public\n */\nexport type Vec2Json = Vec2Like | readonly [number, number];\n\n/**\n * Normalises either written form of a 2D value.\n *\n * @param value - What the document wrote, or `undefined`.\n * @param fallback - What to use when the document wrote nothing.\n * @returns The normalised vector.\n *\n * @public\n */\nexport function readVec2(value: Vec2Json | undefined, fallback: Vec2Like): Vec2Like {\n if (value === undefined) {\n return fallback;\n }\n if (isPair(value)) {\n return { x: value[0], y: value[1] };\n }\n return typeof value.x === \"number\" && typeof value.y === \"number\" ? { x: value.x, y: value.y } : fallback;\n}\n\n/**\n * Whether a written 2D value is the `[x, y]` array form.\n *\n * @param value - The value the document carried.\n * @returns `true` when it is a two-number array.\n */\nfunction isPair(value: Vec2Json): value is readonly [number, number] {\n return Array.isArray(value) && typeof value[0] === \"number\" && typeof value[1] === \"number\";\n}\n\n/**\n * One frame rectangle, in image pixels with a top-left origin.\n *\n * @public\n */\nexport interface SpriteFrameDefinition {\n /** The frame's name, unique within the document; what `#frame:` addresses. */\n readonly name: string;\n /** The left edge, in image pixels. */\n readonly x: number;\n /** The top edge, in image pixels. */\n readonly y: number;\n /** The width, in image pixels. */\n readonly w: number;\n /** The height, in image pixels. */\n readonly h: number;\n /**\n * The pivot in `[0, 1]` of the frame — `[0, 0]` top-left, `[0.5, 0.5]` centre, `[1, 1]`\n * bottom-right. Defaults to the centre. Written either as `[x, y]` or as `{ x, y }`.\n */\n readonly pivot?: Vec2Json;\n /** The untrimmed source size, when the packer trimmed transparent margins. Defaults to `w`/`h`. */\n readonly sourceSize?: Vec2Json;\n}\n\n/**\n * The parsed `.atlas.json` document.\n *\n * @example\n * ```ts\n * const atlas = defineSpriteAtlas({\n * image: \"2d/hero.png\",\n * sampling: \"nearest\",\n * frames: [{ name: \"idle_0\", x: 0, y: 0, w: 32, h: 32, pivot: { x: 0.5, y: 1 } }],\n * });\n * ```\n *\n * @public\n */\nexport interface SpriteAtlasDefinition {\n /** Always `\"ignifx.spriteatlas\"`. */\n readonly format: typeof SPRITE_ATLAS_FORMAT;\n /** Always `1` in this build. */\n readonly formatVersion: number;\n /** The address of the image the frames are cut from. */\n readonly image: string;\n /** The min/mag filter. `\"nearest\"` is what pixel art wants. Defaults to `\"linear\"`. */\n readonly sampling: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha: boolean;\n /** The frames, in the order they are indexed. */\n readonly frames: readonly SpriteFrameDefinition[];\n}\n\n/**\n * What {@link defineSpriteAtlas} accepts: the document with every defaulted field optional.\n *\n * @public\n */\nexport interface SpriteAtlasInput {\n /** Always `\"ignifx.spriteatlas\"` when present. */\n readonly format?: string;\n /** The document version. */\n readonly formatVersion?: number;\n /** The address of the image the frames are cut from. */\n readonly image: string;\n /** The min/mag filter. Defaults to `\"linear\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image is premultiplied. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n /** The frames. */\n readonly frames: readonly SpriteFrameDefinition[];\n}\n\n/**\n * Fills in the defaults of an atlas document and checks the invariants a loader relies on.\n *\n * @param input - The document, as authored or as an importer emitted it.\n * @param address - What to name in an error; defaults to `\"<inline>\"`.\n * @returns The complete document.\n * @throws IgnifxError with code `IGX-1103` when the format tag, the version, the image address, or\n * a frame rectangle is wrong, or two frames share a name.\n *\n * @public\n */\nexport function defineSpriteAtlas(input: SpriteAtlasInput, address = \"<inline>\"): SpriteAtlasDefinition {\n const fail = (reason: string): never => {\n throw twoDError(\n TwoDErrorCode.invalidAtlasFile,\n `${address} is not a readable ignifx.spriteatlas document: ${reason}.`,\n {\n context: { file: address },\n hint: \"Regenerate it with `ignifx import atlas`, or check the format and version fields.\",\n },\n );\n };\n if (input.format !== undefined && input.format !== SPRITE_ATLAS_FORMAT) {\n fail(`its format is ${input.format}, not ${SPRITE_ATLAS_FORMAT}`);\n }\n if (input.formatVersion !== undefined && input.formatVersion !== SPRITE_ATLAS_FORMAT_VERSION) {\n fail(\n `its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(SPRITE_ATLAS_FORMAT_VERSION)}`,\n );\n }\n if (typeof input.image !== \"string\" || input.image === \"\") {\n fail(\"it names no image\");\n }\n if (!Array.isArray(input.frames) || input.frames.length === 0) {\n fail(\"it declares no frames\");\n }\n const seen = new Set<string>();\n for (let index = 0; index < input.frames.length; index += 1) {\n const frame = input.frames[index];\n if (frame === undefined || typeof frame.name !== \"string\" || frame.name === \"\") {\n fail(`frame ${String(index)} has no name`);\n continue;\n }\n if (seen.has(frame.name)) {\n fail(`two frames are named ${frame.name}`);\n }\n seen.add(frame.name);\n if (!(frame.w > 0) || !(frame.h > 0)) {\n fail(`frame ${frame.name} has a non-positive size`);\n }\n if (!(frame.x >= 0) || !(frame.y >= 0)) {\n fail(`frame ${frame.name} starts outside the image`);\n }\n }\n const frames: SpriteFrameDefinition[] = [];\n for (let index = 0; index < input.frames.length; index += 1) {\n const frame = input.frames[index];\n if (frame === undefined) {\n continue;\n }\n // Normalise both written forms of a 2D value once, here, so nothing downstream has to care.\n // `sourceSize` keeps its absence: a frame that declares none is untrimmed, and saying so is\n // information an importer round trip should not invent.\n frames.push({\n ...frame,\n pivot: readVec2(frame.pivot, CENTRE_PIVOT),\n ...(frame.sourceSize === undefined ? {} : { sourceSize: readVec2(frame.sourceSize, { x: frame.w, y: frame.h }) }),\n });\n }\n return {\n format: SPRITE_ATLAS_FORMAT,\n formatVersion: SPRITE_ATLAS_FORMAT_VERSION,\n image: input.image,\n sampling: input.sampling ?? \"linear\",\n premultipliedAlpha: input.premultipliedAlpha ?? false,\n frames,\n };\n}\n\n/**\n * The pivot a frame that declares none uses.\n */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * Splits a sprite address into its atlas address and its frame name.\n *\n * @param fragment - The part after `#`, or `null` for a bare atlas address.\n * @returns The frame name, or `null` when the fragment does not select a frame.\n *\n * @example\n * ```ts\n * parseSpriteFragment(\"frame:idle_0\"); // \"idle_0\"\n * ```\n *\n * @public\n */\nexport function parseSpriteFragment(fragment: string | null): string | null {\n if (fragment === null || !fragment.startsWith(SPRITE_FRAME_FRAGMENT_PREFIX)) {\n return null;\n }\n const name = fragment.slice(SPRITE_FRAME_FRAGMENT_PREFIX.length);\n return name === \"\" ? null : name;\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { readVec2, SPRITE_ATLAS_ASSET_TYPE } from \"./definition.js\";\nimport type { SpriteAtlasDefinition } from \"./definition.js\";\nimport type { LiteSpriteAtlas, LiteSpriteFrame } from \"../lite/types.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The value a `.atlas.json` address loads to: the parsed document, the Lite `SpriteAtlas` built\n * from it, and a name-to-index map so `#frame:` addressing is a hash lookup rather than a scan\n * (`docs/architecture/11-2d-toolkit.md` §2.3).\n */\n\n/**\n * The Babylon Lite objects a {@link SpriteAtlasAsset} owns.\n *\n * @public\n */\nexport interface SpriteAtlasAssetLiteHandles {\n /** The Lite atlas, or `null` under a headless app, which uploads nothing. */\n readonly atlas: LiteSpriteAtlas | null;\n}\n\n/**\n * One frame of a loaded atlas, as game code sees it.\n *\n * @public\n */\nexport interface SpriteFrameInfo {\n /** The frame's name. */\n readonly name: string;\n /** Its index in the atlas, which is what Lite addresses frames by. */\n readonly index: number;\n /** Its drawn width, in image pixels. */\n readonly widthPx: number;\n /** Its drawn height, in image pixels. */\n readonly heightPx: number;\n /** Its pivot in `[0, 1]` of the frame, `[0, 0]` top-left. */\n readonly pivot: Vec2Like;\n}\n\n/**\n * A loaded sprite atlas.\n *\n * @remarks\n * Under a headless app the document is parsed and every frame is queryable, but `lite.atlas` is\n * `null` — nothing is uploaded (`docs/architecture/07-rendering.md` §6). That is what lets a\n * headless test assert frame counts, pivots, and animation timing without a GPU.\n *\n * @example\n * ```ts\n * const handle = app.assets.load<SpriteAtlasAsset>(\"2d/hero.atlas.json\");\n * const atlas = await handle.promise;\n * atlas.frameIndex(\"idle_0\"); // 0\n * ```\n *\n * @public\n */\nexport class SpriteAtlasAsset {\n /** The type name the asset service registers sprite atlases under. */\n static assetType: string = SPRITE_ATLAS_ASSET_TYPE;\n\n /** The address the atlas was loaded from. */\n readonly address: string;\n\n /** The parsed `.atlas.json` document. */\n readonly definition: SpriteAtlasDefinition;\n\n #atlas: LiteSpriteAtlas | null;\n\n readonly #indices: ReadonlyMap<string, number>;\n\n readonly #release: (() => void) | null;\n\n /**\n * Wraps a parsed atlas. The `spriteatlas` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The parsed document.\n * @param atlas - The Lite atlas, or `null` under a headless app.\n * @param release - Frees the GPU texture, or `null` when there is nothing to free.\n *\n * @internal\n */\n constructor(\n address: string,\n definition: SpriteAtlasDefinition,\n atlas: LiteSpriteAtlas | null,\n release: (() => void) | null,\n ) {\n this.address = address;\n this.definition = definition;\n this.#atlas = atlas;\n this.#release = release;\n const indices = new Map<string, number>();\n for (let index = 0; index < definition.frames.length; index += 1) {\n const frame = definition.frames[index];\n if (frame !== undefined) {\n indices.set(frame.name, index);\n }\n }\n this.#indices = indices;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch\n * (`CONSTITUTION.md` §3.4).\n *\n * @returns The Lite atlas, or `null` under a headless app.\n */\n get lite(): SpriteAtlasAssetLiteHandles {\n return { atlas: this.#atlas };\n }\n\n /**\n * How many frames the atlas declares.\n *\n * @returns The frame count.\n */\n get frameCount(): number {\n return this.definition.frames.length;\n }\n\n /**\n * Looks a frame up by name.\n *\n * @param name - The frame name.\n * @returns The index, or `-1` when the atlas has no such frame.\n */\n frameIndex(name: string): number {\n return this.#indices.get(name) ?? -1;\n }\n\n /**\n * Looks a frame up by name and refuses to guess.\n *\n * @param name - The frame name.\n * @returns The index.\n * @throws IgnifxError with code `IGX-1106` when the atlas declares no such frame.\n */\n requireFrame(name: string): number {\n const index = this.#indices.get(name);\n if (index === undefined) {\n throw twoDError(TwoDErrorCode.unknownFrame, `${this.address} declares no frame named ${name}.`, {\n context: { atlas: this.address, frame: name },\n hint: `Known frames: ${this.frameNames().join(\", \")}.`,\n });\n }\n return index;\n }\n\n /**\n * Every frame name, in index order.\n *\n * @returns A freshly allocated array.\n */\n frameNames(): readonly string[] {\n const names: string[] = [];\n for (let index = 0; index < this.definition.frames.length; index += 1) {\n const frame = this.definition.frames[index];\n if (frame !== undefined) {\n names.push(frame.name);\n }\n }\n return names;\n }\n\n /**\n * Describes one frame.\n *\n * @param index - The frame index.\n * @returns The frame, or `null` when the index is out of range.\n */\n frame(index: number): SpriteFrameInfo | null {\n const declared = this.definition.frames[index];\n if (declared === undefined) {\n return null;\n }\n // `defineSpriteAtlas` normalised both fields, so they are always `{ x, y }` here.\n const pivot = readVec2(declared.pivot, DEFAULT_PIVOT);\n const source = readVec2(declared.sourceSize, { x: declared.w, y: declared.h });\n return { name: declared.name, index, widthPx: source.x, heightPx: source.y, pivot };\n }\n\n /**\n * The Lite frame record, for the sync system.\n *\n * @param index - The frame index.\n * @returns The record, or `null` under a headless app or for an out-of-range index.\n *\n * @internal\n */\n liteFrame(index: number): LiteSpriteFrame | null {\n return this.#atlas?.frames[index] ?? null;\n }\n\n /**\n * Whether the atlas was uploaded to a device at all.\n *\n * @returns `true` once the GPU texture has been given up, or under a headless app.\n */\n get isReleased(): boolean {\n return this.#atlas === null;\n }\n\n /**\n * Frees the GPU texture. The asset service calls this on unload.\n *\n * @internal\n */\n releaseGpu(): void {\n if (this.#atlas === null) {\n return;\n }\n this.#atlas = null;\n this.#release?.();\n }\n}\n\n/** The pivot a frame that declares none uses: the centre. */\nconst DEFAULT_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * A sprite: one frame of one atlas, which is what `SpriteRenderer.sprite` points at.\n *\n * @remarks\n * A bare `\"2d/hero.atlas.json\"` address resolves to frame `0`; the `#frame:` fragment picks another\n * (`docs/architecture/11-2d-toolkit.md` §2.2). The asset service shares the underlying atlas\n * between every fragment of the same address, so ten sprites off one atlas upload one texture.\n *\n * @public\n */\nexport interface SpriteAsset {\n /** The atlas the frame lives in. */\n readonly atlas: SpriteAtlasAsset;\n /** The frame index. */\n readonly frame: number;\n /** The frame's name. */\n readonly name: string;\n}\n","import {\n addSprite2D,\n clearSprite2DLayer,\n createSprite2DCustomShader,\n createSprite2DLayer,\n disableSprite2DYSort,\n enableSprite2DYSort,\n getSprite2DHandleIndex,\n getSprite2DVisibleBoundsToRef,\n isSprite2DHandleAlive,\n pickSprite2D,\n removeSprite2D,\n setSprite2DShaderParams,\n sprite2DScreenToWorldToRef,\n setSprite2DYSortHandleBias,\n spriteBlendAdditive,\n spriteBlendAlpha,\n spriteBlendMultiply,\n spriteBlendOpaque,\n spriteBlendPremultiplied,\n updateSprite2D,\n} from \"@babylonjs/lite\";\nimport type {\n Bounds2D,\n Sprite2DCustomShader,\n Sprite2DHandle,\n Sprite2DLayer,\n Sprite2DProps,\n Sprite2DView,\n SpriteAtlas,\n SpriteBlendMode,\n SpritePickInfo,\n} from \"@babylonjs/lite\";\n\n/**\n * The CPU half of the Babylon Lite sprite adapter (`docs/architecture/07-rendering.md` §7,\n * `11-2d-toolkit.md` §1). Nothing in this module touches `engine._device`: a `Sprite2DLayer` is a\n * plain object holding a `Float32Array` of instance data, and every sprite mutation writes into\n * that array (verified in `@babylonjs/lite@1.27.0`, `lib/sprite/sprite-2d.js` lines 14-48 for\n * `createSprite2DLayer` and 73-200 for `writeInstance`/`addSprite2DIndex`). GPU buffers are\n * allocated lazily by the renderer at draw time, which is why the device-only calls live in\n * `./gpu/sprite-renderer.ts` instead.\n *\n * That split is what makes the sprite maths unit-testable under Node: a test fabricates a\n * `SpriteAtlas` with {@link createDataAtlas} and exercises everything here on the null engine.\n *\n * Everything except the blend-mode table is `@internal`.\n */\n\n/**\n * The blend modes `SpriteRenderer.blend` accepts, in the order an inspector should list them.\n *\n * @public\n */\nexport const SPRITE_BLEND_MODES = [\"alpha\", \"premultiplied\", \"additive\", \"multiply\", \"opaque\"] as const;\n\n/**\n * How a sprite's colour combines with what is already in the framebuffer\n * (`docs/architecture/11-2d-toolkit.md` §2.2).\n *\n * @public\n */\nexport type SpriteBlendName = (typeof SPRITE_BLEND_MODES)[number];\n\n/**\n * Resolves a blend name to the Lite descriptor `createSprite2DLayer` wants.\n *\n * @remarks\n * The descriptors are the module constants `spriteBlendAlpha` (`index.d.ts` 12108),\n * `spriteBlendPremultiplied` (12153), `spriteBlendAdditive` (12102), `spriteBlendMultiply` (12131)\n * and `spriteBlendOpaque` (12147). `SpriteBlendMode` is a type alias of the opaque\n * `SpriteBlendDescriptor` (12122), so the values are compared by identity, never inspected.\n *\n * @param name - The ignifx blend name.\n * @returns The Lite descriptor.\n *\n * @internal\n */\nexport function blendModeFor(name: SpriteBlendName): SpriteBlendMode {\n switch (name) {\n case \"alpha\": {\n return spriteBlendAlpha;\n }\n case \"premultiplied\": {\n return spriteBlendPremultiplied;\n }\n case \"additive\": {\n return spriteBlendAdditive;\n }\n case \"multiply\": {\n return spriteBlendMultiply;\n }\n case \"opaque\": {\n return spriteBlendOpaque;\n }\n default: {\n return spriteBlendAlpha;\n }\n }\n}\n\n/**\n * What {@link createLayer} accepts.\n *\n * @internal\n */\nexport interface LayerOptions {\n /** The blend mode the whole layer draws with. */\n readonly blend: SpriteBlendName;\n /** The draw order; lower draws first. Derived from the sorting-layer index. */\n readonly order: number;\n /** How many sprites to pre-allocate for. */\n readonly capacity: number;\n /** A per-layer custom fragment shader, or `null`. */\n readonly customShader: Sprite2DCustomShader | null;\n}\n\n/**\n * Creates one Lite sprite layer.\n *\n * @remarks\n * The layer's pivot is pinned to the centre `[0.5, 0.5]`. Lite's sprite pipeline reads **one pivot\n * per layer** out of its uniform block (`lib/sprite/sprite-pipeline.js` lines 25 and 264-265) and\n * ignores `SpriteFrame.pivot` entirely — only the billboard family consumes that\n * (`lib/sprite/billboard-sprite.js` lines 166-167). ignifx therefore keeps the layer centred and\n * offsets each sprite's `positionPx` instead, which is what makes a per-frame pivot and\n * `SpriteRenderer.pivotOverride` possible at all.\n *\n * `depth` stays `\"none\"`: these layers are drawn by a `SpriteRenderer`, not hosted in the render\n * scene's depth buffer (`index.d.ts` 11877).\n *\n * @param atlas - The atlas every sprite in the layer draws from.\n * @param options - Blend, order, capacity, and an optional custom shader.\n * @returns The layer.\n *\n * @internal\n */\nexport function createLayer(atlas: SpriteAtlas, options: LayerOptions): Sprite2DLayer {\n return createSprite2DLayer(atlas, {\n blendMode: blendModeFor(options.blend),\n order: options.order,\n capacity: Math.max(1, options.capacity),\n depth: \"none\",\n pivot: [0.5, 0.5],\n ...(options.customShader === null ? {} : { customShader: options.customShader }),\n });\n}\n\n/**\n * A reusable `Sprite2DProps` record, so a per-frame sync allocates nothing.\n *\n * @remarks\n * `positionPx`, `sizePx`, and `color` are mutable tuples Lite reads and never retains\n * (`writeInstance` copies each component out — `lib/sprite/sprite-2d.js` lines 79-167), so one\n * scratch object can be rewritten and re-submitted every frame (coding standards §7).\n *\n * @internal\n */\nexport interface SpriteScratch {\n /** The props object handed to `addSprite2D`/`updateSprite2D`. */\n readonly props: Sprite2DProps;\n}\n\n/**\n * Builds the reusable props record a sync loop writes through.\n *\n * @returns A fresh scratch record; each sync system owns exactly one.\n *\n * @internal\n */\nexport function createSpriteScratch(): SpriteScratch {\n return {\n props: {\n positionPx: [0, 0],\n sizePx: [0, 0],\n color: [1, 1, 1, 1],\n frame: 0,\n rotation: 0,\n flipX: false,\n flipY: false,\n visible: true,\n },\n };\n}\n\n/**\n * Writes every field of the scratch props record.\n *\n * @param scratch - The reusable record.\n * @param xPx - The sprite's position, in layer pixels.\n * @param yPx - The sprite's position, in layer pixels.\n * @param widthPx - The drawn width, in pixels.\n * @param heightPx - The drawn height, in pixels.\n * @param frame - The atlas frame index.\n * @param rotation - The Lite rotation, in radians.\n * @param r - The red tint, `0` to `1`.\n * @param g - The green tint.\n * @param b - The blue tint.\n * @param a - The alpha.\n * @param flipX - Whether the sprite is mirrored horizontally.\n * @param flipY - Whether the sprite is mirrored vertically.\n * @param visible - Whether the sprite draws at all.\n *\n * @internal\n */\n// oxlint-disable-next-line max-params -- one call per sprite per frame; an options object would allocate.\nexport function writeScratch(\n scratch: SpriteScratch,\n xPx: number,\n yPx: number,\n widthPx: number,\n heightPx: number,\n frame: number,\n rotation: number,\n r: number,\n g: number,\n b: number,\n a: number,\n flipX: boolean,\n flipY: boolean,\n visible: boolean,\n): void {\n const props = scratch.props;\n props.positionPx[0] = xPx;\n props.positionPx[1] = yPx;\n const size = props.sizePx;\n if (size !== undefined) {\n size[0] = widthPx;\n size[1] = heightPx;\n }\n const color = props.color;\n if (color !== undefined) {\n color[0] = r;\n color[1] = g;\n color[2] = b;\n color[3] = a;\n }\n props.frame = frame;\n props.rotation = rotation;\n props.flipX = flipX;\n props.flipY = flipY;\n props.visible = visible;\n}\n\n/**\n * Adds a sprite described by the scratch record.\n *\n * @param layer - The layer to add to.\n * @param scratch - The reusable props record, already written.\n * @returns The stable handle.\n *\n * @internal\n */\nexport function addSprite(layer: Sprite2DLayer, scratch: SpriteScratch): Sprite2DHandle {\n return addSprite2D(layer, scratch.props);\n}\n\n/**\n * Applies the scratch record to an existing sprite.\n *\n * @param handle - The sprite to update.\n * @param scratch - The reusable props record, already written.\n *\n * @internal\n */\nexport function updateSprite(handle: Sprite2DHandle, scratch: SpriteScratch): void {\n updateSprite2D(handle, scratch.props);\n}\n\n/**\n * Removes a sprite, tolerating a handle whose sprite is already gone.\n *\n * @remarks\n * Lite removes by swapping the last sprite into the freed slot\n * (`lib/sprite/sprite-2d-handle.js`, `onRemoveIndex`), so **indices move** while handles do not.\n * Anything that maps a Lite sprite index back to an ignifx component has to apply the same\n * swap rule.\n *\n * @param handle - The sprite to remove.\n * @returns `true` when a sprite was removed.\n *\n * @internal\n */\nexport function removeSprite(handle: Sprite2DHandle): boolean {\n if (!isSprite2DHandleAlive(handle)) {\n return false;\n }\n removeSprite2D(handle);\n return true;\n}\n\n/**\n * Reads the dense index a handle currently occupies.\n *\n * @param handle - The sprite.\n * @returns The index, or `-1` when the sprite is gone.\n *\n * @internal\n */\nexport function spriteIndexOf(handle: Sprite2DHandle): number {\n return isSprite2DHandleAlive(handle) ? getSprite2DHandleIndex(handle) : -1;\n}\n\n/**\n * Removes every sprite from a layer, keeping the layer itself.\n *\n * @param layer - The layer to empty.\n *\n * @internal\n */\nexport function clearLayer(layer: Sprite2DLayer): void {\n clearSprite2DLayer(layer);\n}\n\n/**\n * Turns Y-sorting on or off for a layer.\n *\n * @remarks\n * Lite sorts **ascending** on `positionPx.y + bias` (`lib/sprite/sprite-2d-y-sort.js`, `keyAt` and\n * `comesBefore`). Layer pixels run +Y **down**, so a sprite higher up the screen has the smaller\n * key and draws first — behind — which is exactly the top-down painter's order ignifx wants.\n *\n * @param layer - The layer.\n * @param enabled - Whether to Y-sort.\n *\n * @internal\n */\nexport function setYSort(layer: Sprite2DLayer, enabled: boolean): void {\n if (enabled) {\n enableSprite2DYSort(layer);\n return;\n }\n disableSprite2DYSort(layer);\n}\n\n/**\n * Applies `orderInLayer` as a Y-sort bias on one sprite.\n *\n * @remarks\n * The bias is added to the sprite's pixel Y before sorting, so it has to be large enough to beat\n * any plausible Y difference: {@link Y_SORT_BIAS_STEP} pixels per unit of `orderInLayer`. A\n * negative `orderInLayer` therefore pulls a sprite behind its neighbours and a positive one pushes\n * it in front, which is what `orderInLayer` means when Y-sort is off too.\n *\n * @param handle - The sprite.\n * @param orderInLayer - The component's `orderInLayer`.\n *\n * @internal\n */\nexport function setYSortOrder(handle: Sprite2DHandle, orderInLayer: number): void {\n setSprite2DYSortHandleBias(handle, orderInLayer * Y_SORT_BIAS_STEP);\n}\n\n/**\n * How many layer pixels one unit of `orderInLayer` is worth as a Y-sort bias.\n *\n * @remarks\n * A million pixels is 10 000 world metres at the default PPU of 100 — far larger than any 2D scene,\n * so `orderInLayer` always dominates world Y, and equal `orderInLayer` values fall back to Y.\n *\n * @internal\n */\nexport const Y_SORT_BIAS_STEP = 1_000_000;\n\n/**\n * Writes a layer's view: where the camera looks, how far in, and how it is turned.\n *\n * @remarks\n * `Sprite2DView.positionPx` is the layer-pixel point that lands at the viewport's **top-left**, not\n * its centre (`sprite2DWorldToScreenToRef` in `lib/sprite/sprite-2d-view.js` subtracts it before\n * scaling, and the vertex shader maps `v.x / screenWidth * 2 - 1`). {@link centreView} does the\n * centring arithmetic so callers can think in centres.\n *\n * @param view - The view to write.\n * @param xPx - The top-left corner, in layer pixels.\n * @param yPx - The top-left corner, in layer pixels.\n * @param zoom - The scale; must not be zero, which Lite rejects with a `RangeError`.\n * @param rotation - The view rotation, in radians.\n *\n * @internal\n */\nexport function writeView(view: Sprite2DView, xPx: number, yPx: number, zoom: number, rotation: number): void {\n view.positionPx[0] = xPx;\n view.positionPx[1] = yPx;\n view.zoom = zoom === 0 ? 1 : zoom;\n view.rotation = rotation;\n}\n\n/**\n * Centres a view on a layer-pixel point.\n *\n * @param view - The view to write.\n * @param centreXPx - The point to centre on, in layer pixels.\n * @param centreYPx - The point to centre on, in layer pixels.\n * @param widthPx - The viewport width, in pixels.\n * @param heightPx - The viewport height, in pixels.\n * @param zoom - The scale.\n * @param rotation - The view rotation, in radians.\n *\n * @internal\n */\n// oxlint-disable-next-line max-params -- called once per camera per frame; an options object would allocate.\nexport function centreView(\n view: Sprite2DView,\n centreXPx: number,\n centreYPx: number,\n widthPx: number,\n heightPx: number,\n zoom: number,\n rotation: number,\n): void {\n const safeZoom = zoom === 0 ? 1 : zoom;\n const inverse = 1 / safeZoom;\n const halfWidth = widthPx * 0.5 * inverse;\n const halfHeight = heightPx * 0.5 * inverse;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n view.positionPx[0] = centreXPx - halfWidth * cos - halfHeight * sin;\n view.positionPx[1] = centreYPx + halfWidth * sin - halfHeight * cos;\n view.zoom = safeZoom;\n view.rotation = rotation;\n}\n\n/**\n * Writes the layer-pixel bounds a view can currently see, for chunk culling.\n *\n * @param view - The view.\n * @param widthPx - The viewport width.\n * @param heightPx - The viewport height.\n * @param out - The bounds to write.\n * @returns `out`.\n *\n * @internal\n */\nexport function visibleBounds<TOut extends Bounds2D>(\n view: Sprite2DView,\n widthPx: number,\n heightPx: number,\n out: TOut,\n): TOut {\n return getSprite2DVisibleBoundsToRef(view, widthPx, heightPx, out);\n}\n\n/**\n * A mutable point in a layer's pixel space.\n *\n * @internal\n */\nexport interface LayerPoint {\n /** The layer-space x. */\n x: number;\n /** The layer-space y. */\n y: number;\n}\n\n/**\n * Unprojects a viewport pixel into the layer-pixel space a layer's sprites live in.\n *\n * @param view - The layer's view.\n * @param screenXPx - The viewport x, from the left edge.\n * @param screenYPx - The viewport y, from the top edge.\n * @param out - The point to write: its `x` and `y` take the layer-space coordinates.\n * @returns `out`.\n *\n * @internal\n */\nexport function screenToLayer(view: Sprite2DView, screenXPx: number, screenYPx: number, out: LayerPoint): LayerPoint {\n return sprite2DScreenToWorldToRef(view, screenXPx, screenYPx, out);\n}\n\n/**\n * Picks the topmost sprite under a **layer-pixel** point.\n *\n * @remarks\n * This is the trap in Lite's picking API, and it is not in the declaration: despite the parameter\n * names, `pickSprite2D` compares `xPx`/`yPx` directly against each sprite's stored `positionPx` and\n * **never applies the layer's view** (`lib/sprite/picking/pick-sprite-2d.js` lines 26-27). A\n * viewport pixel therefore has to be unprojected with {@link screenToLayer} first, per layer,\n * because a world layer and a screen-space layer carry different views.\n *\n * @param layers - The layers to test, in draw order.\n * @param xPx - The layer-space x.\n * @param yPx - The layer-space y.\n * @returns The hit, or `null`.\n *\n * @internal\n */\nexport function pickSprite(layers: readonly Sprite2DLayer[], xPx: number, yPx: number): SpritePickInfo | null {\n return pickSprite2D(layers, xPx, yPx);\n}\n\n/**\n * Compiles a WGSL fragment body into a layer shader (`index.d.ts` 3160).\n *\n * @remarks\n * The body is compiled on demand and the result is pure data, so one compiled shader can back many\n * layers. `Sprite2DLayerOptions.customShader` is only read at creation and\n * `Sprite2DLayer.customShader` is `readonly` — a layer's shader cannot be swapped later.\n *\n * @param fragment - The WGSL fragment body.\n * @returns The compiled shader.\n *\n * @internal\n */\nexport function compileLayerShader(fragment: string): Sprite2DCustomShader {\n return createSprite2DCustomShader({ fragment });\n}\n\n/**\n * Writes a custom shader's `fx.params` vec4 for one layer.\n *\n * @param layer - The layer.\n * @param x - The first component.\n * @param y - The second component.\n * @param z - The third component.\n * @param w - The fourth component.\n *\n * @internal\n */\nexport function setShaderParams(layer: Sprite2DLayer, x: number, y: number, z: number, w: number): void {\n setSprite2DShaderParams(layer, [x, y, z, w]);\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\n\n/**\n * The sorting-layer table (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * `@ignifx/core` owns the `sortingLayers` settings section — an ordered list of names, back to\n * front — but ships no resolver for it, the way `layers/layer-table.ts` resolves the `layers`\n * section. This is that resolver: it turns a name into the index the Lite layer's `order` is\n * derived from, and it refuses a name the project never declared instead of silently drawing on\n * the wrong layer.\n */\n\n/**\n * The sorting layer a component that names none draws on.\n *\n * @public\n */\nexport const DEFAULT_SORTING_LAYER = \"Default\";\n\n/**\n * How far apart two sorting layers' Lite `order` values sit.\n *\n * @remarks\n * A gap of 1000 leaves room for the per-(atlas, blend, space) sub-layers a single sorting layer\n * expands into: one sorting layer holding sprites from twelve atlases in three blend modes still\n * fits inside its slice without reaching the next layer's.\n *\n * @public\n */\nexport const SORTING_LAYER_ORDER_STEP = 1000;\n\n/**\n * Resolves sorting-layer names to draw orders.\n *\n * @example\n * ```ts\n * const layers = new SortingLayerTable([\"Background\", \"Default\", \"Foreground\"]);\n * layers.indexOf(\"Foreground\"); // 2\n * ```\n *\n * @public\n */\nexport class SortingLayerTable {\n readonly #names: readonly string[];\n\n readonly #indices: ReadonlyMap<string, number>;\n\n /**\n * Builds the table from the project's `sortingLayers` section.\n *\n * @param names - The names, back to front. An empty list falls back to `[\"Default\"]`.\n */\n constructor(names: readonly string[]) {\n const resolved = names.length === 0 ? [DEFAULT_SORTING_LAYER] : names;\n const indices = new Map<string, number>();\n for (let index = 0; index < resolved.length; index += 1) {\n const name = resolved[index];\n if (name !== undefined && !indices.has(name)) {\n indices.set(name, index);\n }\n }\n if (!indices.has(DEFAULT_SORTING_LAYER)) {\n // A project may rename every layer; `Default` still has to resolve, because it is what an\n // unconfigured `SpriteRenderer` carries.\n indices.set(DEFAULT_SORTING_LAYER, 0);\n }\n this.#names = resolved;\n this.#indices = indices;\n }\n\n /**\n * The layer names, back to front.\n *\n * @returns The names.\n */\n get names(): readonly string[] {\n return this.#names;\n }\n\n /**\n * Resolves a name to its index.\n *\n * @param name - The sorting layer name.\n * @returns The index, or `-1` when the project declares no such layer.\n */\n indexOf(name: string): number {\n return this.#indices.get(name) ?? -1;\n }\n\n /**\n * Resolves a name to its index and refuses to guess.\n *\n * @param name - The sorting layer name.\n * @returns The index.\n * @throws IgnifxError with code `IGX-1107` when the project declares no such layer.\n */\n require(name: string): number {\n const index = this.#indices.get(name);\n if (index === undefined) {\n throw twoDError(TwoDErrorCode.unknownSortingLayer, `${name} is not a declared sorting layer.`, {\n context: { sortingLayer: name },\n hint: `Add it to the sortingLayers settings section. Declared: ${this.#names.join(\", \")}.`,\n });\n }\n return index;\n }\n\n /**\n * The Lite `Sprite2DLayer.order` a sorting layer's sub-layers start at.\n *\n * @param name - The sorting layer name.\n * @returns The base order.\n * @throws IgnifxError with code `IGX-1107` when the project declares no such layer.\n */\n orderOf(name: string): number {\n return this.require(name) * SORTING_LAYER_ORDER_STEP;\n }\n}\n","import {\n asset,\n bool,\n color,\n Component,\n createDefaults,\n defineSchema,\n enumOf,\n i32,\n optional,\n str,\n vec2,\n} from \"@ignifx/core\";\nimport { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport { SPRITE_BLEND_MODES } from \"../lite/sprite-layer.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport type { SpriteBlendName } from \"../lite/sprite-layer.js\";\nimport type { LiteSprite2DHandle } from \"../lite/types.js\";\nimport type { AssetHandle, ColorLike, ComponentHooks, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `SpriteRenderer` (`docs/architecture/11-2d-toolkit.md` §2.2): one sprite drawn from one frame of\n * one atlas.\n *\n * The component holds a single Lite sprite handle inside the layer that matches its\n * (sorting layer, atlas, blend mode, screen-space) key. It creates nothing itself: the 2D sync\n * system owns every layer, so the component only records which layer it belongs in and lets the\n * system reconcile that against the layer it is currently in.\n */\n\n/**\n * The layer key a sprite belongs to.\n *\n * @remarks\n * Two sprites share a Lite layer exactly when all four parts match. The atlas is part of the key\n * because a `Sprite2DLayer` is bound to one atlas for its whole life (`index.d.ts` 11885,\n * `readonly atlas`), and the blend mode is part of it for the same reason (`readonly blendMode`).\n *\n * @public\n */\nexport interface SpriteLayerKey {\n /** The sorting layer's name. */\n readonly sortingLayer: string;\n /** The atlas every sprite in the layer draws from. */\n readonly atlas: SpriteAtlasAsset;\n /** The blend mode. */\n readonly blend: SpriteBlendName;\n /** Whether the layer keeps the identity view instead of following the `Camera2D`. */\n readonly screenSpace: boolean;\n}\n\n/**\n * A sprite.\n *\n * @remarks\n * The `sprite` field is an atlas handle; the frame inside it comes from the address's `#frame:`\n * fragment when there is one, and otherwise from {@link SpriteRenderer.frame}, which game code and\n * `SpriteAnimator` both write. A sprite whose atlas has not finished loading draws nothing and\n * costs nothing.\n *\n * @example\n * ```ts\n * const hero = app.world.createEntity({ name: \"hero\" });\n * const sprite = hero.addComponent(SpriteRenderer);\n * sprite.sprite = app.assets.load<SpriteAtlasAsset>(\"2d/hero.atlas.json\").retain();\n * sprite.sortingLayer = \"Default\";\n * ```\n *\n * @public\n */\nexport class SpriteRenderer extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/SpriteRenderer\";\n\n /** Several sprites may share an entity — a character and its shadow, for instance. */\n static allowMultiple = true;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = spriteRendererSchema();\n\n /** The atlas this sprite draws a frame of. */\n declare sprite: AssetHandle<SpriteAtlasAsset> | null;\n\n /** The tint multiplied into every texel. */\n declare color: ColorLike;\n\n /** Whether the sprite is mirrored horizontally. */\n declare flipX: boolean;\n\n /** Whether the sprite is mirrored vertically. */\n declare flipY: boolean;\n\n /** Which sorting layer the sprite draws on. */\n declare sortingLayer: string;\n\n /** The sub-order within the sorting layer; higher draws in front. */\n declare orderInLayer: number;\n\n /** How the sprite's colour combines with what is behind it. */\n declare blend: SpriteBlendName;\n\n /** The pivot in `[0, 1]` of the frame, overriding the frame's own; `null` uses the frame's. */\n declare pivotOverride: Vec2Like | null;\n\n /** Whether the sprite keeps the identity view instead of following the `Camera2D`. */\n declare screenSpace: boolean;\n\n /** Whether `app.twoD.pickAt` considers this sprite. */\n declare pickable: boolean;\n\n /** The atlas frame index drawn; `SpriteAnimator` writes this. */\n #frame = 0;\n\n /** The Lite handle, or `null` while the sprite is not in a layer. */\n #handle: LiteSprite2DHandle | null = null;\n\n /** The key of the layer the handle currently lives in, or `null`. */\n #layerKey: string | null = null;\n\n /** The `worldMatrixVersion` the last sync wrote at, so a still entity costs one comparison. */\n #syncedMatrixVersion = -1;\n\n /** Whether a field changed since the last sync. */\n #isDirty = true;\n\n /** Whether a static entity has been synced at least once. */\n #hasSyncedStatic = false;\n\n /** The visibility the last sync wrote, so toggling `enabled` reaches Lite. */\n #appliedVisible = false;\n\n /** The world AABB the last sync computed, as `minX, minY, maxX, maxY` in metres. */\n readonly #bounds = new Float64Array(4);\n\n /**\n * Builds a sprite with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(SpriteRenderer.schema));\n }\n\n /**\n * Resets the sync shadow state, so a recycled component does not inherit the previous one's.\n */\n onAttach(): void {\n this.#syncedMatrixVersion = -1;\n this.#hasSyncedStatic = false;\n this.#appliedVisible = false;\n this.#isDirty = true;\n }\n\n /**\n * Marks the sprite for removal from its layer. The sync system does the removal, because it owns\n * the layer.\n */\n onDetach(): void {\n this.#isDirty = true;\n }\n\n /**\n * The atlas frame drawn.\n *\n * @returns The frame index.\n */\n get frame(): number {\n return this.#frame;\n }\n\n /**\n * Sets the atlas frame drawn, marking the sprite for the next sync when it changes.\n *\n * @param value - The frame index.\n */\n set frame(value: number) {\n if (value !== this.#frame) {\n this.#frame = value;\n this.#isDirty = true;\n }\n }\n\n /**\n * The Babylon Lite objects the component uses. Unstable escape hatch\n * (`CONSTITUTION.md` §3.4).\n *\n * @returns The sprite handle, or `null` when the sprite is not in a layer.\n */\n get lite(): { readonly sprite: LiteSprite2DHandle | null } {\n return { sprite: this.#handle };\n }\n\n /**\n * The sprite's world-space axis-aligned bounding box, for coarse queries\n * (`docs/architecture/11-2d-toolkit.md` §5).\n *\n * @remarks\n * The box is the one the last sync computed, so it is a frame behind a sprite that has just\n * moved, and it is the origin-sized empty box until the sprite has been synced once. It ignores\n * rotation: a rotated sprite reports the box of its unrotated quad, which is the cheap\n * conservative answer only for rotations that are multiples of a quarter turn.\n *\n * @returns A freshly allocated box in world metres.\n */\n get bounds(): { readonly min: Vec2Like; readonly max: Vec2Like } {\n return {\n min: { x: this.#bounds[0] ?? 0, y: this.#bounds[1] ?? 0 },\n max: { x: this.#bounds[2] ?? 0, y: this.#bounds[3] ?? 0 },\n };\n }\n\n /**\n * The loaded atlas, or `null` while it is still loading or failed.\n *\n * @returns The atlas.\n */\n get atlas(): SpriteAtlasAsset | null {\n const handle = this.sprite;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * Whether anything about this sprite needs writing to Lite this frame.\n *\n * @param isStatic - Whether the owning entity is marked static.\n * @param matrixVersion - The entity transform's `worldMatrixVersion`.\n * @returns `true` when the sync system must write the sprite.\n *\n * @internal\n */\n needsSync(isStatic: boolean, matrixVersion: number): boolean {\n if (this.#isDirty) {\n return true;\n }\n // Enabling or disabling the component, or anything above it in the hierarchy, changes nothing\n // the transform version or the dirty flag can see — but it does change what Lite must draw.\n if (this.isEnabledInHierarchy !== this.#appliedVisible) {\n return true;\n }\n if (isStatic) {\n return !this.#hasSyncedStatic;\n }\n return matrixVersion !== this.#syncedMatrixVersion;\n }\n\n /**\n * Records that the sync system has written this sprite.\n *\n * @param isStatic - Whether the owning entity is marked static.\n * @param matrixVersion - The transform version written at.\n * @param minX - The world AABB, in metres.\n * @param minY - The world AABB, in metres.\n * @param maxX - The world AABB, in metres.\n * @param maxY - The world AABB, in metres.\n *\n * @internal\n */\n // oxlint-disable-next-line max-params -- once per moved sprite per frame; an options object would allocate.\n markSynced(isStatic: boolean, matrixVersion: number, minX: number, minY: number, maxX: number, maxY: number): void {\n this.#isDirty = false;\n this.#appliedVisible = this.isEnabledInHierarchy;\n this.#hasSyncedStatic = isStatic;\n this.#syncedMatrixVersion = matrixVersion;\n this.#bounds[0] = minX;\n this.#bounds[1] = minY;\n this.#bounds[2] = maxX;\n this.#bounds[3] = maxY;\n }\n\n /**\n * Forces the next sync to rewrite this sprite.\n *\n * @internal\n */\n invalidate(): void {\n this.#isDirty = true;\n this.#hasSyncedStatic = false;\n }\n\n /**\n * The Lite handle and the key of the layer holding it.\n *\n * @returns The placement, or `null` when the sprite is not in a layer.\n *\n * @internal\n */\n placement(): { readonly handle: LiteSprite2DHandle; readonly key: string } | null {\n const handle = this.#handle;\n const key = this.#layerKey;\n return handle === null || key === null ? null : { handle, key };\n }\n\n /**\n * Records the layer the sync system put this sprite in.\n *\n * @param handle - The Lite handle, or `null` when the sprite was removed.\n * @param key - The layer key, or `null`.\n *\n * @internal\n */\n setPlacement(handle: LiteSprite2DHandle | null, key: string | null): void {\n this.#handle = handle;\n this.#layerKey = key;\n }\n}\n\n/**\n * The `SpriteRenderer` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction spriteRendererSchema(): Schema {\n return defineSchema({\n sprite: asset(SpriteAtlasAsset, { tooltip: \"The atlas this sprite draws a frame of.\" }),\n color: color(\"#ffffffff\", { tooltip: \"Tint multiplied into every texel.\" }),\n flipX: bool(false, { tooltip: \"Mirror horizontally.\" }),\n flipY: bool(false, { tooltip: \"Mirror vertically.\" }),\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Which sorting layer the sprite draws on.\" }),\n orderInLayer: i32(0, { tooltip: \"Sub-order within the sorting layer; higher draws in front.\" }),\n blend: enumOf(SPRITE_BLEND_MODES, \"alpha\", { tooltip: \"How the colour combines with the background.\" }),\n pivotOverride: optional(vec2(), { tooltip: \"Overrides the frame's own pivot, in [0,1] of the frame.\" }),\n screenSpace: bool(false, { tooltip: \"Keep the identity view instead of following the Camera2D.\" }),\n pickable: bool(true, { tooltip: \"Whether app.twoD.pickAt considers this sprite.\" }),\n });\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\n\n/**\n * The `ignifx.spriteanimation` document — the `.spriteanim.json` file that names an atlas and the\n * clips cut out of its frames (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `11-2d-toolkit.md` §2.4).\n *\n * A clip lists frame names explicitly, or names the first and last frame of a contiguous run in the\n * atlas. ignifx drives these on its own clock in `PostUpdate`, not on Lite's\n * `SpriteAnimationManager`, so `timeScale`, pause, and frame events behave exactly as they do for\n * 3D animation (ADR-0003).\n */\n\n/**\n * The `format` discriminator every `.spriteanim.json` document carries.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_FORMAT = \"ignifx.spriteanimation\";\n\n/**\n * The document version this build reads and writes.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_FORMAT_VERSION = 1;\n\n/**\n * The asset type name the loader registers.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_ASSET_TYPE = \"spriteanimation\";\n\n/**\n * The address suffixes that select the sprite-animation loader.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".spriteanim.json\"]);\n\n/**\n * A frame event: a name emitted on `SpriteAnimator.onEvent` when the clip reaches a frame.\n *\n * @public\n */\nexport interface SpriteAnimationEvent {\n /** The zero-based index **within the clip**, not within the atlas. */\n readonly frame: number;\n /** The name emitted on `SpriteAnimator.onEvent`. */\n readonly name: string;\n}\n\n/**\n * One clip: an ordered run of atlas frames with a rate and a loop flag.\n *\n * @remarks\n * A clip names its frames one of two ways, and they mean different things.\n *\n * - `frames` is an explicit **list of frame names**, played in the order written. Anything the\n * atlas does not carry is dropped, and the frames need not be adjacent in the atlas.\n * - `from`/`to` is an **index range over the atlas**, not a pair of endpoints joined by name. Both\n * names are resolved to their atlas indices and *every index between them is played*, in atlas\n * order, endpoints included. So a range whose endpoints are not adjacent in the sheet plays\n * whatever the packer happened to put between them — a `from: \"run_0\"`, `to: \"run_5\"` over an\n * atlas ordered `run_0, idle_0, run_1, …` plays `idle_0` too. Use `frames` whenever the run is\n * not contiguous in the atlas.\n * - `to` before `from` is legal and plays the range backwards.\n *\n * @public\n */\nexport interface SpriteClipDefinition {\n /** The clip's name, unique within the document; what `SpriteAnimator.play` takes. */\n readonly name: string;\n /**\n * The atlas frame names, in play order; they need not be adjacent in the atlas. Absent or empty\n * when `from`/`to` name a range instead.\n */\n readonly frames?: readonly string[];\n /**\n * The atlas frame whose **index** starts the range, when `frames` is absent. The clip plays every\n * atlas index from here to `to`, so the two must bracket a contiguous run in the sheet.\n */\n readonly from?: string;\n /**\n * The atlas frame whose **index** ends the range, inclusive. An index below `from`'s plays the\n * range backwards.\n */\n readonly to?: string;\n /** Frames per second. Defaults to `12`. */\n readonly fps?: number;\n /** Whether the clip restarts at its end. Defaults to `true`. */\n readonly loop?: boolean;\n /** Events fired as the clip passes a frame. */\n readonly events?: readonly SpriteAnimationEvent[];\n}\n\n/**\n * The parsed `.spriteanim.json` document.\n *\n * @public\n */\nexport interface SpriteAnimationDefinition {\n /** Always `\"ignifx.spriteanimation\"`. */\n readonly format: typeof SPRITE_ANIMATION_FORMAT;\n /** Always `1` in this build. */\n readonly formatVersion: number;\n /** The address of the `.atlas.json` the clips index into; empty uses the renderer's own atlas. */\n readonly atlas: string;\n /** The clips, in declaration order; the first is the default when the component names none. */\n readonly clips: readonly SpriteClipDefinition[];\n}\n\n/**\n * What {@link defineSpriteAnimation} accepts.\n *\n * @public\n */\nexport interface SpriteAnimationInput {\n /** Always `\"ignifx.spriteanimation\"` when present. */\n readonly format?: string;\n /** The document version. */\n readonly formatVersion?: number;\n /** The address of the `.atlas.json` the clips index into. */\n readonly atlas?: string;\n /** The clips. */\n readonly clips: readonly SpriteClipDefinition[];\n}\n\n/**\n * The frames-per-second a clip that declares none plays at.\n *\n * @public\n */\nexport const DEFAULT_CLIP_FPS = 12;\n\n/**\n * Fills in the defaults of an animation document and checks the invariants the animator relies on.\n *\n * @param input - The document, as authored or as an importer emitted it.\n * @param address - What to name in an error; defaults to `\"<inline>\"`.\n * @returns The complete document.\n * @throws IgnifxError with code `IGX-1104` when the format tag, the version, or a clip is wrong.\n *\n * @public\n */\nexport function defineSpriteAnimation(input: SpriteAnimationInput, address = \"<inline>\"): SpriteAnimationDefinition {\n const fail = (reason: string): never => {\n throw twoDError(\n TwoDErrorCode.invalidAnimationFile,\n `${address} is not a readable ignifx.spriteanimation document: ${reason}.`,\n { context: { file: address }, hint: \"Check the format, version, and clip fields.\" },\n );\n };\n if (input.format !== undefined && input.format !== SPRITE_ANIMATION_FORMAT) {\n fail(`its format is ${input.format}, not ${SPRITE_ANIMATION_FORMAT}`);\n }\n if (input.formatVersion !== undefined && input.formatVersion !== SPRITE_ANIMATION_FORMAT_VERSION) {\n fail(\n `its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(SPRITE_ANIMATION_FORMAT_VERSION)}`,\n );\n }\n if (!Array.isArray(input.clips) || input.clips.length === 0) {\n fail(\"it declares no clips\");\n }\n const seen = new Set<string>();\n for (let index = 0; index < input.clips.length; index += 1) {\n const clip = input.clips[index];\n if (clip === undefined || typeof clip.name !== \"string\" || clip.name === \"\") {\n fail(`clip ${String(index)} has no name`);\n continue;\n }\n if (seen.has(clip.name)) {\n fail(`two clips are named ${clip.name}`);\n }\n seen.add(clip.name);\n const hasList = clip.frames !== undefined && clip.frames.length > 0;\n const hasRange = typeof clip.from === \"string\" && typeof clip.to === \"string\";\n if (!hasList && !hasRange) {\n fail(`clip ${clip.name} names neither a frame list nor a from/to range`);\n }\n if (clip.fps !== undefined && !(clip.fps > 0)) {\n fail(`clip ${clip.name} has a non-positive fps`);\n }\n }\n return {\n format: SPRITE_ANIMATION_FORMAT,\n formatVersion: SPRITE_ANIMATION_FORMAT_VERSION,\n atlas: input.atlas ?? \"\",\n clips: input.clips,\n };\n}\n\n/**\n * Resolves a clip's frame names into atlas frame indices.\n *\n * @remarks\n * `frames` resolves name by name and skips what the atlas does not carry. `from`/`to` resolves both\n * endpoints to atlas **indices** and walks every index between them — ascending or descending — so\n * a range over non-adjacent frames plays everything the packer put in between\n * ({@link SpriteClipDefinition}).\n *\n * @param clip - The clip to resolve.\n * @param indexOf - Maps an atlas frame name to its index, or `-1` when the atlas has no such frame.\n * @returns The indices in play order; empty when the clip names nothing the atlas has.\n *\n * @public\n */\nexport function resolveClipFrames(clip: SpriteClipDefinition, indexOf: (name: string) => number): readonly number[] {\n const list = clip.frames;\n if (list !== undefined && list.length > 0) {\n const out: number[] = [];\n for (let index = 0; index < list.length; index += 1) {\n const name = list[index];\n const resolved = name === undefined ? -1 : indexOf(name);\n if (resolved >= 0) {\n out.push(resolved);\n }\n }\n return out;\n }\n const first = clip.from === undefined ? -1 : indexOf(clip.from);\n const last = clip.to === undefined ? -1 : indexOf(clip.to);\n if (first < 0 || last < 0) {\n return [];\n }\n const out: number[] = [];\n const step = last >= first ? 1 : -1;\n for (let frame = first; step > 0 ? frame <= last : frame >= last; frame += step) {\n out.push(frame);\n }\n return out;\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { resolveClipFrames, SPRITE_ANIMATION_ASSET_TYPE, DEFAULT_CLIP_FPS } from \"./definition.js\";\nimport type { SpriteAnimationDefinition, SpriteAnimationEvent, SpriteClipDefinition } from \"./definition.js\";\nimport type { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\n\n/**\n * The value a `.spriteanim.json` address loads to: the parsed document plus, once the atlas it\n * names has loaded, every clip resolved to atlas frame indices\n * (`docs/architecture/11-2d-toolkit.md` §2.4).\n */\n\n/**\n * One clip, resolved against an atlas.\n *\n * @public\n */\nexport interface SpriteClip {\n /** The clip's name. */\n readonly name: string;\n /** The atlas frame indices, in play order. */\n readonly frames: readonly number[];\n /** Frames per second. */\n readonly fps: number;\n /** Whether the clip restarts at its end. */\n readonly loop: boolean;\n /** Events fired as the clip passes a frame. */\n readonly events: readonly SpriteAnimationEvent[];\n /** How long one pass through the clip takes, in seconds. */\n readonly durationSeconds: number;\n}\n\n/**\n * A loaded sprite-animation document.\n *\n * @remarks\n * Resolution needs an atlas, and a document may be loaded before, after, or without one. The asset\n * therefore keeps the parsed clips and resolves them lazily the first time an atlas is offered;\n * `SpriteAnimator` offers its renderer's atlas. Under a headless app everything here works\n * unchanged, which is what makes animation timing testable with `app.step`.\n *\n * @example\n * ```ts\n * const clips = await app.assets.load<SpriteAnimationAsset>(\"2d/hero.spriteanim.json\").promise;\n * clips.clipNames(); // [\"idle\", \"run\"]\n * ```\n *\n * @public\n */\nexport class SpriteAnimationAsset {\n /** The type name the asset service registers animation documents under. */\n static assetType: string = SPRITE_ANIMATION_ASSET_TYPE;\n\n /** The address the document was loaded from. */\n readonly address: string;\n\n /** The parsed document. */\n readonly definition: SpriteAnimationDefinition;\n\n /** The atlas address the document names, already resolved against its own address. */\n readonly atlasAddress: string;\n\n #resolved: ReadonlyMap<string, SpriteClip> | null = null;\n\n #resolvedAgainst: SpriteAtlasAsset | null = null;\n\n /**\n * Wraps a parsed document. The `spriteanimation` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The parsed document.\n * @param atlasAddress - The atlas address, resolved against `address`.\n *\n * @internal\n */\n constructor(address: string, definition: SpriteAnimationDefinition, atlasAddress: string) {\n this.address = address;\n this.definition = definition;\n this.atlasAddress = atlasAddress;\n }\n\n /**\n * Every clip name, in declaration order.\n *\n * @returns A freshly allocated array.\n */\n clipNames(): readonly string[] {\n const names: string[] = [];\n for (let index = 0; index < this.definition.clips.length; index += 1) {\n const clip = this.definition.clips[index];\n if (clip !== undefined) {\n names.push(clip.name);\n }\n }\n return names;\n }\n\n /**\n * The name of the clip a component that names none plays.\n *\n * @returns The first clip's name, or `\"\"` when the document is empty.\n */\n get defaultClipName(): string {\n return this.definition.clips[0]?.name ?? \"\";\n }\n\n /**\n * Resolves every clip's frame names against an atlas.\n *\n * @remarks\n * The result is cached against the atlas it was resolved with, so playing ten characters off one\n * atlas resolves once. Offering a different atlas re-resolves.\n *\n * @param atlas - The atlas the frame names index into.\n * @returns The clips, keyed by name.\n */\n resolve(atlas: SpriteAtlasAsset): ReadonlyMap<string, SpriteClip> {\n const cached = this.#resolved;\n if (cached !== null && this.#resolvedAgainst === atlas) {\n return cached;\n }\n const clips = new Map<string, SpriteClip>();\n const indexOf = (name: string): number => atlas.frameIndex(name);\n for (let index = 0; index < this.definition.clips.length; index += 1) {\n const declared = this.definition.clips[index];\n if (declared === undefined) {\n continue;\n }\n clips.set(declared.name, toClip(declared, resolveClipFrames(declared, indexOf)));\n }\n this.#resolved = clips;\n this.#resolvedAgainst = atlas;\n return clips;\n }\n\n /**\n * Looks a clip up, resolving against an atlas first.\n *\n * @param name - The clip name.\n * @param atlas - The atlas the frame names index into.\n * @returns The clip.\n * @throws IgnifxError with code `IGX-1108` when the document declares no such clip.\n */\n requireClip(name: string, atlas: SpriteAtlasAsset): SpriteClip {\n const clip = this.resolve(atlas).get(name);\n if (clip === undefined) {\n throw twoDError(TwoDErrorCode.unknownClip, `${this.address} declares no clip named ${name}.`, {\n context: { asset: this.address, clip: name },\n hint: `Known clips: ${this.clipNames().join(\", \")}.`,\n });\n }\n return clip;\n }\n}\n\n/**\n * Builds a resolved clip from a declaration and its frame indices.\n *\n * @param declared - The clip as the document wrote it.\n * @param frames - Its atlas frame indices.\n * @returns The clip.\n */\nfunction toClip(declared: SpriteClipDefinition, frames: readonly number[]): SpriteClip {\n const fps = declared.fps !== undefined && declared.fps > 0 ? declared.fps : DEFAULT_CLIP_FPS;\n return {\n name: declared.name,\n frames,\n fps,\n loop: declared.loop ?? true,\n events: declared.events ?? EMPTY_EVENTS,\n durationSeconds: frames.length / fps,\n };\n}\n\n/** The event list a clip that declares none carries. */\nconst EMPTY_EVENTS: readonly SpriteAnimationEvent[] = Object.freeze([]);\n","import { asset, bool, Component, createDefaults, defineSchema, f32, Signal, str } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\nimport { SpriteAnimationAsset } from \"./sprite-animation-asset.js\";\nimport type { SpriteClip } from \"./sprite-animation-asset.js\";\nimport type { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport type { AssetHandle, ComponentHooks, Schema } from \"@ignifx/core\";\n\n/**\n * `SpriteAnimator` (`docs/architecture/11-2d-toolkit.md` §2.4): plays a clip of atlas frames on the\n * `SpriteRenderer` sharing its entity.\n *\n * The clock is **ignifx's**, advanced in `PostUpdate` (ADR-0003), not Lite's\n * `SpriteAnimationManager`. That is what makes `app.time.timeScale`, `app.pause()`, and frame\n * events behave for a 2D character exactly as they do for a 3D one — and what makes the whole\n * thing testable with `app.step` under a headless app, where no sprite is drawn at all.\n */\n\n/**\n * What {@link SpriteAnimator.play} accepts.\n *\n * @public\n */\nexport interface PlayClipOptions {\n /** Whether to rewind a clip that is already playing. Defaults to `false`. */\n readonly restart?: boolean;\n}\n\n/**\n * A sprite animator.\n *\n * @example\n * ```ts\n * const animator = hero.addComponent(SpriteAnimator);\n * animator.animations = app.assets.load<SpriteAnimationAsset>(\"2d/hero.spriteanim.json\").retain();\n * animator.onEvent.connect((name) => { if (name === \"footstep\") playStep(); }, { owner: animator });\n * animator.play(\"run\");\n * ```\n *\n * @public\n */\nexport class SpriteAnimator extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/SpriteAnimator\";\n\n /** One animator per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = spriteAnimatorSchema();\n\n /** The document holding the clips. */\n declare animations: AssetHandle<SpriteAnimationAsset> | null;\n\n /** Which clip to start on; empty plays the document's first. */\n declare defaultClip: string;\n\n /** Whether the default clip starts as soon as the document has loaded. */\n declare playOnAwake: boolean;\n\n /** A multiplier on the clip's own frame rate. */\n declare speed: number;\n\n /** The clip currently playing, or `null`. */\n #clip: SpriteClip | null = null;\n\n /** How far into the clip playback is, in seconds. */\n #elapsed = 0;\n\n /** The clip frame index the last advance settled on. */\n #cursor = 0;\n\n /** Whether playback is running. */\n #isPlaying = false;\n\n /** Whether the default clip has been started already. */\n #hasAutoPlayed = false;\n\n /** The renderer this animator writes frames to; found lazily. */\n #renderer: SpriteRenderer | null = null;\n\n readonly #onClipEnded: Signal<string> = new Signal<string>();\n\n readonly #onEvent: Signal<string> = new Signal<string>();\n\n /**\n * Builds an animator with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(SpriteAnimator.schema));\n }\n\n /**\n * Clears playback state, so a recycled component does not inherit the previous one's.\n */\n onAttach(): void {\n this.#clip = null;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#isPlaying = false;\n this.#hasAutoPlayed = false;\n this.#renderer = null;\n }\n\n /**\n * Releases the signals' handlers.\n */\n onDetach(): void {\n this.#isPlaying = false;\n }\n\n /**\n * Emitted with a clip's name when a non-looping clip reaches its last frame.\n *\n * @returns The signal.\n */\n get onClipEnded(): Signal<string> {\n return this.#onClipEnded;\n }\n\n /**\n * Emitted with an event's name when playback passes the frame that declares it.\n *\n * @remarks\n * A looping clip fires each event once per pass. A clip advanced by more than one frame in a\n * single step — a long frame, or a high `speed` — fires every event it skipped over, in order,\n * so a footstep is never silently dropped.\n *\n * @returns The signal.\n */\n get onEvent(): Signal<string> {\n return this.#onEvent;\n }\n\n /**\n * Whether a clip is currently advancing.\n *\n * @returns `true` while playing.\n */\n get isPlaying(): boolean {\n return this.#isPlaying;\n }\n\n /**\n * The clip currently playing, or `null`.\n *\n * @returns The clip.\n */\n get clip(): SpriteClip | null {\n return this.#clip;\n }\n\n /**\n * The atlas frame index the animator last wrote.\n *\n * @returns The frame index, or `-1` when no clip is playing.\n */\n get frame(): number {\n return this.#clip?.frames[this.#cursor] ?? -1;\n }\n\n /**\n * How far into the clip playback is, in seconds.\n *\n * @returns The elapsed time.\n */\n get time(): number {\n return this.#elapsed;\n }\n\n /**\n * The loaded animation document, or `null` while it is still loading.\n *\n * @returns The document.\n */\n get asset(): SpriteAnimationAsset | null {\n const handle = this.animations;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * Starts a clip.\n *\n * @param name - The clip's name.\n * @param options - Whether to rewind a clip that is already playing.\n * @throws IgnifxError with code `IGX-1108` when the document declares no such clip.\n *\n * @example\n * ```ts\n * animator.play(\"run\", { restart: true });\n * ```\n */\n play(name: string, options?: PlayClipOptions): void {\n const clips = this.asset;\n const atlas = this.#atlas();\n if (clips === null || atlas === null) {\n // Nothing loaded yet; remember the intent so `advance` starts it on arrival.\n this.defaultClip = name;\n this.playOnAwake = true;\n this.#hasAutoPlayed = false;\n return;\n }\n const clip = clips.requireClip(name, atlas);\n if (this.#clip === clip && this.#isPlaying && options?.restart !== true) {\n return;\n }\n this.#clip = clip;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#isPlaying = clip.frames.length > 0;\n this.#writeFrame();\n }\n\n /**\n * Stops playback and rewinds to the clip's first frame.\n */\n stop(): void {\n this.#isPlaying = false;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#writeFrame();\n }\n\n /**\n * Suspends playback where it is; {@link SpriteAnimator.resume} continues from there.\n */\n pause(): void {\n this.#isPlaying = false;\n }\n\n /**\n * Continues a paused clip.\n */\n resume(): void {\n if (this.#clip !== null && this.#clip.frames.length > 0) {\n this.#isPlaying = true;\n }\n }\n\n /**\n * Advances playback by one frame's worth of scaled time. The animation system calls this in\n * `PostUpdate`.\n *\n * @remarks\n * `deltaSeconds` is `ctx.dt` in the `PostUpdate` phase, which is `time.deltaTime` — already\n * multiplied by `time.timeScale`; the 2D animation system skips the call while the app is paused\n * (`docs/architecture/01-lifecycle-and-time.md` §2). The animator does not consult the clock\n * itself, which is what makes it deterministic under `app.step`.\n *\n * @param deltaSeconds - The scaled frame delta.\n *\n * @internal\n */\n advance(deltaSeconds: number): void {\n this.#autoPlay();\n const clip = this.#clip;\n if (clip === null || !this.#isPlaying || clip.frames.length === 0) {\n return;\n }\n const rate = clip.fps * this.speed;\n if (rate <= 0) {\n return;\n }\n const count = clip.frames.length;\n const previous = this.#cursor;\n this.#elapsed += deltaSeconds;\n const raw = Math.floor(this.#elapsed * rate);\n let next = raw;\n let ended = false;\n if (raw >= count) {\n if (clip.loop) {\n next = raw % count;\n } else {\n next = count - 1;\n ended = true;\n }\n }\n if (next !== previous) {\n this.#emitEventsBetween(clip, previous, raw, count);\n this.#cursor = next;\n this.#writeFrame();\n }\n if (ended) {\n this.#isPlaying = false;\n this.#onClipEnded.emit(clip.name);\n }\n }\n\n /**\n * Starts the default clip once the document and the atlas have both arrived.\n */\n #autoPlay(): void {\n if (this.#hasAutoPlayed || !this.playOnAwake) {\n return;\n }\n const clips = this.asset;\n const atlas = this.#atlas();\n if (clips === null || atlas === null) {\n return;\n }\n const name = this.defaultClip === \"\" ? clips.defaultClipName : this.defaultClip;\n if (name === \"\") {\n this.#hasAutoPlayed = true;\n return;\n }\n const clip = clips.resolve(atlas).get(name);\n if (clip === undefined) {\n this.#hasAutoPlayed = true;\n throw twoDError(TwoDErrorCode.unknownClip, `${clips.address} declares no clip named ${name}.`, {\n context: { asset: clips.address, clip: name },\n hint: `Known clips: ${clips.clipNames().join(\", \")}.`,\n });\n }\n this.#hasAutoPlayed = true;\n this.#clip = clip;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#isPlaying = clip.frames.length > 0;\n this.#writeFrame();\n }\n\n /**\n * Fires every frame event between two clip positions, in order.\n *\n * @param clip - The playing clip.\n * @param from - The clip frame index playback was on.\n * @param toRaw - The unwrapped frame index playback reached.\n * @param count - How many frames the clip has.\n */\n #emitEventsBetween(clip: SpriteClip, from: number, toRaw: number, count: number): void {\n if (clip.events.length === 0) {\n return;\n }\n // A looping clip can pass every frame at most once per step's worth of wrapping; a\n // non-looping one stops at its last frame, and walking past it would fire that frame's events\n // again for every extra step the clamp swallowed.\n const reach = clip.loop ? count : count - 1 - from;\n const steps = Math.min(toRaw - from, reach);\n for (let step = 1; step <= steps; step += 1) {\n const frame = clip.loop ? (from + step) % count : from + step;\n for (let index = 0; index < clip.events.length; index += 1) {\n const event = clip.events[index];\n if (event !== undefined && event.frame === frame) {\n this.#onEvent.emit(event.name);\n }\n }\n }\n }\n\n /**\n * Writes the current clip frame onto the renderer.\n */\n #writeFrame(): void {\n const renderer = this.#findRenderer();\n const frame = this.#clip?.frames[this.#cursor];\n if (renderer !== null && frame !== undefined) {\n renderer.frame = frame;\n }\n }\n\n /**\n * The atlas the clips index into: the sibling renderer's.\n *\n * @returns The atlas, or `null`.\n */\n #atlas(): SpriteAtlasAsset | null {\n return this.#findRenderer()?.atlas ?? null;\n }\n\n /**\n * The `SpriteRenderer` on this entity, cached once found.\n *\n * @returns The renderer, or `null` when the entity has none.\n */\n #findRenderer(): SpriteRenderer | null {\n const cached = this.#renderer;\n if (cached !== null && !cached.isDestroyed) {\n return cached;\n }\n const found = this.entity.getComponent(SpriteRenderer);\n this.#renderer = found;\n return found;\n }\n}\n\n/**\n * The `SpriteAnimator` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction spriteAnimatorSchema(): Schema {\n return defineSchema({\n animations: asset(SpriteAnimationAsset, { tooltip: \"The .spriteanim.json document holding the clips.\" }),\n defaultClip: str(\"\", { tooltip: \"Which clip to start on; empty plays the document's first.\" }),\n playOnAwake: bool(true, { tooltip: \"Start the default clip as soon as the document has loaded.\" }),\n speed: f32(1, { min: 0, tooltip: \"A multiplier on each clip's own frame rate.\" }),\n });\n}\n","import { SpriteAnimator } from \"./sprite-animator.js\";\nimport type { AnimatedTilemapSink } from \"../tilemap/animated-tiles.js\";\nimport type { System, SystemContext } from \"@ignifx/core\";\n\n/**\n * The 2D animation system (`docs/architecture/01-lifecycle-and-time.md` §3, ADR-0003).\n *\n * It runs in `PostUpdate` — after `update`, before `PreRender` — which is where every animation in\n * ignifx advances, so a `lateUpdate` sees the posed frame and the render sync writes it in the same\n * frame it was computed. It advances every `SpriteAnimator` and every animated tile on the same\n * `ctx.dt`, which is `time.deltaTime`, already scaled by `time.timeScale`. Systems keep running\n * while the app is paused and `dt` is **not** zeroed then (only scripts are filtered by\n * `updateWhenPaused`), so the system checks `time.paused` itself: sprite animation does not advance\n * while paused (`01-lifecycle-and-time.md` §7). Phase 6 shipped without this check and the sprites\n * kept animating under a pause menu.\n */\n\n/**\n * The `PostUpdate` order the 2D animation system runs at.\n *\n * @remarks\n * `PostUpdate` is empty today — no core or extension system registers there — so `0` is the middle\n * of an open phase. Anything a game adds later can sit either side of it by choosing a sign.\n *\n * @public\n */\nexport const TWO_D_ANIMATION_ORDER = 0;\n\n/**\n * Advances sprite animation on ignifx's clock.\n *\n * @public\n */\nexport class TwoDAnimationSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name = \"ignifx/2d-animation\";\n\n readonly #tilemaps: AnimatedTilemapSink;\n\n /**\n * Builds the system.\n *\n * @param tilemaps - Advances animated tiles on the same clock.\n */\n constructor(tilemaps: AnimatedTilemapSink) {\n this.#tilemaps = tilemaps;\n }\n\n /**\n * Advances every animator and every animated tile.\n *\n * @param ctx - The world, clock, phase, and delta.\n */\n update(ctx: SystemContext): void {\n if (ctx.time.paused) {\n return;\n }\n const animators = ctx.world.components(SpriteAnimator);\n for (let index = 0; index < animators.length; index += 1) {\n const animator = animators[index];\n if (animator !== undefined && animator.isEnabledInHierarchy) {\n animator.advance(ctx.dt);\n }\n }\n this.#tilemaps.advanceAnimatedTiles(ctx.world, ctx.dt);\n }\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { defineSpriteAtlas } from \"./definition.js\";\nimport type { SpriteAtlasDefinition, SpriteFrameDefinition } from \"./definition.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The atlas importers: pure functions that turn a third-party packer document — or a plain grid\n * description — into an `ignifx.spriteatlas` document\n * (`docs/architecture/11-2d-toolkit.md` §2.3).\n *\n * Nothing here does I/O. The CLI (`ignifx import atlas`) reads the file, hands the parsed JSON to\n * one of these functions, and writes the returned document out; a game can equally call them at\n * build time from a script. Every frame rectangle stays in **image pixels with a top-left origin**,\n * which is what both TexturePacker and Aseprite emit and what the loader expects.\n *\n * Untrusted input is typed `unknown` and narrowed with the local guards below rather than asserted\n * (coding standards §5.2), so a malformed document fails with `IGX-1109` instead of producing an\n * atlas that only breaks later, at load.\n */\n\n/** The pivot a frame gets when neither the packer nor the caller names one. */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/** The prefix {@link gridAtlas} names frames with when the caller supplies none. */\nconst DEFAULT_GRID_NAME_PREFIX = \"tile\";\n\n/** The name a frame falls back to when normalisation leaves nothing usable. */\nconst FALLBACK_FRAME_NAME = \"frame\";\n\n/** A rectangle as every packer writes it: left, top, width, height, in image pixels. */\ninterface Rect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n}\n\n/** One raw frame entry paired with the key it was found under (hash key or `filename`). */\ninterface RawFrameEntry {\n readonly key: string;\n readonly entry: Record<string, unknown>;\n}\n\n/** A slice pivot lifted out of `meta.slices`, still in sprite-canvas pixels. */\ninterface SlicePivot {\n readonly frame: number;\n readonly bounds: Rect;\n readonly pivot: Vec2Like;\n}\n\n/**\n * Raises the one diagnostic these importers own.\n *\n * @param importer - The importer function's name, echoed into the message and the context.\n * @param reason - What about the document could not be read.\n * @param hint - The remedy sentence, when there is a specific one.\n * @throws IgnifxError with code `IGX-1109`, always.\n */\nfunction failImport(importer: string, reason: string, hint?: string): never {\n throw twoDError(TwoDErrorCode.unsupportedImport, `${importer} cannot read this document: ${reason}.`, {\n context: { importer },\n hint: hint ?? \"Re-export the atlas from the packer, or check that the document is the one the importer expects.\",\n });\n}\n\n/**\n * Narrows an unknown value to a plain property bag.\n *\n * @param value - The value to test.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to an array without widening it to `any[]`.\n *\n * @param value - The value to test.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to a real number.\n *\n * @param value - The value to test.\n * @returns Whether it is a finite number.\n */\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Reads a `{ x, y, w, h }` rectangle out of a property bag.\n *\n * @param entry - The bag to read from.\n * @param key - The field holding the rectangle.\n * @returns The rectangle, or `null` when the field is absent or incomplete.\n */\nfunction readRect(entry: Record<string, unknown>, key: string): Rect | null {\n const raw = entry[key];\n if (!isObject(raw)) {\n return null;\n }\n const x = raw[\"x\"];\n const y = raw[\"y\"];\n const w = raw[\"w\"];\n const h = raw[\"h\"];\n if (!isFiniteNumber(x) || !isFiniteNumber(y) || !isFiniteNumber(w) || !isFiniteNumber(h)) {\n return null;\n }\n return { x, y, w, h };\n}\n\n/**\n * Reads a `{ w, h }` size out of a property bag, as a vector.\n *\n * @param entry - The bag to read from.\n * @param key - The field holding the size.\n * @returns The size as `{ x: w, y: h }`, or `null` when the field is absent or incomplete.\n */\nfunction readSize(entry: Record<string, unknown>, key: string): Vec2Like | null {\n const raw = entry[key];\n if (!isObject(raw)) {\n return null;\n }\n const w = raw[\"w\"];\n const h = raw[\"h\"];\n if (!isFiniteNumber(w) || !isFiniteNumber(h)) {\n return null;\n }\n return { x: w, y: h };\n}\n\n/**\n * Reads an `{ x, y }` vector out of a property bag.\n *\n * @param entry - The bag to read from.\n * @param key - The field holding the vector.\n * @returns The vector, or `null` when the field is absent or incomplete.\n */\nfunction readVec2(entry: Record<string, unknown>, key: string): Vec2Like | null {\n const raw = entry[key];\n if (!isObject(raw)) {\n return null;\n }\n const x = raw[\"x\"];\n const y = raw[\"y\"];\n if (!isFiniteNumber(x) || !isFiniteNumber(y)) {\n return null;\n }\n return { x, y };\n}\n\n/**\n * Clamps a normalised coordinate into `[0, 1]`.\n *\n * @param value - The coordinate.\n * @returns The coordinate, clamped.\n */\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) {\n return 0.5;\n }\n return Math.min(Math.max(value, 0), 1);\n}\n\n/**\n * Drops a trailing file extension.\n *\n * Only a dot followed by a letter and up to seven more alphanumerics counts, so `hero_0.png` and\n * `hero 0.aseprite` lose their suffix while `walk.2` — a name, not a file — keeps it.\n *\n * @param raw - The raw frame key.\n * @returns The key without its extension.\n */\nfunction stripFileExtension(raw: string): string {\n return raw.replace(/\\.[A-Za-z][A-Za-z0-9]{0,7}$/u, \"\");\n}\n\n/**\n * Flattens a TexturePacker-shaped `frames` collection — hash or array — into ordered entries.\n *\n * @param frames - The document's `frames` field.\n * @param importer - The importer name to blame in an error.\n * @returns The entries, in document order.\n * @throws IgnifxError with code `IGX-1109` when `frames` is neither an object nor an array, or\n * holds something that is not an object.\n */\nfunction collectFrameEntries(frames: unknown, importer: string): readonly RawFrameEntry[] {\n const out: RawFrameEntry[] = [];\n if (isUnknownArray(frames)) {\n for (let index = 0; index < frames.length; index += 1) {\n const entry = frames[index];\n if (!isObject(entry)) {\n failImport(importer, `frame ${String(index)} is not an object`);\n }\n const filename = entry[\"filename\"];\n const key =\n typeof filename === \"string\" && filename !== \"\" ? filename : `${FALLBACK_FRAME_NAME}_${String(index)}`;\n out.push({ key, entry });\n }\n return out;\n }\n if (isObject(frames)) {\n const keys = Object.keys(frames);\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n if (key === undefined) {\n continue;\n }\n const entry = frames[key];\n if (!isObject(entry)) {\n failImport(importer, `frame ${key} is not an object`);\n }\n out.push({ key, entry });\n }\n return out;\n }\n return failImport(importer, \"its frames field is neither an object (hash layout) nor an array (array layout)\");\n}\n\n/**\n * Lifts every `meta.slices[].keys[]` entry that declares a pivot out of an Aseprite document.\n *\n * @param meta - The document's `meta` object, or `null` when it has none.\n * @returns The slice pivots, in document order.\n */\nfunction collectSlicePivots(meta: Record<string, unknown> | null): readonly SlicePivot[] {\n const out: SlicePivot[] = [];\n if (meta === null) {\n return out;\n }\n const slices = meta[\"slices\"];\n if (!isUnknownArray(slices)) {\n return out;\n }\n for (let sliceIndex = 0; sliceIndex < slices.length; sliceIndex += 1) {\n const slice = slices[sliceIndex];\n if (!isObject(slice)) {\n continue;\n }\n const keys = slice[\"keys\"];\n if (!isUnknownArray(keys)) {\n continue;\n }\n for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {\n const key = keys[keyIndex];\n if (!isObject(key)) {\n continue;\n }\n const pivot = readVec2(key, \"pivot\");\n const bounds = readRect(key, \"bounds\");\n if (pivot === null || bounds === null) {\n continue;\n }\n const frame = key[\"frame\"];\n out.push({ frame: isFiniteNumber(frame) ? frame : 0, bounds, pivot });\n }\n }\n return out;\n}\n\n/**\n * Picks the slice pivot that applies to one frame and normalises it into `[0, 1]`.\n *\n * @param pivots - Every slice pivot in the document.\n * @param frameIndex - The frame's index in the document's own frame order.\n * @param sourceWidth - The untrimmed frame width the pivot is measured against.\n * @param sourceHeight - The untrimmed frame height the pivot is measured against.\n * @returns The normalised pivot, or `null` when no slice covers the frame.\n */\nfunction slicePivotFor(\n pivots: readonly SlicePivot[],\n frameIndex: number,\n sourceWidth: number,\n sourceHeight: number,\n): Vec2Like | null {\n if (!(sourceWidth > 0) || !(sourceHeight > 0)) {\n return null;\n }\n let best: SlicePivot | null = null;\n for (let index = 0; index < pivots.length; index += 1) {\n const candidate = pivots[index];\n if (candidate === undefined || candidate.frame > frameIndex) {\n continue;\n }\n if (best === null || candidate.frame > best.frame) {\n best = candidate;\n }\n }\n if (best === null) {\n return null;\n }\n return {\n x: clamp01((best.bounds.x + best.pivot.x) / sourceWidth),\n y: clamp01((best.bounds.y + best.pivot.y) / sourceHeight),\n };\n}\n\n/**\n * Normalises an Aseprite frame key into an identifier a clip and a `#frame:` fragment can name.\n *\n * The rule, applied in this order:\n *\n * 1. Drop a trailing file extension — a dot, a letter, then up to seven more alphanumerics — so\n * `hero 0.aseprite` and `hero_0.png` both lose their suffix but `walk.2` does not.\n * 2. Replace every run of non-alphanumeric characters with a single `_`.\n * 3. Trim leading and trailing `_`.\n *\n * Case is preserved: `Hero (Idle) 0.aseprite` becomes `Hero_Idle_0`, not `hero_idle_0`. A key that\n * normalises to nothing at all (`\"###.png\"`) becomes `frame`.\n *\n * {@link importAsepriteAtlas} and `importAsepriteAnimations` both run keys through this function,\n * which is what makes an imported clip's frame names line up with the imported atlas's.\n *\n * @param raw - The frame key as Aseprite wrote it — a hash key, or an array entry's `filename`.\n * @returns The normalised frame name.\n *\n * @example\n * ```ts\n * asepriteFrameName(\"hero (idle) 0.aseprite\"); // \"hero_idle_0\"\n * asepriteFrameName(\"hero_0.png\"); // \"hero_0\"\n * ```\n *\n * @public\n */\nexport function asepriteFrameName(raw: string): string {\n const normalised = stripFileExtension(raw)\n .replaceAll(/[^0-9A-Za-z]+/gu, \"_\")\n .replace(/^_+/u, \"\")\n .replace(/_+$/u, \"\");\n return normalised === \"\" ? FALLBACK_FRAME_NAME : normalised;\n}\n\n/**\n * What {@link gridAtlas} needs to cut an evenly spaced sheet into frames.\n *\n * @public\n */\nexport interface GridAtlasImportOptions {\n /** The address of the image the frames are cut from. */\n readonly image: string;\n /** The image's full width, in pixels. */\n readonly imageWidth: number;\n /** The image's full height, in pixels. */\n readonly imageHeight: number;\n /** One cell's width, in pixels. Must be positive. */\n readonly cellWidth: number;\n /** One cell's height, in pixels. Must be positive. */\n readonly cellHeight: number;\n /** How many columns to emit. Defaults to as many as the image holds; clamped to that. */\n readonly columns?: number;\n /** How many rows to emit. Defaults to as many as the image holds; clamped to that. */\n readonly rows?: number;\n /** The border left around the whole grid, in pixels. Defaults to `0`. */\n readonly margin?: number;\n /** The gap between adjacent cells, in pixels. Defaults to `0`. */\n readonly spacing?: number;\n /** The pivot every frame gets, in `[0, 1]`. Defaults to the centre. */\n readonly pivot?: Vec2Like;\n /** The `<prefix>_<index>` frame names use. Defaults to `\"tile\"`. */\n readonly namePrefix?: string;\n /** The min/mag filter. Defaults to `\"linear\"`; pixel art wants `\"nearest\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n}\n\n/**\n * Cuts an evenly spaced sprite sheet into an `ignifx.spriteatlas` document.\n *\n * Frames come out in reading order — left to right, then top to bottom — named\n * `<namePrefix>_<index>` with `index` counting from `0` across the whole sheet, so a 4×2\n * grid ends at `tile_7`. `columns` and `rows` default to as many whole cells as the image holds\n * (`floor((imageWidth - 2·margin + spacing) / (cellWidth + spacing))`, and likewise for rows) and\n * are clamped to that capacity when given, so an over-large explicit count never produces a frame\n * that falls off the image.\n *\n * @remarks\n * `namePrefix` is how a grid atlas lines up with the rest of the toolkit: `@ignifx/2d`'s Tiled\n * importer names a tileset's frames `<tilesetName>_<index>`, so passing the tileset's name\n * as `namePrefix` makes a hand-cut grid atlas addressable by exactly the names a tilemap emits.\n *\n * @param options - The sheet's geometry and the frame naming.\n * @returns The complete atlas document.\n * @throws IgnifxError with code `IGX-1109` when a cell dimension is not positive, or when the\n * geometry yields no frames at all.\n *\n * @example\n * ```ts\n * const atlas = gridAtlas({\n * image: \"2d/terrain.png\",\n * imageWidth: 64,\n * imageHeight: 64,\n * cellWidth: 32,\n * cellHeight: 32,\n * namePrefix: \"terrain\",\n * sampling: \"nearest\",\n * });\n * atlas.frames.map((frame) => frame.name); // [\"terrain_0\", \"terrain_1\", \"terrain_2\", \"terrain_3\"]\n * ```\n *\n * @public\n */\nexport function gridAtlas(options: GridAtlasImportOptions): SpriteAtlasDefinition {\n const importer = \"gridAtlas\";\n const { cellWidth, cellHeight, imageWidth, imageHeight } = options;\n if (!(cellWidth > 0) || !(cellHeight > 0)) {\n failImport(\n importer,\n `the cell size ${String(cellWidth)}x${String(cellHeight)} is not positive`,\n \"Pass the cell size in pixels; both cellWidth and cellHeight must be greater than zero.\",\n );\n }\n const margin = options.margin ?? 0;\n const spacing = options.spacing ?? 0;\n const capacityColumns = gridCapacity(imageWidth, cellWidth, margin, spacing);\n const capacityRows = gridCapacity(imageHeight, cellHeight, margin, spacing);\n const columns =\n options.columns === undefined ? capacityColumns : Math.min(clampCount(options.columns), capacityColumns);\n const rows = options.rows === undefined ? capacityRows : Math.min(clampCount(options.rows), capacityRows);\n if (columns === 0 || rows === 0) {\n failImport(\n importer,\n `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`,\n \"Check the image size, the cell size, the margin, and the spacing against the sheet.\",\n );\n }\n const prefix = options.namePrefix ?? DEFAULT_GRID_NAME_PREFIX;\n const pivot = options.pivot ?? CENTRE_PIVOT;\n const frames: SpriteFrameDefinition[] = [];\n for (let row = 0; row < rows; row += 1) {\n for (let column = 0; column < columns; column += 1) {\n frames.push({\n name: `${prefix}_${String(row * columns + column)}`,\n x: margin + column * (cellWidth + spacing),\n y: margin + row * (cellHeight + spacing),\n w: cellWidth,\n h: cellHeight,\n pivot: { x: pivot.x, y: pivot.y },\n });\n }\n }\n return defineSpriteAtlas(\n {\n image: options.image,\n ...(options.sampling === undefined ? {} : { sampling: options.sampling }),\n ...(options.premultipliedAlpha === undefined ? {} : { premultipliedAlpha: options.premultipliedAlpha }),\n frames,\n },\n options.image,\n );\n}\n\n/**\n * How many whole cells fit along one axis.\n *\n * @param extent - The image's size along the axis, in pixels.\n * @param cell - One cell's size along the axis, in pixels.\n * @param margin - The border left at both ends, in pixels.\n * @param spacing - The gap between adjacent cells, in pixels.\n * @returns The cell count, never negative.\n */\nfunction gridCapacity(extent: number, cell: number, margin: number, spacing: number): number {\n const usable = extent - 2 * margin + spacing;\n const count = Math.floor(usable / (cell + spacing));\n return Number.isFinite(count) && count > 0 ? count : 0;\n}\n\n/**\n * Coerces a caller-supplied count into a non-negative whole number.\n *\n * @param value - The requested count.\n * @returns The count, truncated and floored at zero.\n */\nfunction clampCount(value: number): number {\n return Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\n/**\n * What {@link importTexturePackerAtlas} accepts alongside the document.\n *\n * @public\n */\nexport interface TexturePackerImportOptions {\n /** The image address to write into the atlas. Defaults to the document's `meta.image`. */\n readonly image?: string;\n /** Whether to keep the `.png` on frame names. Defaults to `false`, which strips it. */\n readonly keepExtensions?: boolean;\n /** The min/mag filter. Defaults to `\"linear\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n}\n\n/**\n * Converts a TexturePacker JSON export into an `ignifx.spriteatlas` document.\n *\n * Both of TexturePacker's JSON layouts are read and produce identical output for the same sheet:\n * the **hash** layout, whose `frames` is an object keyed by file name, and the **array** layout,\n * whose `frames` is an array of entries carrying a `filename`. Frame names lose their trailing file\n * extension (`hero_0.png` becomes `hero_0`) unless `keepExtensions` is set.\n *\n * A frame's `pivot` is used as-is when the document declares one: TexturePacker already writes\n * pivots normalised into `[0, 1]` against a top-left origin, which is exactly ignifx's convention.\n * Frames without one get the centre. A frame marked `trimmed` carries its `sourceSize` through so\n * the loader can lay the trimmed rectangle back inside its original bounds.\n *\n * @remarks\n * Rotated frames are rejected rather than silently drawn wrong — the sprite pipeline has no\n * per-frame rotation flag.\n *\n * `spriteSourceSize`'s **offset** (`x`/`y`) has no home in `SpriteFrameDefinition`, which records\n * only the untrimmed size, so a trimmed frame whose art is not centred in its source bounds may sit\n * slightly off. Pack with trimming disabled, or with `spriteSourceSize` centred, when that matters.\n *\n * @param json - The parsed TexturePacker document.\n * @param options - The image override, name handling, and sampling.\n * @returns The complete atlas document.\n * @throws IgnifxError with code `IGX-1109` when the document is not an object, when `frames` is\n * neither an object nor an array, when it is empty, when no image address can be found, when a\n * frame has no rectangle, or when a frame is rotated.\n *\n * @example\n * ```ts\n * const atlas = importTexturePackerAtlas(JSON.parse(text), { image: \"2d/hero.png\" });\n * atlas.frames[0]?.name; // \"hero_0\"\n * ```\n *\n * @public\n */\nexport function importTexturePackerAtlas(json: unknown, options?: TexturePackerImportOptions): SpriteAtlasDefinition {\n const importer = \"importTexturePackerAtlas\";\n if (!isObject(json)) {\n failImport(importer, \"the document is not a JSON object\");\n }\n const meta = isObject(json[\"meta\"]) ? json[\"meta\"] : null;\n const entries = collectFrameEntries(json[\"frames\"], importer);\n if (entries.length === 0) {\n failImport(importer, \"it declares no frames\");\n }\n const image = resolveImage(options?.image, meta, importer);\n const keepExtensions = options?.keepExtensions ?? false;\n const frames: SpriteFrameDefinition[] = [];\n for (let index = 0; index < entries.length; index += 1) {\n const item = entries[index];\n if (item === undefined) {\n continue;\n }\n if (item.entry[\"rotated\"] === true) {\n failImport(\n importer,\n `frame ${item.key} is rotated`,\n \"TexturePacker rotated frames are not supported; disable rotation when packing.\",\n );\n }\n const rect = readRect(item.entry, \"frame\");\n if (rect === null) {\n failImport(importer, `frame ${item.key} has no {x, y, w, h} frame rectangle`);\n }\n const pivot = readVec2(item.entry, \"pivot\") ?? CENTRE_PIVOT;\n const sourceSize = item.entry[\"trimmed\"] === true ? readSize(item.entry, \"sourceSize\") : null;\n frames.push({\n name: keepExtensions ? item.key : stripFileExtension(item.key),\n x: rect.x,\n y: rect.y,\n w: rect.w,\n h: rect.h,\n pivot: { x: pivot.x, y: pivot.y },\n ...(sourceSize === null ? {} : { sourceSize }),\n });\n }\n return defineSpriteAtlas(\n {\n image,\n ...(options?.sampling === undefined ? {} : { sampling: options.sampling }),\n ...(options?.premultipliedAlpha === undefined ? {} : { premultipliedAlpha: options.premultipliedAlpha }),\n frames,\n },\n image,\n );\n}\n\n/**\n * Picks the image address an imported atlas points at.\n *\n * @param override - The caller's `options.image`, when given.\n * @param meta - The document's `meta` object, or `null`.\n * @param importer - The importer name to blame in an error.\n * @returns The image address.\n * @throws IgnifxError with code `IGX-1109` when neither source names an image.\n */\nfunction resolveImage(override: string | undefined, meta: Record<string, unknown> | null, importer: string): string {\n if (override !== undefined && override !== \"\") {\n return override;\n }\n const fromMeta = meta === null ? undefined : meta[\"image\"];\n if (typeof fromMeta === \"string\" && fromMeta !== \"\") {\n return fromMeta;\n }\n return failImport(\n importer,\n \"neither options.image nor meta.image names an image\",\n \"Pass options.image, or re-export the sheet with the image name included in its metadata.\",\n );\n}\n\n/**\n * What {@link importAsepriteAtlas} accepts alongside the document.\n *\n * @public\n */\nexport interface AsepriteImportOptions {\n /** The image address to write into the atlas. Defaults to the document's `meta.image`. */\n readonly image?: string;\n /** The min/mag filter. Defaults to `\"linear\"`; pixel art wants `\"nearest\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n}\n\n/**\n * Converts an Aseprite JSON sheet export into an `ignifx.spriteatlas` document.\n *\n * Aseprite writes a TexturePacker-shaped document — `frames` as either a hash or an array,\n * `meta.image`, `meta.size` — plus its own `meta.frameTags`, `meta.slices` and `meta.layers`. The\n * frame keys it produces are file-ish (`hero 0.aseprite`, `hero (idle) 0.aseprite`), so every one\n * is put through {@link asepriteFrameName}; `importAsepriteAnimations` uses the same normaliser,\n * which is what makes the imported clips and the imported atlas agree on names.\n *\n * A trimmed frame keeps its `sourceSize` so the loader can place the trimmed rectangle back inside\n * its original bounds.\n *\n * @remarks\n * Pivots are **best-effort**. Aseprite has no per-frame pivot; it has slices, which carry an\n * optional pivot in sprite-canvas pixels relative to the slice's own bounds and apply from their\n * key's `frame` index onwards. This importer takes the slice key with the greatest `frame` index at\n * or below the frame being converted (ties going to the earlier slice in document order) and\n * normalises `bounds + pivot` against the frame's untrimmed size, clamped into `[0, 1]`. That is\n * right for the common case — one slice covering the character, authored on an untrimmed sheet —\n * and approximate for anything else. Frames no slice covers get the centre.\n *\n * @param json - The parsed Aseprite document.\n * @param options - The image override and sampling.\n * @returns The complete atlas document.\n * @throws IgnifxError with code `IGX-1109` when the document is not an object, when `frames` is\n * neither an object nor an array, when it is empty, when no image address can be found, or when a\n * frame has no rectangle.\n *\n * @example\n * ```ts\n * const atlas = importAsepriteAtlas(JSON.parse(text), { sampling: \"nearest\" });\n * atlas.frames[0]?.name; // \"hero_idle_0\", from the key \"hero (idle) 0.aseprite\"\n * ```\n *\n * @public\n */\nexport function importAsepriteAtlas(json: unknown, options?: AsepriteImportOptions): SpriteAtlasDefinition {\n const importer = \"importAsepriteAtlas\";\n if (!isObject(json)) {\n failImport(importer, \"the document is not a JSON object\");\n }\n const meta = isObject(json[\"meta\"]) ? json[\"meta\"] : null;\n const entries = collectFrameEntries(json[\"frames\"], importer);\n if (entries.length === 0) {\n failImport(importer, \"it declares no frames\");\n }\n const image = resolveImage(options?.image, meta, importer);\n const slicePivots = collectSlicePivots(meta);\n const frames: SpriteFrameDefinition[] = [];\n for (let index = 0; index < entries.length; index += 1) {\n const item = entries[index];\n if (item === undefined) {\n continue;\n }\n const rect = readRect(item.entry, \"frame\");\n if (rect === null) {\n failImport(importer, `frame ${item.key} has no {x, y, w, h} frame rectangle`);\n }\n const declaredSource = readSize(item.entry, \"sourceSize\");\n const trimmed = item.entry[\"trimmed\"] === true;\n const sourceWidth = declaredSource === null ? rect.w : declaredSource.x;\n const sourceHeight = declaredSource === null ? rect.h : declaredSource.y;\n const pivot = slicePivotFor(slicePivots, index, sourceWidth, sourceHeight) ?? CENTRE_PIVOT;\n frames.push({\n name: asepriteFrameName(item.key),\n x: rect.x,\n y: rect.y,\n w: rect.w,\n h: rect.h,\n pivot: { x: pivot.x, y: pivot.y },\n ...(trimmed && declaredSource !== null ? { sourceSize: declaredSource } : {}),\n });\n }\n return defineSpriteAtlas(\n {\n image,\n ...(options?.sampling === undefined ? {} : { sampling: options.sampling }),\n ...(options?.premultipliedAlpha === undefined ? {} : { premultipliedAlpha: options.premultipliedAlpha }),\n frames,\n },\n image,\n );\n}\n","import { asepriteFrameName } from \"../atlas/importers.js\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { defineSpriteAnimation } from \"./definition.js\";\nimport type { SpriteAnimationDefinition, SpriteClipDefinition } from \"./definition.js\";\n\n/**\n * The animation importer: a pure function that turns an Aseprite sheet export's tags into an\n * `ignifx.spriteanimation` document (`docs/architecture/11-2d-toolkit.md` §2.4).\n *\n * It reads the same document `importAsepriteAtlas` reads and names frames with the same\n * normaliser, so an atlas and an animation set imported from one export always agree on frame\n * names. Nothing here does I/O; the CLI reads the file and writes the result.\n */\n\n/** The frames-per-second a tag falls back to when Aseprite recorded no usable durations. */\nconst FALLBACK_FPS = 12;\n\n/** How many decimal places a derived frames-per-second keeps. */\nconst FPS_DECIMALS = 3;\n\n/** The `repeat` value Aseprite writes for a tag that plays exactly once. */\nconst PLAY_ONCE_REPEAT = \"1\";\n\n/** One frame of the document, reduced to what a clip needs. */\ninterface FrameRecord {\n readonly key: string;\n readonly duration: number;\n}\n\n/**\n * Raises the one diagnostic this importer owns.\n *\n * @param reason - What about the document could not be read.\n * @param hint - The remedy sentence, when there is a specific one.\n * @throws IgnifxError with code `IGX-1109`, always.\n */\nfunction failImport(reason: string, hint?: string): never {\n throw twoDError(TwoDErrorCode.unsupportedImport, `importAsepriteAnimations cannot read this document: ${reason}.`, {\n context: { importer: \"importAsepriteAnimations\" },\n hint: hint ?? \"Re-export the sheet from Aseprite with `JSON Data` and `Meta: Tags` enabled.\",\n });\n}\n\n/**\n * Narrows an unknown value to a plain property bag.\n *\n * @param value - The value to test.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to an array without widening it to `any[]`.\n *\n * @param value - The value to test.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to a real number.\n *\n * @param value - The value to test.\n * @returns Whether it is a finite number.\n */\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Reads the per-frame duration, in milliseconds, out of one frame entry.\n *\n * @param entry - The frame entry.\n * @returns The duration, or `0` when the entry declares none.\n */\nfunction readDuration(entry: Record<string, unknown>): number {\n const duration = entry[\"duration\"];\n return isFiniteNumber(duration) && duration > 0 ? duration : 0;\n}\n\n/**\n * Flattens the document's `frames` collection — hash or array — into ordered records.\n *\n * @param frames - The document's `frames` field.\n * @returns The records in document order; empty when `frames` is unreadable.\n */\nfunction collectFrames(frames: unknown): readonly FrameRecord[] {\n const out: FrameRecord[] = [];\n if (isUnknownArray(frames)) {\n for (let index = 0; index < frames.length; index += 1) {\n const entry = frames[index];\n if (!isObject(entry)) {\n continue;\n }\n const filename = entry[\"filename\"];\n out.push({\n key: typeof filename === \"string\" && filename !== \"\" ? filename : `frame_${String(index)}`,\n duration: readDuration(entry),\n });\n }\n return out;\n }\n if (isObject(frames)) {\n const keys = Object.keys(frames);\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n if (key === undefined) {\n continue;\n }\n const entry = frames[key];\n if (!isObject(entry)) {\n continue;\n }\n out.push({ key, duration: readDuration(entry) });\n }\n return out;\n }\n return out;\n}\n\n/**\n * Rounds a derived frames-per-second to {@link FPS_DECIMALS} places.\n *\n * @param value - The unrounded rate.\n * @returns The rounded rate.\n */\nfunction roundFps(value: number): number {\n const scale = 10 ** FPS_DECIMALS;\n return Math.round(value * scale) / scale;\n}\n\n/**\n * What {@link importAsepriteAnimations} accepts alongside the document.\n *\n * @public\n */\nexport interface AsepriteAnimationImportOptions {\n /** The `.atlas.json` address the clips index into. Defaults to `\"\"`, the renderer's own atlas. */\n readonly atlas?: string;\n /** The rate a tag gets when Aseprite recorded no usable frame durations. Defaults to `12`. */\n readonly defaultFps?: number;\n /**\n * Names the atlas frame at a document frame index. Defaults to the same normalisation\n * `importAsepriteAtlas` applies to the document's own frame keys, which is what makes the two\n * imports agree; override it when the atlas was produced some other way.\n */\n readonly frameNameOf?: (index: number) => string;\n}\n\n/**\n * Converts an Aseprite sheet export's tags into an `ignifx.spriteanimation` document.\n *\n * Every entry in `meta.frameTags` becomes one clip, named after the tag, listing the frame names\n * for indices `from` through `to` explicitly rather than as a range — a clip that lists names\n * survives an atlas being repacked in a different order.\n *\n * Playback direction is baked into that list, because ignifx clips play forwards:\n *\n * - `\"forward\"` (and anything unrecognised) lists `from … to` in order.\n * - `\"reverse\"` lists them backwards.\n * - `\"pingpong\"` lists them forwards and then appends the **interior** frames in reverse, so a\n * three-frame tag becomes `0, 1, 2, 1` — the ends are not repeated, which is what makes the clip\n * loop seamlessly.\n *\n * `loop` is `true` unless the tag's `repeat` is the string `\"1\"`, Aseprite's \"play once\".\n *\n * @remarks\n * Aseprite stores a duration **per frame**, in milliseconds, while an ignifx clip carries a single\n * `fps`. A tag is therefore approximated by the mean of its frames' durations: `fps` is\n * `1000 / averageDuration`, rounded to three decimal places. A tag whose frames all share a\n * duration converts exactly; one with uneven durations does not, and the individual frames will\n * hold for the average instead of their authored time. Split such a tag, or even the durations out\n * in Aseprite, when the timing matters. When no frame in the range declares a positive duration,\n * `options.defaultFps` — itself defaulting to `12` — is used instead.\n *\n * Aseprite has no frame-event concept, so no clip carries `events`.\n *\n * @param json - The parsed Aseprite document.\n * @param options - The atlas address, the fallback rate, and a frame-naming override.\n * @returns The complete animation document, already through `defineSpriteAnimation`.\n * @throws IgnifxError with code `IGX-1109` when the document is not an object, when\n * `meta.frameTags` is missing, is not an array, or is empty, when a tag has no name, or when\n * frames cannot be named because the document has no readable `frames` and no `frameNameOf` was\n * supplied.\n *\n * @example\n * ```ts\n * const animations = importAsepriteAnimations(JSON.parse(text), { atlas: \"2d/hero.atlas.json\" });\n * animations.clips[0]; // { name: \"idle\", frames: [\"hero_0\", \"hero_1\"], fps: 10, loop: true }\n * ```\n *\n * @public\n */\nexport function importAsepriteAnimations(\n json: unknown,\n options?: AsepriteAnimationImportOptions,\n): SpriteAnimationDefinition {\n if (!isObject(json)) {\n failImport(\"the document is not a JSON object\");\n }\n const meta = isObject(json[\"meta\"]) ? json[\"meta\"] : null;\n const tags = meta === null ? undefined : meta[\"frameTags\"];\n if (!isUnknownArray(tags) || tags.length === 0) {\n failImport(\n \"it declares no meta.frameTags, and tags are what become clips\",\n \"Re-export from Aseprite with `Meta: Tags` ticked, and tag the animations in the timeline first.\",\n );\n }\n const records = collectFrames(json[\"frames\"]);\n const nameOf = options?.frameNameOf;\n if (nameOf === undefined && records.length === 0) {\n failImport(\n \"it declares no readable frames, so tag indices cannot be turned into frame names\",\n \"Re-export with `Meta: Frames` included, or pass options.frameNameOf to name frames yourself.\",\n );\n }\n const defaultFps = options?.defaultFps ?? FALLBACK_FPS;\n const clips: SpriteClipDefinition[] = [];\n for (let index = 0; index < tags.length; index += 1) {\n const tag = tags[index];\n if (!isObject(tag)) {\n failImport(`tag ${String(index)} is not an object`);\n }\n const name = tag[\"name\"];\n if (typeof name !== \"string\" || name === \"\") {\n failImport(`tag ${String(index)} has no name`);\n }\n const rawFrom = tag[\"from\"];\n const rawTo = tag[\"to\"];\n const first = isFiniteNumber(rawFrom) && rawFrom > 0 ? Math.trunc(rawFrom) : 0;\n const last = isFiniteNumber(rawTo) && rawTo > first ? Math.trunc(rawTo) : first;\n const ordered = orderedFrameNames(first, last, tag[\"direction\"], records, nameOf);\n clips.push({\n name,\n frames: ordered,\n fps: tagFps(records, first, last, defaultFps),\n loop: tag[\"repeat\"] !== PLAY_ONCE_REPEAT,\n });\n }\n return defineSpriteAnimation({ ...(options?.atlas === undefined ? {} : { atlas: options.atlas }), clips });\n}\n\n/**\n * Builds one tag's frame-name list, with its direction already baked in.\n *\n * @param first - The tag's first frame index.\n * @param last - The tag's last frame index, inclusive.\n * @param direction - The tag's `direction` field, unnarrowed.\n * @param records - The document's frames, in order.\n * @param nameOf - The caller's frame namer, or `undefined` to use the document's own keys.\n * @returns The frame names in play order.\n */\nfunction orderedFrameNames(\n first: number,\n last: number,\n direction: unknown,\n records: readonly FrameRecord[],\n nameOf: ((index: number) => string) | undefined,\n): readonly string[] {\n const forward: string[] = [];\n for (let index = first; index <= last; index += 1) {\n forward.push(frameNameAt(index, records, nameOf));\n }\n if (direction === \"reverse\") {\n return forward.toReversed();\n }\n if (direction === \"pingpong\") {\n const out = forward.slice();\n for (let index = forward.length - 2; index >= 1; index -= 1) {\n const name = forward[index];\n if (name !== undefined) {\n out.push(name);\n }\n }\n return out;\n }\n return forward;\n}\n\n/**\n * Names the atlas frame at one document frame index.\n *\n * @param index - The frame index the tag refers to.\n * @param records - The document's frames, in order.\n * @param nameOf - The caller's frame namer, or `undefined` to use the document's own keys.\n * @returns The atlas frame name.\n */\nfunction frameNameAt(\n index: number,\n records: readonly FrameRecord[],\n nameOf: ((index: number) => string) | undefined,\n): string {\n if (nameOf !== undefined) {\n return nameOf(index);\n }\n const record = records[index];\n return asepriteFrameName(record === undefined ? `frame_${String(index)}` : record.key);\n}\n\n/**\n * Derives a tag's frames-per-second from the mean of its frames' durations.\n *\n * @param records - The document's frames, in order.\n * @param first - The tag's first frame index.\n * @param last - The tag's last frame index, inclusive.\n * @param defaultFps - The rate to fall back to when no duration is usable.\n * @returns The rate, rounded to three decimal places.\n */\nfunction tagFps(records: readonly FrameRecord[], first: number, last: number, defaultFps: number): number {\n let total = 0;\n let count = 0;\n for (let index = first; index <= last; index += 1) {\n const record = records[index];\n if (record === undefined || record.duration <= 0) {\n continue;\n }\n total += record.duration;\n count += 1;\n }\n if (count === 0 || total <= 0) {\n return defaultFps;\n }\n return roundFps(1000 / (total / count));\n}\n","/**\n * Resolving one document's reference to another (`docs/architecture/05-assets-and-loading.md` §2).\n *\n * Every reference `@ignifx/2d` reads out of a file — an atlas's `image`, an animation document's\n * `atlas`, a tilemap tileset's `atlas` — is interpreted **relative to the document that names it**,\n * which is what every atlas packer and map editor emits. The same arithmetic serves an address and\n * a URL, because both are `/`-separated paths.\n */\n\n/** The URL schemes that are never joined to a base. */\nconst ABSOLUTE_PREFIXES: readonly string[] = Object.freeze([\"http://\", \"https://\", \"blob:\", \"data:\", \"//\"]);\n\n/**\n * Resolves a document-relative reference against the document's own address or URL.\n *\n * @remarks\n * A reference that is absolute — one of the recognised URL schemes, or one starting with `/` — is\n * returned untouched, so a project that prefers project-root addresses can write them. `.` and `..`\n * segments are collapsed, and a base with no `/` at all is treated as a file in the root.\n *\n * @param base - The address or URL of the document holding the reference.\n * @param reference - What the document wrote.\n * @returns The resolved address or URL.\n *\n * @example\n * ```ts\n * resolveRelative(\"2d/hero.atlas.json\", \"hero.png\"); // \"2d/hero.png\"\n * resolveRelative(\"2d/hero.atlas.json\", \"../shared/pal.png\"); // \"shared/pal.png\"\n * resolveRelative(\"2d/hero.atlas.json\", \"/sprites/hero.png\"); // \"/sprites/hero.png\"\n * ```\n *\n * @public\n */\nexport function resolveRelative(base: string, reference: string): string {\n if (reference === \"\") {\n return \"\";\n }\n if (reference.startsWith(\"/\")) {\n return reference;\n }\n for (let index = 0; index < ABSOLUTE_PREFIXES.length; index += 1) {\n const prefix = ABSOLUTE_PREFIXES[index];\n if (prefix !== undefined && reference.startsWith(prefix)) {\n return reference;\n }\n }\n const cut = base.lastIndexOf(\"/\");\n const directory = cut < 0 ? \"\" : base.slice(0, cut);\n const joined = directory === \"\" ? reference : `${directory}/${reference}`;\n return normalisePath(joined);\n}\n\n/**\n * Collapses `.` and `..` segments in a `/`-separated path.\n *\n * @param path - The path to normalise.\n * @returns The normalised path; leading `..` segments that escape the root are dropped.\n *\n * @public\n */\nexport function normalisePath(path: string): string {\n const segments = path.split(\"/\");\n const out: string[] = [];\n for (let index = 0; index < segments.length; index += 1) {\n const segment = segments[index];\n if (segment === undefined || segment === \"\" || segment === \".\") {\n continue;\n }\n if (segment === \"..\") {\n out.pop();\n continue;\n }\n out.push(segment);\n }\n return out.join(\"/\");\n}\n\n/**\n * Whether a reference is a URL in its own right rather than an address: root-relative (`/…`),\n * protocol-relative (`//…`), or carrying a scheme (`http(s)://`, `blob:`, `data:`).\n *\n * @param reference - The reference as written in a document.\n * @returns `true` when the reference must be fetched verbatim rather than resolved through the manifest.\n */\nexport function isAbsoluteReference(reference: string): boolean {\n if (reference.startsWith(\"/\")) {\n return true;\n }\n for (let index = 0; index < ABSOLUTE_PREFIXES.length; index += 1) {\n const prefix = ABSOLUTE_PREFIXES[index];\n if (prefix !== undefined && reference.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n}\n","import { resolveRelative } from \"../assets/relative.js\";\nimport { defineSpriteAnimation, SPRITE_ANIMATION_ASSET_TYPE, SPRITE_ANIMATION_FILE_EXTENSIONS } from \"./definition.js\";\nimport { SpriteAnimationAsset } from \"./sprite-animation-asset.js\";\nimport type { SpriteAnimationInput } from \"./definition.js\";\nimport type { AssetLoader, LoaderContext } from \"@ignifx/core\";\n\n/**\n * The `spriteanimation` asset loader (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * The document is pure data — clip names, frame names, rates — so the loader needs no device and\n * behaves identically under a headless app. It does not load the atlas it names: a `SpriteAnimator`\n * already has one on its `SpriteRenderer`, and forcing a second copy would double the upload.\n * `SpriteAnimationAsset.atlasAddress` carries the reference for a game that wants to load it.\n */\n\n/**\n * Builds the loader for `.spriteanim.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createSpriteAnimationLoader());\n * ```\n *\n * @public\n */\nexport function createSpriteAnimationLoader(): AssetLoader<SpriteAnimationAsset> {\n return {\n type: SPRITE_ANIMATION_ASSET_TYPE,\n extensions: SPRITE_ANIMATION_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<SpriteAnimationAsset> {\n const raw = await ctx.fetchJson<SpriteAnimationInput>();\n const definition = defineSpriteAnimation(raw, ctx.address);\n const atlasAddress = definition.atlas === \"\" ? \"\" : resolveRelative(ctx.address, definition.atlas);\n return new SpriteAnimationAsset(ctx.address, definition, atlasAddress);\n },\n };\n}\n","import type { SpriteAtlas, SpriteFrame, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * The atlas half of the Babylon Lite sprite adapter: turning pixel rectangles into the normalised\n * UV records Lite's `SpriteAtlas` holds (`index.d.ts` 12041 and 12156).\n *\n * A `SpriteAtlas` is pure data — `{ texture, textureSizePx, frames, premultipliedAlpha }` — so\n * building one touches no device and this module stays Node-testable. Only the texture behind it\n * needs a GPU, and that lives in `./gpu/texture.ts`.\n *\n * Everything here is `@internal`.\n */\n\n/**\n * One frame rectangle in image pixels, top-left origin — the shape a `.atlas.json` document and\n * every importer speak.\n *\n * @internal\n */\nexport interface FrameRect {\n /** The frame's name, carried onto `SpriteFrame.name`. */\n readonly name: string;\n /** The left edge, in image pixels. */\n readonly x: number;\n /** The top edge, in image pixels. */\n readonly y: number;\n /** The width, in image pixels. */\n readonly w: number;\n /** The height, in image pixels. */\n readonly h: number;\n /** The pivot in `[0, 1]` of the frame, `[0, 0]` top-left. */\n readonly pivotX: number;\n /** The pivot in `[0, 1]` of the frame. */\n readonly pivotY: number;\n /** The drawn size in pixels, which differs from `w`/`h` only for a trimmed frame. */\n readonly sourceW: number;\n /** The drawn size in pixels. */\n readonly sourceH: number;\n}\n\n/**\n * Converts pixel rectangles into Lite `SpriteFrame` records.\n *\n * @remarks\n * Lite's sprite UVs are **top-down**: `uvMin` is the frame's top-left corner in `[0, 1]`, which is\n * why the atlas texture is uploaded with `invertY: false` (Lite's own `loadSpriteAtlas` does the\n * same — `lib/sprite/shared/sprite-atlas.js`, \"Sprite UVs are top-down (origin at image\n * top-left); do not flip\").\n *\n * @param frames - The rectangles, in the order they should be indexed.\n * @param textureWidth - The atlas image width, in pixels.\n * @param textureHeight - The atlas image height, in pixels.\n * @returns The Lite frame records.\n *\n * @internal\n */\nexport function toSpriteFrames(\n frames: readonly FrameRect[],\n textureWidth: number,\n textureHeight: number,\n): readonly SpriteFrame[] {\n const width = textureWidth > 0 ? textureWidth : 1;\n const height = textureHeight > 0 ? textureHeight : 1;\n const out: SpriteFrame[] = [];\n for (let index = 0; index < frames.length; index += 1) {\n const rect = frames[index];\n if (rect === undefined) {\n continue;\n }\n out.push({\n name: rect.name,\n uvMin: [rect.x / width, rect.y / height],\n uvMax: [(rect.x + rect.w) / width, (rect.y + rect.h) / height],\n sourceSizePx: [rect.sourceW, rect.sourceH],\n pivot: [rect.pivotX, rect.pivotY],\n });\n }\n return out;\n}\n\n/**\n * Assembles a `SpriteAtlas` from a texture and pixel rectangles.\n *\n * @param texture - The uploaded atlas image.\n * @param textureWidth - Its width, in pixels.\n * @param textureHeight - Its height, in pixels.\n * @param frames - The rectangles.\n * @param premultipliedAlpha - Whether the image's RGB is already multiplied by its alpha.\n * @returns The atlas.\n *\n * @internal\n */\nexport function buildAtlas(\n texture: Texture2D,\n textureWidth: number,\n textureHeight: number,\n frames: readonly FrameRect[],\n premultipliedAlpha: boolean,\n): SpriteAtlas {\n return {\n texture,\n textureSizePx: [textureWidth, textureHeight],\n frames: toSpriteFrames(frames, textureWidth, textureHeight),\n premultipliedAlpha,\n };\n}\n\n/**\n * Finds a frame by name.\n *\n * @param atlas - The atlas to search.\n * @param name - The frame name.\n * @returns The frame index, or `-1`.\n *\n * @internal\n */\nexport function frameIndexOf(atlas: SpriteAtlas, name: string): number {\n const frames = atlas.frames;\n for (let index = 0; index < frames.length; index += 1) {\n if (frames[index]?.name === name) {\n return index;\n }\n }\n return -1;\n}\n","import { loadTexture2D, releaseTexture } from \"@babylonjs/lite\";\nimport type { EngineContext, SpriteSampling, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * The device-only half of the atlas adapter: uploading an atlas image and releasing it again.\n * Every line here needs `engine._device`, so the module lives under `gpu/` and the root Vitest\n * coverage config excludes it; the `browser` project covers it instead\n * (`vitest.config.ts`, and the same rule core's `src/lite/gpu/**` follows).\n *\n * Everything here is `@internal`.\n */\n\n/**\n * Uploads an atlas image with the sampler settings a sprite atlas needs.\n *\n * @remarks\n * Four of the five options are not defaults and each one matters, and Lite's own `loadSpriteAtlas`\n * chooses exactly the same set (`lib/sprite/shared/sprite-atlas.js`):\n *\n * - `invertY: false` — Lite's `Texture2DOptions.invertY` defaults to **`true`** (`index.d.ts`\n * 12923) to match Babylon's convention, but sprite UVs are top-down with the origin at the image\n * top-left, so flipping would put every frame upside down.\n * - `mipMaps: false` — a sprite is drawn at roughly one texel per pixel; a mip chain only costs\n * memory and blurs a pixel-perfect camera.\n * - `addressModeU`/`addressModeV: \"clamp-to-edge\"` — the default `\"repeat\"` lets a frame at the\n * image edge sample its opposite edge.\n * - `minFilter`/`magFilter` — `\"nearest\"` is what pixel art needs; anything else blends adjacent\n * texels and defeats `Camera2D.pixelPerfect`.\n *\n * @param engine - The engine that owns the GPU texture.\n * @param url - Where to fetch the image from.\n * @param sampling - The min/mag filter.\n * @param premultiplyOnLoad - Whether to premultiply alpha at decode time.\n * @returns The uploaded texture; its reference count starts at an implicit one.\n *\n * @internal\n */\nexport function loadAtlasTexture(\n engine: EngineContext,\n url: string,\n sampling: SpriteSampling,\n premultiplyOnLoad: boolean,\n): Promise<Texture2D> {\n const filter = sampling === \"nearest\" ? \"nearest\" : \"linear\";\n return loadTexture2D(engine, url, {\n invertY: false,\n mipMaps: false,\n addressModeU: \"clamp-to-edge\",\n addressModeV: \"clamp-to-edge\",\n minFilter: filter,\n magFilter: filter,\n premultiplyAlpha: premultiplyOnLoad,\n });\n}\n\n/**\n * Releases an atlas texture through Lite's reference-counted resource pool.\n *\n * @remarks\n * This is deliberately **not** `disposeSpriteAtlas`. That function calls\n * `atlas.texture.texture.destroy()` unconditionally (`lib/sprite/shared/sprite-atlas.js` line 73)\n * and its own doc says idempotence is not guaranteed and that an atlas built over an\n * externally-owned texture should be freed by whoever owns the texture. ignifx's asset layer owns\n * it, so it releases the texture through the pool instead — the same call\n * `@ignifx/core`'s `TextureAsset` makes.\n *\n * @param texture - The texture to release.\n * @returns `true` when the reference count reached zero and the GPU texture was destroyed.\n *\n * @internal\n */\nexport function releaseAtlasTexture(texture: Texture2D): boolean {\n return releaseTexture(texture);\n}\n","import { isAbsoluteReference, resolveRelative } from \"../assets/relative.js\";\nimport { TwoDErrorCode } from \"../errors.js\";\nimport { buildAtlas } from \"../lite/atlas.js\";\nimport { loadAtlasTexture, releaseAtlasTexture } from \"../lite/gpu/texture.js\";\nimport {\n defineSpriteAtlas,\n parseSpriteFragment,\n readVec2,\n SPRITE_ATLAS_ASSET_TYPE,\n SPRITE_ATLAS_FILE_EXTENSIONS,\n} from \"./definition.js\";\nimport { SpriteAtlasAsset } from \"./sprite-atlas-asset.js\";\nimport type { SpriteAtlasDefinition, SpriteAtlasInput } from \"./definition.js\";\nimport type { SpriteAsset } from \"./sprite-atlas-asset.js\";\nimport type { FrameRect } from \"../lite/atlas.js\";\nimport type { AssetLoader, LoaderContext, Logger, Vec2Like } from \"@ignifx/core\";\n\n/**\n * The `spriteatlas` asset loader (`docs/architecture/05-assets-and-loading.md` §5,\n * `11-2d-toolkit.md` §2.3).\n *\n * The loader fetches the `.atlas.json` document, uploads the image it names, and builds Lite's\n * `SpriteAtlas` from the pixel rectangles. Under a headless app it stops after parsing: the frames\n * are all queryable, nothing is uploaded, and `asset.lite.atlas` is `null`\n * (`docs/architecture/07-rendering.md` §6).\n *\n * `parseFragment` is what makes `\"2d/hero.atlas.json#frame:idle_0\"` work: the base document is\n * loaded once and shared, and the fragment handle resolves to a {@link SpriteAsset} naming one\n * frame of it.\n */\n\n/**\n * The centre pivot a frame that declares none uses.\n */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * Converts the document's frame rectangles into the adapter's shape.\n *\n * @param definition - The parsed document.\n * @returns The rectangles, in index order.\n */\nfunction toRects(definition: SpriteAtlasDefinition): readonly FrameRect[] {\n const rects: FrameRect[] = [];\n for (let index = 0; index < definition.frames.length; index += 1) {\n const frame = definition.frames[index];\n if (frame === undefined) {\n continue;\n }\n rects.push({\n name: frame.name,\n x: frame.x,\n y: frame.y,\n w: frame.w,\n h: frame.h,\n pivotX: readVec2(frame.pivot, CENTRE_PIVOT).x,\n pivotY: readVec2(frame.pivot, CENTRE_PIVOT).y,\n sourceW: readVec2(frame.sourceSize, { x: frame.w, y: frame.h }).x,\n sourceH: readVec2(frame.sourceSize, { x: frame.w, y: frame.h }).y,\n });\n }\n return rects;\n}\n\n/**\n * Warns about frames that a pixel-perfect camera will bleed.\n *\n * @remarks\n * `docs/architecture/11-2d-toolkit.md` §4 asks importers to warn when a frame lacks a one-pixel\n * extruded border. The loader cannot see the image's pixels — it only has rectangles — so it checks\n * the thing it *can* see and that causes the bleed: a frame whose rectangle touches another frame's\n * rectangle, or the image edge, with no gap. Two frames packed flush against each other are exactly\n * the case where a `nearest` sample at a frame boundary can pick up the neighbour.\n *\n * This is a log, not a throw (`IGX-1102`): a game that never turns on `pixelPerfect` is unaffected,\n * and the remedy — repacking with padding — belongs to the art pipeline.\n *\n * @param definition - The parsed document.\n * @param address - The atlas address, for the message.\n * @param log - Where to report.\n *\n * @internal\n */\nexport function warnUnextrudedFrames(definition: SpriteAtlasDefinition, address: string, log: Logger): void {\n const frames = definition.frames;\n for (let index = 0; index < frames.length; index += 1) {\n const frame = frames[index];\n if (frame === undefined) {\n continue;\n }\n let touches = false;\n for (let other = 0; other < frames.length && !touches; other += 1) {\n const neighbour = frames[other];\n if (neighbour === undefined || other === index) {\n continue;\n }\n const gapX = Math.max(frame.x - (neighbour.x + neighbour.w), neighbour.x - (frame.x + frame.w));\n const gapY = Math.max(frame.y - (neighbour.y + neighbour.h), neighbour.y - (frame.y + frame.h));\n touches = gapX === 0 || gapY === 0;\n }\n if (touches) {\n log.warnOnce(\n `${address}#${frame.name}`,\n `${TwoDErrorCode.atlasFrameNotExtruded}: atlas frame ${frame.name} has no 1-px extruded border.`,\n {\n atlas: address,\n frame: frame.name,\n hint: \"Repack with at least 1 px of padding, or a pixel-perfect camera can sample the neighbouring frame.\",\n },\n );\n }\n }\n}\n\n/** The one thing the image resolution needs from `app.assets`. */\nexport interface AtlasImageUrlResolver {\n /** Resolves an address to the URL the asset service would fetch. */\n resolveUrl(address: string): string;\n}\n\n/**\n * Resolves an atlas document's `image` reference to the URL to fetch.\n *\n * @remarks\n * A relative reference is an **address** relative to the atlas document's own address and goes\n * through the asset manifest (`assets.resolveUrl`), so a production build that content-hashes the\n * asset root still finds the image. A root-relative (`/sheet.png`) or absolute (`https://…`,\n * `blob:`, `data:`) reference is a URL and is fetched verbatim — the shape a file in Vite's `public/`\n * directory has. Resolving against the document's *URL* instead broke hashed builds (Phase 6).\n *\n * @param assets - The app's asset service, or anything with its `resolveUrl`.\n * @param atlasAddress - The address of the atlas document.\n * @param image - The `image` reference as written in the document.\n * @returns The URL to load the sheet from.\n *\n * @internal\n */\nexport function resolveAtlasImageUrl(assets: AtlasImageUrlResolver, atlasAddress: string, image: string): string {\n const reference = resolveRelative(atlasAddress, image);\n return isAbsoluteReference(reference) ? reference : assets.resolveUrl(reference);\n}\n\n/**\n * Builds the loader for `.atlas.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createSpriteAtlasLoader());\n * ```\n *\n * @public\n */\nexport function createSpriteAtlasLoader(): AssetLoader<SpriteAtlasAsset> {\n return {\n type: SPRITE_ATLAS_ASSET_TYPE,\n extensions: SPRITE_ATLAS_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<SpriteAtlasAsset> {\n const raw = await ctx.fetchJson<SpriteAtlasInput>();\n const definition = defineSpriteAtlas(raw, ctx.address);\n warnUnextrudedFrames(definition, ctx.address, ctx.app.log);\n if (ctx.app.isHeadless) {\n // §6: a loader must tolerate the null engine and return CPU-only data.\n return new SpriteAtlasAsset(ctx.address, definition, null, null);\n }\n ctx.reportProgress(0);\n const url = resolveAtlasImageUrl(ctx.app.assets, ctx.address, definition.image);\n const texture = await loadAtlasTexture(ctx.lite.engine, url, definition.sampling, definition.premultipliedAlpha);\n ctx.reportProgress(1);\n const atlas = buildAtlas(\n texture,\n texture.width,\n texture.height,\n toRects(definition),\n definition.premultipliedAlpha,\n );\n return new SpriteAtlasAsset(ctx.address, definition, atlas, (): void => {\n releaseAtlasTexture(texture);\n });\n },\n unload(value: SpriteAtlasAsset): void {\n value.releaseGpu();\n },\n parseFragment(fragment: string, value: SpriteAtlasAsset): unknown {\n const name = parseSpriteFragment(fragment);\n if (name === null) {\n const first = value.frame(0);\n return first === null ? null : ({ atlas: value, frame: 0, name: first.name } satisfies SpriteAsset);\n }\n const index = value.requireFrame(name);\n return { atlas: value, frame: index, name } satisfies SpriteAsset;\n },\n };\n}\n","import { DEG_TO_RAD, RAD_TO_DEG } from \"@ignifx/core\";\nimport type { MutableVec2, Vec2Like } from \"@ignifx/core\";\n\n/**\n * The one place the ignifx 2D world (metres, **+Y up**, ADR-0011) is converted into Babylon Lite's\n * sprite space (pixels, **+Y down**) and back. Every other module in this package goes through\n * these functions, so the flip lives in exactly one file\n * (`docs/architecture/11-2d-toolkit.md` §1 and §3).\n *\n * Nothing here allocates: every conversion writes into a caller-owned vector (coding standards §7).\n */\n\n/**\n * The default pixels-per-unit, matching `twoD.pixelsPerUnit`\n * (`docs/architecture/11-2d-toolkit.md` §1). At 100, a 32-pixel sprite is 0.32 metres wide.\n *\n * @public\n */\nexport const DEFAULT_PIXELS_PER_UNIT = 100;\n\n/**\n * Converts a world point in metres to a Lite layer-pixel point.\n *\n * @param x - The world x, in metres.\n * @param y - The world y, in metres, with +Y up.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @param out - The vector to write.\n * @returns `out`, in pixels with +Y down.\n *\n * @example\n * ```ts\n * worldToPixelsToRef(1.5, 0.5, 100, out); // out is (150, -50)\n * ```\n *\n * @public\n */\nexport function worldToPixelsToRef<TOut extends MutableVec2>(\n x: number,\n y: number,\n pixelsPerUnit: number,\n out: TOut,\n): TOut {\n out.x = x * pixelsPerUnit;\n out.y = -y * pixelsPerUnit;\n return out;\n}\n\n/**\n * Converts a Lite layer-pixel point back to world metres.\n *\n * @param xPx - The layer x, in pixels.\n * @param yPx - The layer y, in pixels, with +Y down.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @param out - The vector to write.\n * @returns `out`, in metres with +Y up.\n *\n * @public\n */\nexport function pixelsToWorldToRef<TOut extends MutableVec2>(\n xPx: number,\n yPx: number,\n pixelsPerUnit: number,\n out: TOut,\n): TOut {\n out.x = xPx / pixelsPerUnit;\n out.y = -yPx / pixelsPerUnit;\n return out;\n}\n\n/**\n * Converts an ignifx rotation about +Z into the rotation Lite gives a **sprite**.\n *\n * @remarks\n * `Transform.rotation2D` is degrees counter-clockwise in a +Y-up world. A sprite's quad is built in\n * Lite's +Y-down pixel space (`(corner - pivot) * sizePx`, then rotated), so the same visual turn is\n * the negated angle there. Verified against the sprite vertex shader in\n * `@babylonjs/lite@1.27.0`, `lib/sprite/sprite-pipeline.js` line 25.\n *\n * @param degrees - The ignifx rotation, in degrees counter-clockwise.\n * @returns The rotation to write to `Sprite2DProps.rotation`, in radians.\n *\n * @public\n */\nexport function spriteRotationToLite(degrees: number): number {\n return -degrees * DEG_TO_RAD;\n}\n\n/**\n * Converts a Lite sprite rotation back to ignifx degrees.\n *\n * @param radians - The `Sprite2DProps.rotation` value.\n * @returns The ignifx rotation, in degrees counter-clockwise.\n *\n * @public\n */\nexport function spriteRotationFromLite(radians: number): number {\n return -radians * RAD_TO_DEG;\n}\n\n/**\n * Converts a `Camera2D` rotation into the rotation Lite gives a **view**.\n *\n * @remarks\n * A view rotation is applied to an already-flipped world offset rather than to a sprite-local\n * offset, and the two flips cancel — so unlike {@link spriteRotationToLite} the sign is kept.\n * Verified against `sprite2DWorldToScreenToRef` in `@babylonjs/lite@1.27.0`,\n * `lib/sprite/sprite-2d-view.js`.\n *\n * @param degrees - The camera rotation, in degrees counter-clockwise.\n * @returns The rotation to write to `Sprite2DView.rotation`, in radians.\n *\n * @public\n */\nexport function viewRotationToLite(degrees: number): number {\n return degrees * DEG_TO_RAD;\n}\n\n/**\n * The zoom a `Camera2D` needs so that `orthographicSize` metres fill half the viewport's height\n * (`docs/architecture/11-2d-toolkit.md` §2.1).\n *\n * @param viewportHeightPx - The viewport height, in pixels.\n * @param orthographicSize - The camera's half-height, in metres.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @returns The `Sprite2DView.zoom` value; never zero, because Lite rejects a zero zoom.\n *\n * @public\n */\nexport function zoomForSize(viewportHeightPx: number, orthographicSize: number, pixelsPerUnit: number): number {\n const divisor = 2 * orthographicSize * pixelsPerUnit;\n if (divisor <= 0) {\n return 1;\n }\n const zoom = viewportHeightPx / divisor;\n return zoom > 0 ? zoom : 1;\n}\n\n/**\n * The inverse of {@link zoomForSize}: what half-height a zoom shows.\n *\n * @param viewportHeightPx - The viewport height, in pixels.\n * @param zoom - The `Sprite2DView.zoom` value.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @returns The half-height, in metres.\n *\n * @public\n */\nexport function sizeForZoom(viewportHeightPx: number, zoom: number, pixelsPerUnit: number): number {\n if (zoom <= 0 || pixelsPerUnit <= 0) {\n return 0;\n }\n return viewportHeightPx / (2 * zoom * pixelsPerUnit);\n}\n\n/**\n * Snaps a zoom to the nearest usable integer for a pixel-perfect camera\n * (`docs/architecture/11-2d-toolkit.md` §4).\n *\n * @remarks\n * Zooms below 1 snap to the reciprocal of an integer (`1/2`, `1/3`, …) rather than to zero, so a\n * camera that is pulled far out still lands on a whole-texel scale.\n *\n * @param zoom - The continuous zoom {@link zoomForSize} produced.\n * @returns The snapped zoom, always greater than zero.\n *\n * @public\n */\nexport function snapZoomToInteger(zoom: number): number {\n if (zoom >= 1) {\n return Math.max(1, Math.floor(zoom));\n }\n if (zoom <= 0) {\n return 1;\n }\n return 1 / Math.max(1, Math.round(1 / zoom));\n}\n\n/**\n * Snaps a layer-pixel coordinate to the whole-pixel grid a pixel-perfect camera draws on.\n *\n * @param valuePx - The coordinate, in layer pixels.\n * @param zoom - The camera's zoom; at zoom 2 the grid step is half a layer pixel.\n * @returns The snapped coordinate.\n *\n * @public\n */\nexport function snapPixel(valuePx: number, zoom: number): number {\n if (zoom <= 0) {\n return valuePx;\n }\n return Math.round(valuePx * zoom) / zoom;\n}\n\n/**\n * Places the pivot of a sprite at a world point by offsetting the position Lite draws it at.\n *\n * @remarks\n * Lite's sprite pipeline has **one pivot per layer**, not per sprite or per frame: the vertex\n * shader reads `L.pivot` out of the layer uniform (`lib/sprite/sprite-pipeline.js` lines 25 and\n * 264–265), and the per-frame `SpriteFrame.pivot` is consumed only by the *billboard* family\n * (`lib/sprite/billboard-sprite.js` lines 166–167). ignifx therefore keeps every layer on the\n * centre pivot `[0.5, 0.5]` and moves the sprite instead, which is what makes a per-frame pivot and\n * `SpriteRenderer.pivotOverride` work at all.\n *\n * @param anchorXPx - The world anchor, in layer pixels.\n * @param anchorYPx - The world anchor, in layer pixels.\n * @param pivot - The pivot in `[0, 1]` of the frame; `[0, 0]` is top-left, `[1, 1]` bottom-right.\n * @param widthPx - The drawn width, in pixels.\n * @param heightPx - The drawn height, in pixels.\n * @param rotationRadians - The sprite's Lite rotation, which the offset turns with.\n * @param out - The vector to write.\n * @returns `out`: the value to write to `Sprite2DProps.positionPx`.\n *\n * @public\n */\nexport function pivotedPositionToRef<TOut extends MutableVec2>(\n anchorXPx: number,\n anchorYPx: number,\n pivot: Vec2Like,\n widthPx: number,\n heightPx: number,\n rotationRadians: number,\n out: TOut,\n): TOut {\n const offsetX = (0.5 - pivot.x) * widthPx;\n const offsetY = (0.5 - pivot.y) * heightPx;\n if (rotationRadians === 0) {\n out.x = anchorXPx + offsetX;\n out.y = anchorYPx + offsetY;\n return out;\n }\n const cos = Math.cos(rotationRadians);\n const sin = Math.sin(rotationRadians);\n out.x = anchorXPx + offsetX * cos - offsetY * sin;\n out.y = anchorYPx + offsetX * sin + offsetY * cos;\n return out;\n}\n","import { bool, Component, createDefaults, defineSchema, entityRef, f32, i32, optional, vec2, Vec2 } from \"@ignifx/core\";\nimport {\n pixelsToWorldToRef,\n snapPixel,\n snapZoomToInteger,\n viewRotationToLite,\n worldToPixelsToRef,\n zoomForSize,\n} from \"../math/coords.js\";\nimport type { Entity, MutableVec2, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `Camera2D` (`docs/architecture/11-2d-toolkit.md` §2.1): the component that drives every world\n * sprite layer's `Sprite2DView`.\n *\n * The camera holds no Lite object of its own. A `Sprite2DView` belongs to a layer, and every world\n * layer gets the *same* view written to it each frame, which is what makes the layers move\n * together; screen-space layers keep the identity view. The 2D sync system does the writing —\n * this class owns the arithmetic and the public conversions.\n */\n\n/**\n * The half-height, in metres, a camera that declares none shows.\n *\n * @public\n */\nexport const DEFAULT_ORTHOGRAPHIC_SIZE = 5;\n\n/**\n * The reference resolution a pixel-perfect camera fits an integer zoom to.\n *\n * @public\n */\nexport const DEFAULT_REFERENCE_RESOLUTION: Vec2Like = Object.freeze({ x: 640, y: 360 });\n\n/**\n * The 2D camera.\n *\n * @remarks\n * `orthographicSize` is a **half-height in metres**, exactly as Unity's orthographic camera is, so\n * the zoom it produces is `viewportHeightPx / (2 · size · PPU)`. With `pixelPerfect` on, that zoom\n * is snapped to a whole number (or to `1/n` when the camera is pulled far out) and the camera's\n * position is snapped to the pixel grid at sync time — scripts keep their sub-pixel positions, so\n * movement stays smooth even though drawing does not.\n *\n * @example\n * ```ts\n * const camera = app.world.createEntity({ name: \"camera\" }).addComponent(Camera2D);\n * camera.orthographicSize = 3;\n * camera.pixelPerfect = true;\n * ```\n *\n * @public\n */\nexport class Camera2D extends Component {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/Camera2D\";\n\n /** One camera per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = camera2DSchema();\n\n /** Half the viewport height, in metres. */\n declare orthographicSize: number;\n\n /** Whether zoom snaps to an integer and positions snap to the pixel grid. */\n declare pixelPerfect: boolean;\n\n /** The design resolution a pixel-perfect camera fits an integer zoom to, in pixels. */\n declare referenceResolution: Vec2Like;\n\n /** The lower bound of the camera's travel, in metres, or `null` for no bound. */\n declare boundsMin: Vec2Like | null;\n\n /** The upper bound of the camera's travel, in metres, or `null` for no bound. */\n declare boundsMax: Vec2Like | null;\n\n /** The entity this camera follows, or `null`. Read by `Camera2DFollow`. */\n declare follow: Entity | null;\n\n /** How long the follow takes to catch up, in seconds. */\n declare followDamping: number;\n\n /** A constant offset added to the followed entity's position, in metres. */\n declare followOffset: Vec2Like;\n\n /** The half-size of the rectangle the target may move inside before the camera reacts, in metres. */\n declare deadZone: Vec2Like;\n\n /** Highest wins when a world has several enabled cameras. */\n declare priority: number;\n\n /** The viewport width the last sync measured, in pixels. */\n #viewportWidthPx = 0;\n\n /** The viewport height the last sync measured, in pixels. */\n #viewportHeightPx = 0;\n\n /** The pixels-per-unit the last sync used. */\n #pixelsPerUnit = 100;\n\n /** The zoom the last sync computed, after any pixel-perfect snapping. */\n #zoom = 1;\n\n /** The world centre the last sync used, after bounds clamping and pixel snapping. */\n readonly #centre: MutableVec2 = new Vec2();\n\n /** Scratch, so the conversions allocate nothing (coding standards §7). */\n readonly #scratchA: MutableVec2 = new Vec2();\n\n /** Scratch; see {@link Camera2D.screenToWorld}. */\n readonly #scratchB: MutableVec2 = new Vec2();\n\n /**\n * Builds a camera with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(Camera2D.schema));\n }\n\n /**\n * The zoom the camera last resolved to — `Sprite2DView.zoom`.\n *\n * @returns The zoom; `1` before the first sync.\n */\n get zoom(): number {\n return this.#zoom;\n }\n\n /**\n * The viewport the camera last measured, in pixels.\n *\n * @returns A read-only view of the size.\n */\n get viewportSizePx(): Vec2Like {\n return { x: this.#viewportWidthPx, y: this.#viewportHeightPx };\n }\n\n /**\n * The world point the camera is centred on, after bounds clamping and pixel-perfect snapping.\n *\n * @returns A read-only view of the centre, in metres.\n */\n get centre(): Vec2Like {\n return this.#centre;\n }\n\n /**\n * Recomputes the camera's zoom and centre. The 2D sync system calls this once per frame, before\n * it writes the view onto each world layer.\n *\n * @param worldX - The entity's world x, in metres.\n * @param worldY - The entity's world y, in metres.\n * @param viewportWidthPx - The surface width, in pixels.\n * @param viewportHeightPx - The surface height, in pixels.\n * @param pixelsPerUnit - The pixels one metre spans.\n *\n * @internal\n */\n // oxlint-disable-next-line max-params -- once per camera per frame; an options object would allocate.\n resolve(\n worldX: number,\n worldY: number,\n viewportWidthPx: number,\n viewportHeightPx: number,\n pixelsPerUnit: number,\n ): void {\n this.#viewportWidthPx = viewportWidthPx;\n this.#viewportHeightPx = viewportHeightPx;\n this.#pixelsPerUnit = pixelsPerUnit;\n const raw = zoomForSize(viewportHeightPx, this.orthographicSize, pixelsPerUnit);\n // Pixel-perfect ignores `orthographicSize` and scales the reference resolution by a whole\n // number instead, which is what makes one source texel cover an exact square of screen pixels\n // (`docs/architecture/11-2d-toolkit.md` §4). Unity's Pixel Perfect Camera does the same.\n const referenceHeight = this.referenceResolution.y;\n const scaled = this.pixelPerfect\n ? snapZoomToInteger(referenceHeight > 0 ? viewportHeightPx / referenceHeight : raw)\n : raw;\n this.#zoom = scaled > 0 ? scaled : 1;\n let centreX = worldX;\n let centreY = worldY;\n const min = this.boundsMin;\n const max = this.boundsMax;\n if (min !== null && max !== null) {\n const halfHeight = viewportHeightPx / (2 * this.#zoom * pixelsPerUnit);\n const halfWidth = viewportWidthPx / (2 * this.#zoom * pixelsPerUnit);\n centreX = clampSpan(centreX, min.x, max.x, halfWidth);\n centreY = clampSpan(centreY, min.y, max.y, halfHeight);\n }\n if (this.pixelPerfect) {\n centreX = snapPixel(centreX * pixelsPerUnit, this.#zoom) / pixelsPerUnit;\n centreY = snapPixel(centreY * pixelsPerUnit, this.#zoom) / pixelsPerUnit;\n }\n this.#centre.x = centreX;\n this.#centre.y = centreY;\n }\n\n /**\n * Converts a viewport pixel into a world point.\n *\n * @remarks\n * `x` and `y` are measured from the surface's top-left corner, which is what a `PointerEvent`\n * reports and what `@ignifx/input`'s pointer position carries. The result is in metres with +Y\n * up. Before the first frame has synced, the camera has no viewport and the result is the\n * camera's own centre.\n *\n * @param x - The viewport x, in pixels from the left edge.\n * @param y - The viewport y, in pixels from the top edge.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, in world metres.\n *\n * @example\n * ```ts\n * const world = camera.screenToWorld(pointer.x, pointer.y);\n * ```\n */\n screenToWorld(x: number, y: number, out: MutableVec2 = new Vec2()): MutableVec2 {\n const zoom = this.#zoom;\n if (this.#viewportWidthPx === 0 || zoom === 0) {\n out.x = this.#centre.x;\n out.y = this.#centre.y;\n return out;\n }\n // The view's top-left in layer pixels, then the offset the pixel sits at, unrotated.\n const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, this.#scratchA);\n const offsetX = (x - this.#viewportWidthPx * 0.5) / zoom;\n const offsetY = (y - this.#viewportHeightPx * 0.5) / zoom;\n const rotation = viewRotationToLite(this.#rotationDegrees());\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const layerX = centrePx.x + offsetX * cos + offsetY * sin;\n const layerY = centrePx.y - offsetX * sin + offsetY * cos;\n return pixelsToWorldToRef(layerX, layerY, this.#pixelsPerUnit, out);\n }\n\n /**\n * Converts a world point into a viewport pixel.\n *\n * @param point - The world point, in metres.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, in pixels from the surface's top-left corner.\n */\n worldToScreen(point: Vec2Like, out: MutableVec2 = new Vec2()): MutableVec2 {\n const zoom = this.#zoom;\n const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, this.#scratchA);\n const pointPx = worldToPixelsToRef(point.x, point.y, this.#pixelsPerUnit, this.#scratchB);\n const deltaX = pointPx.x - centrePx.x;\n const deltaY = pointPx.y - centrePx.y;\n const rotation = viewRotationToLite(this.#rotationDegrees());\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n out.x = (deltaX * cos - deltaY * sin) * zoom + this.#viewportWidthPx * 0.5;\n out.y = (deltaX * sin + deltaY * cos) * zoom + this.#viewportHeightPx * 0.5;\n return out;\n }\n\n /**\n * The camera entity's rotation about +Z, in degrees counter-clockwise.\n *\n * @returns The angle; `0` when the component is not attached yet.\n */\n #rotationDegrees(): number {\n return this.entity.transform.rotation2D;\n }\n}\n\n/**\n * Clamps a camera centre so the viewport stays inside a bound.\n *\n * @remarks\n * When the bound is narrower than the viewport there is no position that keeps the viewport\n * inside it, so the camera centres on the bound instead of jittering against one edge — the\n * behaviour Godot's `limit_*` has.\n *\n * @param value - The desired centre.\n * @param min - The lower bound.\n * @param max - The upper bound.\n * @param half - Half the viewport's extent on this axis, in metres.\n * @returns The clamped centre.\n */\nfunction clampSpan(value: number, min: number, max: number, half: number): number {\n if (max - min <= half * 2) {\n return (min + max) * 0.5;\n }\n return Math.min(Math.max(value, min + half), max - half);\n}\n\n/**\n * The `Camera2D` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction camera2DSchema(): Schema {\n return defineSchema({\n orthographicSize: f32(DEFAULT_ORTHOGRAPHIC_SIZE, {\n min: Number.EPSILON,\n tooltip: \"Half the viewport height, in metres.\",\n }),\n pixelPerfect: bool(false, { tooltip: \"Snap zoom to an integer and positions to whole pixels.\" }),\n referenceResolution: vec2(DEFAULT_REFERENCE_RESOLUTION, {\n tooltip: \"The design resolution a pixel-perfect camera fits an integer zoom to.\",\n }),\n boundsMin: optional(vec2(), { tooltip: \"The lower bound of the camera's travel, in metres.\" }),\n boundsMax: optional(vec2(), { tooltip: \"The upper bound of the camera's travel, in metres.\" }),\n follow: entityRef<Entity>({ tooltip: \"The entity Camera2DFollow tracks.\" }),\n followDamping: f32(0.15, { min: 0, tooltip: \"Seconds the follow takes to catch up; 0 is rigid.\" }),\n followOffset: vec2({ x: 0, y: 0 }, { tooltip: \"A constant offset added to the followed position.\" }),\n deadZone: vec2({ x: 0, y: 0 }, { tooltip: \"Half-size of the rectangle the target moves in freely.\" }),\n priority: i32(0, { tooltip: \"Highest enabled camera wins.\" }),\n });\n}\n","import { Script, Vec2 } from \"@ignifx/core\";\nimport { Camera2D } from \"./camera-2d.js\";\nimport type { MutableVec2 } from \"@ignifx/core\";\n\n/**\n * `Camera2DFollow` (`docs/architecture/11-2d-toolkit.md` §2.1): the reference implementation of a\n * smooth, dead-zoned camera follow.\n *\n * It is a `Script`, not part of `Camera2D`, on purpose: following is a *policy*, and a game that\n * wants look-ahead, screen shake, or room-based snapping replaces this script without touching the\n * camera. `Camera2D` holds the fields (`follow`, `followDamping`, `followOffset`, `deadZone`)\n * because a scene file has to be able to author them; this script is what reads them.\n *\n * The move happens in `lateUpdate`, after every `update` has run, so the camera sees the frame's\n * final player position rather than last frame's — the single most common cause of a camera that\n * visibly lags its target by one frame.\n */\n\n/**\n * A damped, dead-zoned camera follow.\n *\n * @example\n * ```ts\n * const camera = app.world.createEntity({ name: \"camera\" });\n * const view = camera.addComponent(Camera2D);\n * view.follow = player;\n * view.deadZone = { x: 0.5, y: 0.3 };\n * camera.addComponent(Camera2DFollow);\n * ```\n *\n * @public\n */\nexport class Camera2DFollow extends Script {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/Camera2DFollow\";\n\n /** One follow per entity. */\n static allowMultiple = false;\n\n /** The camera this script drives, found once on attach. */\n #camera: Camera2D | null = null;\n\n /** Scratch, so following allocates nothing per frame. */\n readonly #target: MutableVec2 = new Vec2();\n\n /**\n * Finds the camera on this entity.\n */\n awake(): void {\n this.#camera = this.entity.getComponent(Camera2D);\n }\n\n /**\n * Moves the camera toward its target.\n *\n * @remarks\n * The damping is frame-rate independent: the camera covers the same fraction of the remaining\n * distance per *second*, not per frame, so a 30 fps machine and a 144 fps machine see the same\n * motion. `followDamping` is the time constant in seconds; `0` snaps.\n *\n * @param deltaTime - The scaled frame delta.\n */\n lateUpdate(deltaTime: number): void {\n const camera = this.#camera;\n const target = camera?.follow ?? null;\n if (camera === null || target === null || target.isDestroyed) {\n return;\n }\n const targetMatrix = target.transform.worldMatrix;\n const offset = camera.followOffset;\n const desiredX = (targetMatrix[12] ?? 0) + offset.x;\n const desiredY = (targetMatrix[13] ?? 0) + offset.y;\n const transform = this.entity.transform;\n const matrix = transform.worldMatrix;\n const currentX = matrix[12] ?? 0;\n const currentY = matrix[13] ?? 0;\n const zone = camera.deadZone;\n // Inside the dead zone the camera does not move at all; outside it, it chases only the part of\n // the distance that is beyond the zone, so the target rides the zone's edge.\n const wantedX = beyond(desiredX, currentX, zone.x);\n const wantedY = beyond(desiredY, currentY, zone.y);\n const damping = camera.followDamping;\n const blend = damping <= 0 ? 1 : 1 - Math.exp(-deltaTime / damping);\n this.#target.x = currentX + (wantedX - currentX) * blend;\n this.#target.y = currentY + (wantedY - currentY) * blend;\n transform.position2D = new Vec2(this.#target.x, this.#target.y);\n }\n}\n\n/**\n * The position the camera should chase, given a dead zone.\n *\n * @param desired - Where the target is.\n * @param current - Where the camera is.\n * @param half - Half the dead zone's extent on this axis, in metres.\n * @returns The camera's goal: `current` while the target is inside the zone.\n */\nfunction beyond(desired: number, current: number, half: number): number {\n const delta = desired - current;\n if (Math.abs(delta) <= half) {\n return current;\n }\n return delta > 0 ? desired - half : desired + half;\n}\n","import {\n addSpriteRendererLayer,\n createSpriteRenderer,\n disposeSpriteRenderer,\n enableDeviceLostSpriteRecovery,\n registerSpriteRenderer,\n removeSpriteRendererLayer,\n unregisterSpriteRenderer,\n} from \"@babylonjs/lite\";\nimport type {\n DeviceLostRecoveryHandle,\n EngineContext,\n Sprite2DLayer,\n SpriteRenderer,\n SurfaceContext,\n} from \"@babylonjs/lite\";\n\n/**\n * The device-only half of the sprite adapter: the second rendering context `@ignifx/2d` puts on the\n * app's surface (`docs/architecture/07-rendering.md` §1, `11-2d-toolkit.md` §1).\n *\n * A `SpriteRenderer` opens its own single-sample swapchain pass and is registered directly on the\n * engine, independent of any scene. Lite's own contract (`index.d.ts` 12193-12216) is explicit\n * about ordering: *\"Register the renderer **after** `registerScene` so it draws on top\"* — and\n * about compositing: `SpriteRendererOptions.clear` *\"Default true. Set false for HUD overlays so\n * the sprite pass preserves existing scene color\"* (12222).\n *\n * Everything here needs `engine._device`, so the module lives under `gpu/` and the root Vitest\n * coverage config excludes it; the `browser` project covers it.\n *\n * Everything here is `@internal`.\n */\n\n/**\n * The surface a sprite renderer draws into.\n *\n * @remarks\n * `EngineContext extends SurfaceContext` (`index.d.ts` 4676) and an engine's index-0 surface *is*\n * the engine itself, so a single-canvas app passes `app.lite.engine` straight through. This alias\n * exists so callers outside `src/lite/**` never have to name a Lite type.\n *\n * @internal\n */\nexport type SpriteSurface = SurfaceContext;\n\n/**\n * A straight RGBA clear value, each channel in `0` to `1`.\n *\n * @internal\n */\nexport interface ClearColor {\n /** The red channel. */\n readonly r: number;\n /** The green channel. */\n readonly g: number;\n /** The blue channel. */\n readonly b: number;\n /** The alpha channel. */\n readonly a: number;\n}\n\n/**\n * Creates the sprite renderer and pushes it onto the engine's rendering-context list.\n *\n * @remarks\n * Call this **after** the render scene is registered. `registerSpriteRenderer` appends to\n * `engine._renderingContexts` and Lite draws that list in order, so a context pushed later\n * composites later. It is idempotent (`index.d.ts` 9544).\n *\n * @param surface - The surface to draw into; the engine, for a single-canvas app.\n * @param clear - Whether the sprite pass clears first. `false` in `\"mixed\"` mode, so the 3D scene's\n * colour survives underneath.\n * @param clearColor - The clear value used when `clear` is `true`, as straight RGBA in `0` to `1`.\n * @param clearColor.r - The red channel.\n * @param clearColor.g - The green channel.\n * @param clearColor.b - The blue channel.\n * @param clearColor.a - The alpha channel.\n * @returns The registered renderer.\n *\n * @internal\n */\nexport function createRegisteredSpriteRenderer(\n surface: SpriteSurface,\n clear: boolean,\n clearColor: ClearColor,\n): SpriteRenderer {\n const renderer = createSpriteRenderer(surface, {\n layers: [],\n clear,\n clearValue: { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a },\n });\n registerSpriteRenderer(renderer);\n return renderer;\n}\n\n/**\n * Adds a layer to a renderer's draw list (`index.d.ts` 190).\n *\n * @param renderer - The sprite renderer.\n * @param layer - The layer to draw.\n *\n * @internal\n */\nexport function attachLayer(renderer: SpriteRenderer, layer: Sprite2DLayer): void {\n addSpriteRendererLayer(renderer, layer);\n}\n\n/**\n * Removes a layer from a renderer's draw list (`index.d.ts` 9666).\n *\n * @param renderer - The sprite renderer.\n * @param layer - The layer to stop drawing.\n * @returns `true` when the layer was there.\n *\n * @internal\n */\nexport function detachLayer(renderer: SpriteRenderer, layer: Sprite2DLayer): boolean {\n return removeSpriteRendererLayer(renderer, layer);\n}\n\n/**\n * Unregisters and disposes a sprite renderer (`index.d.ts` 13215 and 4078).\n *\n * @param renderer - The renderer to tear down.\n *\n * @internal\n */\nexport function destroySpriteRenderer(renderer: SpriteRenderer): void {\n unregisterSpriteRenderer(renderer);\n disposeSpriteRenderer(renderer);\n}\n\n/**\n * Turns on best-effort WebGPU device-lost recovery for every registered sprite renderer\n * (`index.d.ts` 4378).\n *\n * @remarks\n * Lite's own documentation is emphatic that ordering matters: *\"Enable this before creating or\n * loading sprite textures so their recovery sources are retained\"* (`index.d.ts` 4372-4373). The\n * extension therefore calls this in `onStart`, before any atlas or layer exists.\n *\n * @param engine - The engine to protect.\n * @param onRecovered - Called after the replacement device and every rendering context are ready.\n * @param onFailed - Called when reacquisition or rebuilding fails.\n * @returns The handle whose `disable()` turns recovery off again.\n *\n * @internal\n */\nexport function enableSpriteDeviceLostRecovery(\n engine: EngineContext,\n onRecovered: () => void,\n onFailed: (error: unknown) => void,\n): DeviceLostRecoveryHandle {\n return enableDeviceLostSpriteRecovery(engine, { onRecovered, onRecoveryFailed: onFailed });\n}\n","import { bool, Component, createDefaults, defineSchema, f32, str, vec2, Vec2 } from \"@ignifx/core\";\nimport { worldToPixelsToRef } from \"../math/coords.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport type { Camera2D } from \"../camera/camera-2d.js\";\nimport type { SpriteLayerEntry } from \"../service/layer-registry.js\";\nimport type { MutableVec2, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `ParallaxLayer` (`docs/architecture/11-2d-toolkit.md` §2.6): makes one sorting layer scroll at a\n * fraction of the camera's speed, which is what gives a side-scroller depth.\n *\n * The component owns no sprites. It reaches into the views of every Lite layer belonging to its\n * sorting layer, after the 2D sync system has written the camera's view onto them, and slides each\n * one back by `cameraPositionPx × (1 − factor)`. A factor of `1` moves with the camera (no\n * parallax); `0` is pinned to the world origin, which is what a distant sky wants.\n */\n\n/**\n * A parallax layer.\n *\n * @example\n * ```ts\n * const sky = app.world.createEntity({ name: \"sky\" }).addComponent(ParallaxLayer);\n * sky.sortingLayer = \"Background\";\n * sky.factor = { x: 0.2, y: 0.5 };\n * ```\n *\n * @public\n */\nexport class ParallaxLayer extends Component {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/ParallaxLayer\";\n\n /** One parallax setting per entity; several entities may each drive a different sorting layer. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = parallaxLayerSchema();\n\n /** Which sorting layer this component slows down. */\n declare sortingLayer: string;\n\n /** How much of the camera's motion the layer follows, per axis; `1` is no parallax. */\n declare factor: Vec2Like;\n\n /** Whether the layer's sprites repeat horizontally across the camera's view. */\n declare repeatX: boolean;\n\n /** Whether the layer's sprites repeat vertically. */\n declare repeatY: boolean;\n\n /** The world width one repetition spans, in metres; `0` disables horizontal repetition. */\n declare repeatWidth: number;\n\n /** The world height one repetition spans, in metres. */\n declare repeatHeight: number;\n\n /** Scratch, so applying the offset allocates nothing. */\n readonly #scratch: MutableVec2 = new Vec2();\n\n /**\n * Builds a parallax layer with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(ParallaxLayer.schema));\n }\n\n /**\n * Slides every matching layer's view.\n *\n * @remarks\n * Runs after the camera has written its own view, so the arithmetic is a pure offset:\n * `view.positionPx -= cameraPx × (1 − factor)`. With `repeatX`/`repeatY` the offset is taken\n * modulo one repetition, which keeps a tiled backdrop from drifting away from the camera no\n * matter how far the player walks — and keeps the number in single-precision range.\n *\n * @param entries - Every layer, as the registry describes them.\n * @param camera - The active camera.\n * @param pixelsPerUnit - The pixels one metre spans.\n *\n * @internal\n */\n applyTo(entries: readonly SpriteLayerEntry[], camera: Camera2D, pixelsPerUnit: number): void {\n const cameraPx = worldToPixelsToRef(camera.centre.x, camera.centre.y, pixelsPerUnit, this.#scratch);\n let offsetX = cameraPx.x * (1 - this.factor.x);\n let offsetY = cameraPx.y * (1 - this.factor.y);\n if (this.repeatX && this.repeatWidth > 0) {\n offsetX = wrap(offsetX, this.repeatWidth * pixelsPerUnit);\n }\n if (this.repeatY && this.repeatHeight > 0) {\n offsetY = wrap(offsetY, this.repeatHeight * pixelsPerUnit);\n }\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry === undefined || entry.screenSpace || entry.sortingLayer !== this.sortingLayer) {\n continue;\n }\n const view = entry.layer.view;\n view.positionPx[0] -= offsetX;\n view.positionPx[1] -= offsetY;\n }\n }\n}\n\n/**\n * Wraps a value into `[0, span)`, keeping the sign of the mathematical modulus.\n *\n * @param value - The value.\n * @param span - The period; must be greater than zero.\n * @returns The wrapped value.\n */\nfunction wrap(value: number, span: number): number {\n const remainder = value % span;\n return remainder < 0 ? remainder + span : remainder;\n}\n\n/**\n * The `ParallaxLayer` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction parallaxLayerSchema(): Schema {\n return defineSchema({\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Which sorting layer scrolls slowly.\" }),\n factor: vec2({ x: 0.5, y: 1 }, { tooltip: \"Fraction of the camera's motion the layer follows.\" }),\n repeatX: bool(false, { tooltip: \"Tile the layer horizontally across the camera's view.\" }),\n repeatY: bool(false, { tooltip: \"Tile the layer vertically.\" }),\n repeatWidth: f32(0, { min: 0, tooltip: \"World width of one repetition, in metres.\" }),\n repeatHeight: f32(0, { min: 0, tooltip: \"World height of one repetition, in metres.\" }),\n });\n}\n","import { color, Component, createDefaults, defineSchema, enumOf, str, vec4 } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport type { Schema, Vec4Like } from \"@ignifx/core\";\n\n/**\n * `SpriteLayerEffect` (`docs/architecture/11-2d-toolkit.md` §6): a per-layer custom fragment shader.\n *\n * Lite's 2D path has no lighting model, so effects are what a 2D game reaches for instead: a tint,\n * a dissolve, water, a heat shimmer. A layer created with a `customShader`\n * (`Sprite2DLayerOptions.customShader`, `index.d.ts` 11934) runs a WGSL fragment body with a\n * built-in `fx.time` clock and a `fx.params` vec4 the component writes every frame through\n * `setSprite2DShaderParams` (`index.d.ts` 11074).\n *\n * ## The one-shader-per-layer constraint\n *\n * `Sprite2DLayer.customShader` is `readonly` and is only set at creation. A layer's shader\n * therefore cannot change once sprites are in it, so `SpriteLayerEffect` has to exist **before**\n * the first sprite on its sorting layer is synced — put it in the scene file, or add it in\n * `awake`, not halfway through a level.\n */\n\n/**\n * The built-in effects, in the order an inspector should list them.\n *\n * @public\n */\nexport const SPRITE_EFFECT_KINDS = [\"tint\", \"custom\"] as const;\n\n/**\n * Which shader a `SpriteLayerEffect` installs.\n *\n * @public\n */\nexport type SpriteEffectKind = (typeof SPRITE_EFFECT_KINDS)[number];\n\n/**\n * The WGSL body of the built-in `tint` effect.\n *\n * @remarks\n * Multiplies the sampled texel by `fx.params.rgb` and scales its alpha by `fx.params.a`, which is\n * a per-layer tint that a per-sprite `color` cannot express — every sprite in the layer fades\n * together, in one uniform write, rather than in one instance write each.\n *\n * @public\n */\nexport const TINT_EFFECT_WGSL =\n \"let texel = textureSample(atlasTex, atlasSamp, uv); return vec4f(texel.rgb * fx.params.rgb, texel.a * fx.params.a);\";\n\n/**\n * A per-layer shader effect.\n *\n * @example\n * ```ts\n * const dusk = app.world.createEntity({ name: \"dusk\" }).addComponent(SpriteLayerEffect);\n * dusk.sortingLayer = \"Default\";\n * dusk.kind = \"tint\";\n * dusk.tint = { r: 0.6, g: 0.6, b: 0.9, a: 1 };\n * ```\n *\n * @public\n */\nexport class SpriteLayerEffect extends Component {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/SpriteLayerEffect\";\n\n /** One effect per entity; several entities may each drive a different sorting layer. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = spriteLayerEffectSchema();\n\n /** Which sorting layer the effect applies to. */\n declare sortingLayer: string;\n\n /** Which shader to install. */\n declare kind: SpriteEffectKind;\n\n /** The colour the `tint` effect multiplies by, written into `fx.params`. */\n declare tint: { readonly r: number; readonly g: number; readonly b: number; readonly a: number };\n\n /** The `fx.params` vec4 a `custom` shader reads. */\n declare params: Vec4Like;\n\n /** The WGSL fragment body a `custom` effect installs. */\n declare shader: string;\n\n /**\n * Builds an effect with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(SpriteLayerEffect.schema));\n }\n\n /**\n * The WGSL fragment body this effect installs.\n *\n * @returns The shader source.\n * @throws IgnifxError with code `IGX-1113` when `kind` is `\"custom\"` and `shader` is empty.\n */\n source(): string {\n if (this.kind === \"tint\") {\n return TINT_EFFECT_WGSL;\n }\n if (this.shader === \"\") {\n throw twoDError(TwoDErrorCode.missingShaderSource, \"A custom SpriteLayerEffect needs a WGSL fragment body.\", {\n context: { sortingLayer: this.sortingLayer, entity: this.entity.uid },\n hint: 'Set `effect.shader` to a WGSL body, or use kind: \"tint\".',\n });\n }\n return this.shader;\n }\n\n /**\n * The `fx.params` vec4 to write this frame.\n *\n * @param out - The four numbers to fill.\n * @returns `out`.\n *\n * @internal\n */\n writeParams(out: Float32Array): Float32Array {\n if (this.kind === \"tint\") {\n out[0] = this.tint.r;\n out[1] = this.tint.g;\n out[2] = this.tint.b;\n out[3] = this.tint.a;\n return out;\n }\n out[0] = this.params.x;\n out[1] = this.params.y;\n out[2] = this.params.z;\n out[3] = this.params.w;\n return out;\n }\n}\n\n/**\n * The `SpriteLayerEffect` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction spriteLayerEffectSchema(): Schema {\n return defineSchema({\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Which sorting layer the effect applies to.\" }),\n kind: enumOf(SPRITE_EFFECT_KINDS, \"tint\", { tooltip: \"Which shader to install.\" }),\n tint: color(\"#ffffffff\", { tooltip: \"The colour the tint effect multiplies by.\" }),\n params: vec4({ x: 0, y: 0, z: 0, w: 0 }, { tooltip: \"The fx.params vec4 a custom shader reads.\" }),\n shader: str(\"\", { tooltip: \"The WGSL fragment body a custom effect installs.\" }),\n });\n}\n","import { assertNever } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { DEFAULT_PIXELS_PER_UNIT } from \"../math/coords.js\";\nimport type { TileCollisionInfo, TileCollisionShape } from \"./collision-data.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The `ignifx.tilemap` document — the `.tilemap.json` file that names tile sizes, tilesets, tile\n * layers and object layers (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `11-2d-toolkit.md` §2.5).\n *\n * Two coordinate conventions meet in this file and it is worth stating both loudly, because getting\n * them backwards is the single easiest mistake to make in a tilemap pipeline:\n *\n * - **Authoring space** (everything on `TileColliderDefinition` and every editor this package\n * imports from) is cell-normalised `[0, 1]` with the origin at the **top-left** of the cell and\n * +Y pointing **down**. Tiled and LDtk both emit pixels in that orientation, and the importers\n * divide by the tile size rather than flipping.\n * - **Runtime space** (`TileCollisionShape`, `TilemapCollisionData`, and every world coordinate on\n * `TilemapObjectDefinition`) is metres with the origin at the **bottom-left** and +Y pointing\n * **up**, because that is the ignifx 2D world (ADR-0011).\n *\n * {@link tileCollisionInfo} is the one function that crosses between them, so the flip lives in\n * exactly one place — the same discipline `../math/coords.ts` applies to the render path.\n */\n\n/**\n * The `format` discriminator every `.tilemap.json` document carries.\n *\n * @public\n */\nexport const TILEMAP_FORMAT = \"ignifx.tilemap\";\n\n/**\n * The document version this build reads and writes.\n *\n * @public\n */\nexport const TILEMAP_FORMAT_VERSION = 1;\n\n/**\n * The asset type name the loader registers.\n *\n * @public\n */\nexport const TILEMAP_ASSET_TYPE = \"tilemap\";\n\n/**\n * The address suffixes that select the tilemap loader.\n *\n * @public\n */\nexport const TILEMAP_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".tilemap.json\"]);\n\n/**\n * The tile id that means \"this cell is empty\"; no tileset may claim it.\n *\n * @public\n */\nexport const EMPTY_TILE_ID = 0;\n\n/** The properties record handed back for a tile that declares none; frozen and shared. */\nconst EMPTY_PROPERTIES: Readonly<Record<string, string | number | boolean>> = Object.freeze({});\n\n/** The collision info of a cell that does not collide; frozen and shared. */\nconst NO_TILE_COLLISION: TileCollisionInfo = Object.freeze({\n shape: Object.freeze({ kind: \"none\" } as const),\n oneWay: false,\n properties: EMPTY_PROPERTIES,\n});\n\n/**\n * A tile's collision footprint **as authored**: cell-normalised `[0, 1]` units with the origin at\n * the cell's **top-left** corner and +Y pointing **down**.\n *\n * @remarks\n * This is deliberately *not* {@link TileCollisionShape}, which is cell-local **metres** with a\n * **bottom-left** origin, +Y up and counter-clockwise winding. Editors work top-down and the\n * physics world works bottom-up; {@link tileCollisionInfo} converts, and nothing else should.\n *\n * A box covering the top quarter of a cell — the usual one-way platform — is\n * `{ kind: \"box\", x: 0, y: 0, width: 1, height: 0.25, oneWay: true }`.\n *\n * @public\n */\nexport type TileColliderDefinition =\n | {\n /** Discriminant: an axis-aligned box. */\n readonly kind: \"box\";\n /** The box's left edge, in cell-normalised units. */\n readonly x: number;\n /** The box's **top** edge, in cell-normalised units measured downwards from the cell's top. */\n readonly y: number;\n /** The box's width, in cell-normalised units. */\n readonly width: number;\n /** The box's height, in cell-normalised units. */\n readonly height: number;\n /** Whether the tile is a one-way platform. Defaults to `false`. */\n readonly oneWay?: boolean;\n }\n | {\n /** Discriminant: an outline. */\n readonly kind: \"polygon\";\n /** The vertices in cell-normalised units with a top-left origin, in the editor's winding. */\n readonly points: readonly Vec2Like[];\n /** Whether the tile is a one-way platform. Defaults to `false`. */\n readonly oneWay?: boolean;\n }\n | {\n /** Discriminant: the tile renders but does not collide. */\n readonly kind: \"none\";\n };\n\n/**\n * One frame of an animated tile.\n *\n * @public\n */\nexport interface TileAnimationFrame {\n /** The atlas frame name drawn during this step. */\n readonly frame: string;\n /** How long the step lasts, in milliseconds. */\n readonly durationMs: number;\n}\n\n/**\n * One tile of a tileset: what it draws, what it collides with, and what it carries.\n *\n * @public\n */\nexport interface TileDefinition {\n /** The tile's index **within its tileset**, zero-based; the global id is `tileset.firstId + id`. */\n readonly id: number;\n /** The atlas frame the tile draws, by name. */\n readonly frame: string;\n /** The collision footprint, in cell-normalised top-left-origin units. Absent means no collider. */\n readonly collider?: TileColliderDefinition;\n /** The tile's custom properties, carried through from the editor. */\n readonly properties?: Readonly<Record<string, string | number | boolean>>;\n /** The animation frames, when the tile animates. A single frame is treated as a static tile. */\n readonly animation?: readonly TileAnimationFrame[];\n}\n\n/**\n * A block of tiles cut from one atlas, occupying a contiguous run of global tile ids.\n *\n * @public\n */\nexport interface TilesetDefinition {\n /** The tileset's name, unique within the document; also the frame-name prefix. */\n readonly name: string;\n /** The address of the `.atlas.json` the frames come from; empty for a collision-only tileset. */\n readonly atlas: string;\n /** The global id of this tileset's tile `0`. Always at least `1`, because `0` means empty. */\n readonly firstId: number;\n /** The tiles, indexed by their local {@link TileDefinition.id}. */\n readonly tiles: readonly TileDefinition[];\n}\n\n/**\n * One layer of tiles.\n *\n * @remarks\n * `tiles` is **always** the dense, decoded array in the parsed form: `width * height` global tile\n * ids in row-major order with the **top** row first, which is how every editor stores a grid.\n * `0` ({@link EMPTY_TILE_ID}) means the cell is empty. Runtime code that thinks in +Y-up cell\n * coordinates reads index `(height - 1 - cellY) * width + cellX`.\n *\n * @public\n */\nexport interface TilemapLayerDefinition {\n /** The layer's name, unique within the document. */\n readonly name: string;\n /** The sorting layer the tiles draw in (`docs/architecture/11-2d-toolkit.md` §1). */\n readonly sortingLayer: string;\n /** The order within the sorting layer; higher draws in front. */\n readonly orderInLayer: number;\n /** The layer's opacity in `[0, 1]`. */\n readonly opacity: number;\n /** The parallax multiplier; `{ x: 1, y: 1 }` moves with the camera. */\n readonly parallax: Vec2Like;\n /** Whether the layer contributes collision geometry. */\n readonly collision: boolean;\n /** The layer's width, in cells. */\n readonly width: number;\n /** The layer's height, in cells. */\n readonly height: number;\n /** `width * height` global tile ids, row-major, top row first. */\n readonly tiles: readonly number[];\n}\n\n/**\n * One object placed on the map, to be turned into an entity by a registered `TileObjectFactory`.\n *\n * @remarks\n * `x`, `y`, `width` and `height` are **world metres with +Y up**, and `x`/`y` name the object's\n * **bottom-left** corner. Importers do the conversion out of the editor's top-left pixel space, so\n * nothing downstream has to know what editor the map came from.\n *\n * @public\n */\nexport interface TilemapObjectDefinition {\n /** The object's name, as authored; not required to be unique. */\n readonly name: string;\n /** The object's type — what `app.twoD.registerTileObjectFactory` keys on. */\n readonly type: string;\n /** The left edge, in world metres. */\n readonly x: number;\n /** The bottom edge, in world metres, +Y up. */\n readonly y: number;\n /** The width, in world metres. */\n readonly width: number;\n /** The height, in world metres. */\n readonly height: number;\n /** The object's custom properties. */\n readonly properties: Readonly<Record<string, string | number | boolean>>;\n}\n\n/**\n * The parsed `.tilemap.json` document.\n *\n * @example\n * ```ts\n * const map = defineTilemap({\n * tileWidth: 32,\n * width: 2,\n * height: 1,\n * tilesets: [{ name: \"hero\", atlas: \"2d/hero.atlas.json\", firstId: 1, tiles: [{ id: 0, frame: \"hero_0\" }] }],\n * layers: [{ name: \"Ground\", tiles: [1, 0] }],\n * });\n * map.cellSize; // 0.32 — 32 px at the default 100 pixels per unit\n * ```\n *\n * @public\n */\nexport interface TilemapDefinition {\n /** Always `\"ignifx.tilemap\"`. */\n readonly format: typeof TILEMAP_FORMAT;\n /** Always `1` in this build. */\n readonly formatVersion: number;\n /** The width of one tile, in **pixels**. */\n readonly tileWidth: number;\n /** The height of one tile, in **pixels**. */\n readonly tileHeight: number;\n /**\n * The world size of one cell, in metres — `tileWidth / pixelsPerUnit`.\n *\n * @remarks\n * Collision uses this single number on both axes. A map whose tiles are not square still gets a\n * square collision cell; that is a deliberate MVP limitation and it is why the importers warn\n * nothing and simply record both pixel sizes above.\n */\n readonly cellSize: number;\n /** The map's width, in cells. */\n readonly width: number;\n /** The map's height, in cells. */\n readonly height: number;\n /** The tilesets, sorted by ascending {@link TilesetDefinition.firstId}. */\n readonly tilesets: readonly TilesetDefinition[];\n /** The tile layers, back to front: index `0` draws behind index `1`. */\n readonly layers: readonly TilemapLayerDefinition[];\n /** The objects gathered from every object layer, in document order. */\n readonly objects: readonly TilemapObjectDefinition[];\n /** The map's custom properties. */\n readonly properties: Readonly<Record<string, string | number | boolean>>;\n}\n\n/**\n * A run-length-encoded tile array, as a `.tilemap.json` may store it to keep sparse maps small.\n *\n * @public\n */\nexport interface TileRleData {\n /** Flattened `[count, value, count, value, …]` pairs; see {@link decodeTileRle}. */\n readonly rle: readonly number[];\n}\n\n/**\n * What {@link defineTilemap} accepts for one layer: every defaulted field optional, and `tiles`\n * either dense or run-length encoded.\n *\n * @public\n */\nexport interface TilemapLayerInput {\n /** The layer's name, unique within the document. */\n readonly name: string;\n /** The sorting layer. Defaults to `\"Default\"`. */\n readonly sortingLayer?: string;\n /** The order within the sorting layer. Defaults to `0`. */\n readonly orderInLayer?: number;\n /** The opacity in `[0, 1]`. Defaults to `1`. */\n readonly opacity?: number;\n /** The parallax multiplier. Defaults to `{ x: 1, y: 1 }`. */\n readonly parallax?: Vec2Like;\n /** Whether the layer collides. Defaults to `false`. */\n readonly collision?: boolean;\n /** The layer's width in cells. Defaults to the map's width. */\n readonly width?: number;\n /** The layer's height in cells. Defaults to the map's height. */\n readonly height?: number;\n /** The tile ids, dense (row-major, top row first) or run-length encoded. */\n readonly tiles: readonly number[] | TileRleData;\n}\n\n/**\n * What {@link defineTilemap} accepts: the document with every defaulted field optional.\n *\n * @public\n */\nexport interface TilemapInput {\n /** Always `\"ignifx.tilemap\"` when present. */\n readonly format?: string;\n /** The document version. */\n readonly formatVersion?: number;\n /** The width of one tile, in pixels. */\n readonly tileWidth: number;\n /** The height of one tile, in pixels. Defaults to `tileWidth`. */\n readonly tileHeight?: number;\n /** The metre size of one cell. Defaults to `tileWidth / 100`, the default pixels-per-unit. */\n readonly cellSize?: number;\n /** The map's width, in cells. */\n readonly width: number;\n /** The map's height, in cells. */\n readonly height: number;\n /** The tilesets. Defaults to none. */\n readonly tilesets?: readonly TilesetDefinition[];\n /** The tile layers, back to front. Defaults to none. */\n readonly layers?: readonly TilemapLayerInput[];\n /** The objects. Defaults to none. */\n readonly objects?: readonly TilemapObjectDefinition[];\n /** The map's custom properties. Defaults to none. */\n readonly properties?: Readonly<Record<string, string | number | boolean>>;\n}\n\n/**\n * Run-length encodes a dense tile array.\n *\n * @remarks\n * The layout is flat `[count, value, count, value, …]` pairs, read left to right, so\n * `[1, 1, 0, 0, 0]` encodes to `[2, 1, 3, 0]`. It is the same shape Tiled's chunk encoding and\n * LDtk's exports settle on, and it round-trips exactly through {@link decodeTileRle}.\n *\n * @param tiles - The dense tile ids.\n * @returns The encoded pairs; empty for an empty input.\n *\n * @example\n * ```ts\n * encodeTileRle([1, 1, 0, 0, 0]); // [2, 1, 3, 0]\n * ```\n *\n * @public\n */\nexport function encodeTileRle(tiles: readonly number[]): readonly number[] {\n const out: number[] = [];\n let index = 0;\n while (index < tiles.length) {\n const value = tiles[index] ?? EMPTY_TILE_ID;\n let count = 1;\n while (index + count < tiles.length && tiles[index + count] === value) {\n count += 1;\n }\n out.push(count, value);\n index += count;\n }\n return out;\n}\n\n/**\n * Expands the `[count, value, …]` pairs {@link encodeTileRle} produces back into a dense array.\n *\n * @param rle - The encoded pairs.\n * @returns The dense tile ids.\n * @throws IgnifxError with code `IGX-1105` when the array has an odd length, or a run count that is\n * not a finite non-negative integer.\n *\n * @example\n * ```ts\n * decodeTileRle([2, 1, 3, 0]); // [1, 1, 0, 0, 0]\n * ```\n *\n * @public\n */\nexport function decodeTileRle(rle: readonly number[]): readonly number[] {\n if (rle.length % 2 !== 0) {\n throw twoDError(\n TwoDErrorCode.invalidTilemapFile,\n `A run-length-encoded tile array must hold [count, value] pairs, and this one has ${String(rle.length)} entries.`,\n { context: { file: \"<inline>\", length: rle.length }, hint: \"Re-export the map, or pass a dense tiles array.\" },\n );\n }\n const out: number[] = [];\n for (let index = 0; index < rle.length; index += 2) {\n const count = rle[index] ?? 0;\n const value = rle[index + 1] ?? EMPTY_TILE_ID;\n if (!Number.isInteger(count) || count < 0) {\n throw twoDError(\n TwoDErrorCode.invalidTilemapFile,\n `A run-length-encoded tile array has the run count ${String(count)} at index ${String(index)}.`,\n { context: { file: \"<inline>\", index }, hint: \"Run counts must be non-negative integers.\" },\n );\n }\n for (let repeat = 0; repeat < count; repeat += 1) {\n out.push(value);\n }\n }\n return out;\n}\n\n/**\n * Fills in the defaults of a tilemap document, decodes any run-length-encoded layer, and checks the\n * invariants the renderer and the collider rely on.\n *\n * @param input - The document, as authored or as an importer emitted it.\n * @param address - What to name in an error; defaults to `\"\\<inline\\>\"`.\n * @returns The complete document, with every layer's `tiles` dense.\n * @throws IgnifxError with code `IGX-1105` when the format tag or version is wrong, a tile size is\n * not positive, a tileset's `firstId` is not positive, two layers share a name, a run-length array\n * has an odd length, or a layer's decoded tile count is not `width * height`.\n *\n * @public\n */\nexport function defineTilemap(input: TilemapInput, address = \"<inline>\"): TilemapDefinition {\n const fail = (reason: string): never => {\n throw twoDError(\n TwoDErrorCode.invalidTilemapFile,\n `${address} is not a readable ignifx.tilemap document: ${reason}.`,\n {\n context: { file: address },\n hint: \"Re-import the map with `ignifx import tilemap`, or check the format and version fields.\",\n },\n );\n };\n if (input.format !== undefined && input.format !== TILEMAP_FORMAT) {\n fail(`its format is ${input.format}, not ${TILEMAP_FORMAT}`);\n }\n if (input.formatVersion !== undefined && input.formatVersion !== TILEMAP_FORMAT_VERSION) {\n fail(`its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(TILEMAP_FORMAT_VERSION)}`);\n }\n const tileWidth = input.tileWidth;\n const tileHeight = input.tileHeight ?? input.tileWidth;\n if (!(tileWidth > 0) || !(tileHeight > 0)) {\n fail(`its tile size is ${String(tileWidth)}x${String(tileHeight)} pixels, which is not positive`);\n }\n const width = input.width;\n const height = input.height;\n if (!(width > 0) || !(height > 0)) {\n fail(`its size is ${String(width)}x${String(height)} cells, which is not positive`);\n }\n\n const tilesetsInput = input.tilesets ?? [];\n for (let index = 0; index < tilesetsInput.length; index += 1) {\n const tileset = tilesetsInput[index];\n if (tileset === undefined) {\n continue;\n }\n if (!Number.isInteger(tileset.firstId) || tileset.firstId <= EMPTY_TILE_ID) {\n fail(`tileset ${tileset.name} has firstId ${String(tileset.firstId)}, and 0 is reserved for the empty tile`);\n }\n }\n // A stable ascending order is what makes `findTileset`'s \"highest firstId that fits\" a single\n // backward scan rather than a search over an arbitrary order.\n const tilesets = tilesetsInput.toSorted((left, right) => left.firstId - right.firstId);\n\n const layersInput = input.layers ?? [];\n const layers: TilemapLayerDefinition[] = [];\n const seenLayerNames = new Set<string>();\n for (let index = 0; index < layersInput.length; index += 1) {\n const layer = layersInput[index];\n if (layer === undefined) {\n continue;\n }\n if (seenLayerNames.has(layer.name)) {\n fail(`two layers are named ${layer.name}`);\n }\n seenLayerNames.add(layer.name);\n const layerWidth = layer.width ?? width;\n const layerHeight = layer.height ?? height;\n const tilesInput = layer.tiles;\n const tiles = \"rle\" in tilesInput ? decodeTileRle(tilesInput.rle) : tilesInput;\n if (tiles.length !== layerWidth * layerHeight) {\n fail(\n `layer ${layer.name} is ${String(layerWidth)}x${String(layerHeight)} cells but decodes to ${String(tiles.length)} tiles`,\n );\n }\n layers.push({\n name: layer.name,\n sortingLayer: layer.sortingLayer ?? \"Default\",\n orderInLayer: layer.orderInLayer ?? 0,\n opacity: layer.opacity ?? 1,\n parallax: layer.parallax ?? { x: 1, y: 1 },\n collision: layer.collision ?? false,\n width: layerWidth,\n height: layerHeight,\n tiles,\n });\n }\n\n return {\n format: TILEMAP_FORMAT,\n formatVersion: TILEMAP_FORMAT_VERSION,\n tileWidth,\n tileHeight,\n cellSize: input.cellSize ?? tileWidth / DEFAULT_PIXELS_PER_UNIT,\n width,\n height,\n tilesets,\n layers,\n objects: input.objects ?? [],\n properties: input.properties ?? EMPTY_PROPERTIES,\n };\n}\n\n/**\n * Resolves a global tile id to the tileset that owns it.\n *\n * @remarks\n * The owner is the tileset with the highest {@link TilesetDefinition.firstId} that is still less\n * than or equal to `tileId` — the rule Tiled's `firstgid` implies. `defineTilemap` sorts the\n * tilesets ascending, so this is a backward scan over a handful of entries.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id.\n * @returns The owning tileset, or `null` for the empty tile and for an id no tileset claims.\n *\n * @public\n */\nexport function findTileset(map: TilemapDefinition, tileId: number): TilesetDefinition | null {\n if (tileId <= EMPTY_TILE_ID) {\n return null;\n }\n for (let index = map.tilesets.length - 1; index >= 0; index -= 1) {\n const tileset = map.tilesets[index];\n if (tileset !== undefined && tileset.firstId <= tileId) {\n // An id past the end of the highest tileset belongs to nobody; no earlier tileset can claim\n // it either, because their ranges all end before this one begins.\n return tileId - tileset.firstId < tileset.tiles.length ? tileset : null;\n }\n }\n return null;\n}\n\n/**\n * Resolves a global tile id to the tile entry that describes it.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id.\n * @returns The tile entry, or `null` when no tileset claims the id.\n */\nfunction findTile(map: TilemapDefinition, tileId: number): TileDefinition | null {\n const tileset = findTileset(map, tileId);\n if (tileset === null) {\n return null;\n }\n const localId = tileId - tileset.firstId;\n const byIndex = tileset.tiles[localId];\n if (byIndex !== undefined && byIndex.id === localId) {\n return byIndex;\n }\n for (let index = 0; index < tileset.tiles.length; index += 1) {\n const tile = tileset.tiles[index];\n if (tile !== undefined && tile.id === localId) {\n return tile;\n }\n }\n return null;\n}\n\n/**\n * The atlas frame a global tile id draws.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id.\n * @returns The frame name, or `null` for the empty tile and for an id no tileset claims.\n *\n * @example\n * ```ts\n * tileFrameName(map, 1); // \"hero_0\"\n * ```\n *\n * @public\n */\nexport function tileFrameName(map: TilemapDefinition, tileId: number): string | null {\n return findTile(map, tileId)?.frame ?? null;\n}\n\n/**\n * Resolves a global tile id into the collision information a physics backend consumes.\n *\n * @remarks\n * This is the only place the authoring convention becomes the runtime one. A\n * {@link TileColliderDefinition} is cell-normalised with a **top-left** origin and +Y down; a\n * {@link TileCollisionShape} is cell-local **metres** with a **bottom-left** origin, +Y up and\n * counter-clockwise winding. So:\n *\n * - a box's bottom edge is `(1 - y - height) * cellSize`, because the authored `y` measures the\n * distance from the cell's top down to the box's *top* edge;\n * - a polygon's points each become `(x * cellSize, (1 - y) * cellSize)`, and the point **order is\n * reversed**, because mirroring a ring about a horizontal axis flips its winding — a clockwise\n * editor outline is counter-clockwise once flipped only if it is also walked backwards.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id, `0` for an empty cell.\n * @returns The tile's runtime collision info; a non-colliding, non-one-way default for the empty\n * tile, for an id no tileset claims, and for a tile that declares no collider.\n *\n * @example\n * ```ts\n * // A one-way platform authored as the top quarter of the cell, at cellSize 1:\n * tileCollisionInfo(map, 2).shape; // { kind: \"box\", x: 0, y: 0.75, width: 1, height: 0.25 }\n * ```\n *\n * @public\n */\nexport function tileCollisionInfo(map: TilemapDefinition, tileId: number): TileCollisionInfo {\n const tile = findTile(map, tileId);\n if (tile === null) {\n return NO_TILE_COLLISION;\n }\n const collider = tile.collider;\n const properties = tile.properties ?? EMPTY_PROPERTIES;\n if (collider === undefined) {\n return { shape: { kind: \"none\" }, oneWay: false, properties };\n }\n const cellSize = map.cellSize;\n switch (collider.kind) {\n case \"none\": {\n return { shape: { kind: \"none\" }, oneWay: false, properties };\n }\n case \"box\": {\n const shape: TileCollisionShape = {\n kind: \"box\",\n x: collider.x * cellSize,\n y: (1 - collider.y - collider.height) * cellSize,\n width: collider.width * cellSize,\n height: collider.height * cellSize,\n };\n return { shape, oneWay: collider.oneWay ?? false, properties };\n }\n case \"polygon\": {\n const points: Vec2Like[] = [];\n for (let index = collider.points.length - 1; index >= 0; index -= 1) {\n const point = collider.points[index];\n if (point === undefined) {\n continue;\n }\n points.push({ x: point.x * cellSize, y: (1 - point.y) * cellSize });\n }\n return { shape: { kind: \"polygon\", points }, oneWay: collider.oneWay ?? false, properties };\n }\n default: {\n return assertNever(collider, \"TileColliderDefinition.kind\");\n }\n }\n}\n","import { asset, bool, Component, createDefaults, defineSchema, str, Vec2 } from \"@ignifx/core\";\nimport { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport { createSpriteScratch, writeScratch } from \"../lite/sprite-layer.js\";\nimport { worldToPixelsToRef } from \"../math/coords.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport { tileFrameName } from \"./definition.js\";\nimport type { Tilemap } from \"./tilemap.js\";\nimport type { SpriteScratch } from \"../lite/sprite-layer.js\";\nimport type { LiteBounds2D, LiteSprite2DHandle } from \"../lite/types.js\";\nimport type { SpriteLayerRegistry } from \"../service/layer-registry.js\";\nimport type { AssetHandle, ComponentHooks, MutableVec2, Schema } from \"@ignifx/core\";\n\n/**\n * `TilemapRenderer` (`docs/architecture/11-2d-toolkit.md` §2.5): draws a `Tilemap`'s cells as\n * sprites, one chunk at a time.\n *\n * ## Why chunks\n *\n * A 100x100 map is 10 000 cells. Materialising all of them as sprites costs 10 000 instance slots\n * and, worse, 10 000 per-frame comparisons. Instead the renderer materialises a chunk — 32x32 cells\n * by default — only while it intersects the camera's visible bounds\n * (`getSprite2DVisibleBoundsToRef`, `index.d.ts` 5992), and drops it again when it leaves. A chunk\n * that is up and unchanged costs **nothing** per frame: its sprites are written once, at the moment\n * the chunk is built, and never touched again. That is the property spike S6.1 measures.\n *\n * ## Why the renderer owns its sprites\n *\n * Tiles do not get a `SpriteRenderer` component each — 10 000 components and 10 000 entities is a\n * cost with no benefit, since a tile has no behaviour. The renderer places sprites into the same\n * Lite layers component-owned sprites use, through the registry's raw path, so tiles sort against\n * characters correctly. The trade is that `app.twoD.pickAt` does not resolve a tile;\n * `Tilemap.worldToCell` does, exactly and for free.\n */\n\n/** One materialised chunk. */\ninterface ChunkRecord {\n /** The chunk's column, in chunks. */\n readonly chunkX: number;\n /** The chunk's row, in chunks. */\n readonly chunkY: number;\n /** The layer keys and handles of every sprite in the chunk. */\n readonly sprites: { readonly key: string; readonly handle: LiteSprite2DHandle }[];\n}\n\n/**\n * A tilemap renderer.\n *\n * @example\n * ```ts\n * const level = app.world.createEntity({ name: \"level\" });\n * level.addComponent(Tilemap).map = app.assets.load<TilemapAsset>(\"2d/level-1.tilemap.json\").retain();\n * const renderer = level.addComponent(TilemapRenderer);\n * renderer.atlas = app.assets.load<SpriteAtlasAsset>(\"2d/tiles.atlas.json\").retain();\n * ```\n *\n * @public\n */\nexport class TilemapRenderer extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/TilemapRenderer\";\n\n /** One renderer per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = tilemapRendererSchema();\n\n /** The atlas the tile frames come from. */\n declare atlas: AssetHandle<SpriteAtlasAsset> | null;\n\n /** Which sorting layer the tiles draw on, when the document's layers name none. */\n declare sortingLayer: string;\n\n /** Whether chunks outside the camera's visible bounds are dropped. */\n declare cullChunks: boolean;\n\n /** Chunks currently materialised, keyed by `<chunkX>,<chunkY>`. */\n readonly #chunks = new Map<string, ChunkRecord>();\n\n /** The reusable props record, so building a chunk allocates one object rather than 1024. */\n readonly #scratch: SpriteScratch = createSpriteScratch();\n\n /** Scratch, so the per-chunk arithmetic allocates nothing. */\n readonly #pixels: MutableVec2 = new Vec2();\n\n /** How far animated tiles have advanced, in seconds. */\n #animationClock = 0;\n\n /** Whether every chunk must be rebuilt, because the map or the atlas changed. */\n #isStale = true;\n\n /**\n * Builds a renderer with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(TilemapRenderer.schema));\n }\n\n /**\n * Marks every chunk stale, so a recycled component rebuilds.\n */\n onAttach(): void {\n this.#isStale = true;\n }\n\n /**\n * Marks every chunk stale; the 2D sync system does the removal, because it owns the layers.\n */\n onDetach(): void {\n this.#isStale = true;\n }\n\n /**\n * How many chunks are currently materialised.\n *\n * @returns The count.\n */\n get chunkCount(): number {\n return this.#chunks.size;\n }\n\n /**\n * How many sprites the materialised chunks hold in total.\n *\n * @returns The count.\n */\n get spriteCount(): number {\n let total = 0;\n for (const chunk of this.#chunks.values()) {\n total += chunk.sprites.length;\n }\n return total;\n }\n\n /**\n * The loaded atlas, or `null`.\n *\n * @returns The atlas.\n */\n get loadedAtlas(): SpriteAtlasAsset | null {\n const handle = this.atlas;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * Forces every chunk to be rebuilt on the next sync.\n *\n * @remarks\n * `Tilemap.onTileChanged` is what normally calls this — a rewritten cell has to reach the sprite\n * that draws it, and rebuilding the chunk is both simpler and, for anything short of a per-frame\n * rewrite, cheaper than tracking one sprite per cell.\n *\n * @internal\n */\n invalidate(): void {\n this.#isStale = true;\n }\n\n /**\n * Brings the materialised chunks in line with the camera's visible bounds.\n *\n * @param map - The tilemap being drawn.\n * @param registry - The layer registry that owns the Lite layers.\n * @param bounds - The camera's visible bounds, in layer pixels, or `null` to build every chunk.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @returns How many sprites were written this call; `0` on a steady frame.\n *\n * @internal\n */\n sync(map: Tilemap, registry: SpriteLayerRegistry, bounds: LiteBounds2D | null, pixelsPerUnit: number): number {\n const atlas = this.loadedAtlas;\n const definition = map.definition;\n if (atlas === null || atlas.lite.atlas === null || definition === null) {\n return 0;\n }\n if (this.#isStale) {\n this.#dropAll(registry);\n this.#isStale = false;\n }\n const chunkSize = Math.max(1, map.chunkSize);\n const cellSize = map.cellSize;\n if (cellSize <= 0) {\n return 0;\n }\n const chunksX = Math.ceil(definition.width / chunkSize);\n const chunksY = Math.ceil(definition.height / chunkSize);\n const window = this.#chunkWindow(bounds, chunkSize, cellSize, pixelsPerUnit, chunksX, chunksY);\n let written = 0;\n for (const [key, chunk] of this.#chunks) {\n if (!inWindow(chunk.chunkX, chunk.chunkY, window)) {\n this.#drop(registry, key, chunk);\n }\n }\n for (let chunkY = window.minY; chunkY <= window.maxY; chunkY += 1) {\n for (let chunkX = window.minX; chunkX <= window.maxX; chunkX += 1) {\n const key = `${String(chunkX)},${String(chunkY)}`;\n if (this.#chunks.has(key)) {\n continue;\n }\n written += this.#build(map, atlas, registry, chunkX, chunkY, chunkSize, cellSize, pixelsPerUnit);\n }\n }\n return written;\n }\n\n /**\n * Advances animated tiles and rewrites the chunks holding them.\n *\n * @param deltaSeconds - The scaled frame delta.\n * @returns `true` when a tile's frame changed, so the renderer must rebuild.\n *\n * @internal\n */\n advanceAnimation(deltaSeconds: number): boolean {\n const previous = this.#animationClock;\n this.#animationClock += deltaSeconds;\n // A tile animation is a whole-map property: if any tileset declares one, a frame boundary\n // anywhere invalidates the chunks. Rebuilding on a 100 ms grid is cheap next to tracking every\n // animated cell, and tile animations are authored in tenths of a second, not milliseconds.\n return (\n Math.floor(previous * ANIMATION_TICKS_PER_SECOND) !==\n Math.floor(this.#animationClock * ANIMATION_TICKS_PER_SECOND)\n );\n }\n\n /**\n * The animation clock animated tiles are sampled at, in seconds.\n *\n * @returns The elapsed time.\n *\n * @internal\n */\n get animationClock(): number {\n return this.#animationClock;\n }\n\n /**\n * Drops every materialised chunk.\n *\n * @param registry - The layer registry.\n *\n * @internal\n */\n dropAll(registry: SpriteLayerRegistry): void {\n this.#dropAll(registry);\n }\n\n /**\n * The range of chunks the camera can see.\n *\n * @param bounds - The camera's visible bounds, in layer pixels, or `null`.\n * @param chunkSize - Cells per chunk.\n * @param cellSize - Metres per cell.\n * @param pixelsPerUnit - Pixels per metre.\n * @param chunksX - How many chunk columns the map has.\n * @param chunksY - How many chunk rows.\n * @returns The inclusive chunk window.\n */\n // oxlint-disable-next-line max-params -- once per tilemap per frame; an options object would allocate.\n #chunkWindow(\n bounds: LiteBounds2D | null,\n chunkSize: number,\n cellSize: number,\n pixelsPerUnit: number,\n chunksX: number,\n chunksY: number,\n ): ChunkWindow {\n if (bounds === null || !this.cullChunks) {\n return { minX: 0, minY: 0, maxX: chunksX - 1, maxY: chunksY - 1 };\n }\n const matrix = this.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n // Layer pixels run +Y down, so the bounds' minY is the *top* of the world window.\n const worldMinX = bounds.minX / pixelsPerUnit - originX;\n const worldMaxX = bounds.maxX / pixelsPerUnit - originX;\n const worldMinY = -bounds.maxY / pixelsPerUnit - originY;\n const worldMaxY = -bounds.minY / pixelsPerUnit - originY;\n const span = chunkSize * cellSize;\n return {\n minX: clampIndex(Math.floor(worldMinX / span), chunksX),\n maxX: clampIndex(Math.floor(worldMaxX / span), chunksX),\n minY: clampIndex(Math.floor(worldMinY / span), chunksY),\n maxY: clampIndex(Math.floor(worldMaxY / span), chunksY),\n };\n }\n\n /**\n * Materialises one chunk's sprites.\n *\n * @param map - The tilemap.\n * @param atlas - The tile atlas.\n * @param registry - The layer registry.\n * @param chunkX - The chunk's column.\n * @param chunkY - The chunk's row.\n * @param chunkSize - Cells per chunk.\n * @param cellSize - Metres per cell.\n * @param pixelsPerUnit - Pixels per metre.\n * @returns How many sprites were created.\n */\n // oxlint-disable-next-line max-params -- once per chunk; an options object would allocate per chunk.\n #build(\n map: Tilemap,\n atlas: SpriteAtlasAsset,\n registry: SpriteLayerRegistry,\n chunkX: number,\n chunkY: number,\n chunkSize: number,\n cellSize: number,\n pixelsPerUnit: number,\n ): number {\n const definition = map.definition;\n if (definition === null) {\n return 0;\n }\n const matrix = this.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n const sizePx = cellSize * pixelsPerUnit;\n const sprites: { key: string; handle: LiteSprite2DHandle }[] = [];\n for (let layerIndex = 0; layerIndex < definition.layers.length; layerIndex += 1) {\n const layer = definition.layers[layerIndex];\n if (layer === undefined) {\n continue;\n }\n const sortingLayer = layer.sortingLayer === \"\" ? this.sortingLayer : layer.sortingLayer;\n const alpha = layer.opacity;\n const endX = Math.min(layer.width, (chunkX + 1) * chunkSize);\n const endY = Math.min(layer.height, (chunkY + 1) * chunkSize);\n for (let y = chunkY * chunkSize; y < endY; y += 1) {\n for (let x = chunkX * chunkSize; x < endX; x += 1) {\n const tileId = map.getTile(layerIndex, x, y);\n if (tileId === 0) {\n continue;\n }\n const frameName = tileFrameName(definition, tileId);\n const frame = frameName === null ? -1 : atlas.frameIndex(frameName);\n if (frame < 0) {\n continue;\n }\n const worldX = originX + (x + 0.5) * cellSize;\n const worldY = originY + (y + 0.5) * cellSize;\n const centre = worldToPixelsToRef(worldX, worldY, pixelsPerUnit, this.#pixels);\n writeScratch(this.#scratch, centre.x, centre.y, sizePx, sizePx, frame, 0, 1, 1, 1, alpha, false, false, true);\n sprites.push(registry.placeRaw(sortingLayer, atlas, \"alpha\", false, this.#scratch));\n }\n }\n }\n this.#chunks.set(`${String(chunkX)},${String(chunkY)}`, { chunkX, chunkY, sprites });\n return sprites.length;\n }\n\n /**\n * Removes one chunk's sprites.\n *\n * @param registry - The layer registry.\n * @param key - The chunk key.\n * @param chunk - The chunk record.\n */\n #drop(registry: SpriteLayerRegistry, key: string, chunk: ChunkRecord): void {\n for (let index = chunk.sprites.length - 1; index >= 0; index -= 1) {\n const sprite = chunk.sprites[index];\n if (sprite !== undefined) {\n registry.removeRaw(sprite.key, sprite.handle);\n }\n }\n this.#chunks.delete(key);\n }\n\n /**\n * Removes every chunk's sprites.\n *\n * @param registry - The layer registry.\n */\n #dropAll(registry: SpriteLayerRegistry): void {\n for (const [key, chunk] of this.#chunks) {\n this.#drop(registry, key, chunk);\n }\n this.#chunks.clear();\n }\n}\n\n/** How often an animated tile's frame is allowed to change, in ticks per second. */\nconst ANIMATION_TICKS_PER_SECOND = 10;\n\n/** An inclusive range of chunk indices. */\ninterface ChunkWindow {\n /** The first chunk column. */\n readonly minX: number;\n /** The first chunk row. */\n readonly minY: number;\n /** The last chunk column. */\n readonly maxX: number;\n /** The last chunk row. */\n readonly maxY: number;\n}\n\n/**\n * Whether a chunk is inside a window.\n *\n * @param x - The chunk column.\n * @param y - The chunk row.\n * @param window - The window.\n * @returns `true` when the chunk should stay materialised.\n */\nfunction inWindow(x: number, y: number, window: ChunkWindow): boolean {\n return x >= window.minX && x <= window.maxX && y >= window.minY && y <= window.maxY;\n}\n\n/**\n * Clamps a chunk index into a map's range.\n *\n * @param value - The index.\n * @param count - How many chunks the map has on this axis.\n * @returns The clamped index.\n */\nfunction clampIndex(value: number, count: number): number {\n return Math.min(Math.max(value, 0), Math.max(0, count - 1));\n}\n\n/**\n * The `TilemapRenderer` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction tilemapRendererSchema(): Schema {\n return defineSchema({\n atlas: asset(SpriteAtlasAsset, { tooltip: \"The atlas the tile frames come from.\" }),\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Sorting layer used when a map layer names none.\" }),\n cullChunks: bool(true, { tooltip: \"Drop chunks outside the camera's visible bounds.\" }),\n });\n}\n","import {\n addSprite,\n clearLayer,\n createLayer,\n removeSprite,\n setShaderParams,\n setYSort,\n setYSortOrder,\n spriteIndexOf,\n} from \"../lite/sprite-layer.js\";\nimport type { SortingLayerTable } from \"./sorting-layers.js\";\nimport type { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport type { SpriteScratch, SpriteBlendName } from \"../lite/sprite-layer.js\";\nimport type { LiteSprite2DHandle, LiteSprite2DLayer, LiteSpriteCustomShader } from \"../lite/types.js\";\nimport type { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\n\n/**\n * The pool of Lite sprite layers (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * One `Sprite2DLayer` exists per **(sorting layer, atlas, blend mode, screen-space)** tuple,\n * because Lite binds a layer to one atlas and one blend mode for its whole life (`index.d.ts` 11885\n * declares both `readonly`). Layers are created on demand as sprites appear and torn down with the\n * app; a sprite that changes any part of its key is removed from one layer and added to another,\n * which replaces its handle.\n *\n * The registry also carries the **handle-index to component** map that picking needs. Lite has no\n * per-sprite metadata slot and removes by swapping the last sprite into the freed index\n * (`lib/sprite/sprite-2d-handle.js`), so the map is a dense array kept in step by applying the same\n * swap rule.\n */\n\n/** How many sprites a new layer pre-allocates room for. */\nconst INITIAL_LAYER_CAPACITY = 64;\n\n/**\n * One Lite layer and everything the registry tracks alongside it.\n *\n * @public\n */\nexport interface SpriteLayerEntry {\n /** The composite key, built by {@link spriteLayerKey}. */\n readonly key: string;\n /** The sorting layer's name. */\n readonly sortingLayer: string;\n /** The Lite layer. */\n readonly layer: LiteSprite2DLayer;\n /** Whether the layer keeps the identity view instead of following the `Camera2D`. */\n readonly screenSpace: boolean;\n /** How many sprites the layer currently holds. */\n readonly count: number;\n /** Whether the layer is Y-sorted. */\n readonly ySort: boolean;\n}\n\n/**\n * The registry's internal record for one layer.\n */\ninterface LayerRecord {\n readonly key: string;\n readonly sortingLayer: string;\n readonly layer: LiteSprite2DLayer;\n readonly screenSpace: boolean;\n ySort: boolean;\n /** Component per dense sprite index; kept in step with Lite's swap-remove. */\n readonly components: (SpriteRenderer | null)[];\n}\n\n/**\n * Builds the composite key two sprites must share to land in one Lite layer.\n *\n * @param sortingLayer - The sorting layer's name.\n * @param atlasAddress - The atlas's address.\n * @param blend - The blend mode.\n * @param screenSpace - Whether the layer ignores the camera.\n * @returns The key.\n *\n * @public\n */\nexport function spriteLayerKey(\n sortingLayer: string,\n atlasAddress: string,\n blend: SpriteBlendName,\n screenSpace: boolean,\n): string {\n return `${sortingLayer}|${atlasAddress}|${blend}|${screenSpace ? \"screen\" : \"world\"}`;\n}\n\n/**\n * Owns every Lite sprite layer in one app.\n *\n * @public\n */\nexport class SpriteLayerRegistry {\n readonly #records = new Map<string, LayerRecord>();\n\n /** Records in draw order, rebuilt whenever a layer is created. */\n #ordered: LayerRecord[] = [];\n\n readonly #sortingLayers: SortingLayerTable;\n\n readonly #ySort: Readonly<Record<string, boolean>>;\n\n readonly #onLayerCreated: (layer: LiteSprite2DLayer) => void;\n\n readonly #onLayerRemoved: (layer: LiteSprite2DLayer) => void;\n\n /**\n * Supplies the compiled custom shader a sorting layer's layers are created with.\n *\n * @returns The shader, or `null` when no effect covers the layer.\n */\n #shaderFor: (sortingLayer: string) => LiteSpriteCustomShader | null = (): null => null;\n\n /**\n * Builds the registry.\n *\n * @param sortingLayers - Resolves a sorting-layer name to its draw order.\n * @param ySort - Which sorting layers draw back-to-front by world Y.\n * @param onLayerCreated - Called with each new Lite layer, so the sprite renderer can draw it.\n * @param onLayerRemoved - Called before a layer is dropped.\n */\n constructor(\n sortingLayers: SortingLayerTable,\n ySort: Readonly<Record<string, boolean>>,\n onLayerCreated: (layer: LiteSprite2DLayer) => void,\n onLayerRemoved: (layer: LiteSprite2DLayer) => void,\n ) {\n this.#sortingLayers = sortingLayers;\n this.#ySort = ySort;\n this.#onLayerCreated = onLayerCreated;\n this.#onLayerRemoved = onLayerRemoved;\n }\n\n /**\n * Installs the source of per-sorting-layer custom shaders.\n *\n * @remarks\n * `Sprite2DLayer.customShader` is `readonly` and is only read at creation, so a\n * `SpriteLayerEffect` has to be discoverable **before** the first sprite on its sorting layer is\n * placed. That is why the registry pulls the shader rather than the effect pushing it.\n *\n * @param provider - Returns the compiled shader for a sorting layer, or `null`.\n *\n * @internal\n */\n setShaderProvider(provider: (sortingLayer: string) => LiteSpriteCustomShader | null): void {\n this.#shaderFor = provider;\n }\n\n /**\n * Writes a sorting layer's `fx.params` vec4 onto every layer belonging to it.\n *\n * @param sortingLayer - The sorting layer's name.\n * @param params - The four components.\n *\n * @internal\n */\n writeShaderParams(sortingLayer: string, params: Float32Array): void {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined && record.sortingLayer === sortingLayer) {\n setShaderParams(record.layer, params[0] ?? 0, params[1] ?? 0, params[2] ?? 0, params[3] ?? 0);\n }\n }\n }\n\n /**\n * Every layer, in draw order.\n *\n * @returns A freshly allocated snapshot, for diagnostics.\n */\n describe(): readonly SpriteLayerEntry[] {\n const out: SpriteLayerEntry[] = [];\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined) {\n out.push({\n key: record.key,\n sortingLayer: record.sortingLayer,\n layer: record.layer,\n screenSpace: record.screenSpace,\n count: record.layer.count,\n ySort: record.ySort,\n });\n }\n }\n return out;\n }\n\n /**\n * The Lite layers, in draw order — what picking tests against.\n *\n * @param worldOnly - Whether to skip screen-space layers.\n * @param out - The array to fill; it is emptied first, so one array serves every frame.\n * @returns `out`.\n */\n collectLayers(worldOnly: boolean, out: LiteSprite2DLayer[]): LiteSprite2DLayer[] {\n out.length = 0;\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined && !(worldOnly && record.screenSpace)) {\n out.push(record.layer);\n }\n }\n return out;\n }\n\n /**\n * Walks every layer's view, so the camera can write world layers and skip screen-space ones.\n *\n * @param visit - Called with each layer and whether it follows the camera.\n *\n * @internal\n */\n forEachLayer(visit: (layer: LiteSprite2DLayer, screenSpace: boolean) => void): void {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined) {\n visit(record.layer, record.screenSpace);\n }\n }\n }\n\n /**\n * Adds a sprite to the layer its key selects, creating the layer when it is the first of its kind.\n *\n * @param component - The sprite component.\n * @param atlas - Its loaded atlas.\n * @param scratch - The reusable props record, already written.\n * @returns The key of the layer the sprite landed in.\n *\n * @internal\n */\n place(component: SpriteRenderer, atlas: SpriteAtlasAsset, scratch: SpriteScratch): string {\n const key = spriteLayerKey(component.sortingLayer, atlas.address, component.blend, component.screenSpace);\n const record = this.#ensure(key, component.sortingLayer, component.blend, component.screenSpace, atlas);\n const handle = addSprite(record.layer, scratch);\n const index = spriteIndexOf(handle);\n if (index >= 0) {\n record.components[index] = component;\n }\n component.setPlacement(handle, key);\n return key;\n }\n\n /**\n * Removes a sprite from whichever layer holds it.\n *\n * @param component - The sprite component.\n *\n * @internal\n */\n remove(component: SpriteRenderer): void {\n const placement = component.placement();\n if (placement === null) {\n return;\n }\n const record = this.#records.get(placement.key);\n const index = spriteIndexOf(placement.handle);\n if (record !== undefined && index >= 0) {\n // Lite swap-removes: the last sprite moves into the freed slot. Mirror that in the map.\n const last = record.components.length - 1;\n record.components[index] = record.components[last] ?? null;\n record.components.length = Math.max(0, last);\n }\n removeSprite(placement.handle);\n component.setPlacement(null, null);\n }\n\n /**\n * Adds a sprite that no `SpriteRenderer` owns — a tilemap's tiles.\n *\n * @remarks\n * The sprite occupies a slot in the same layers component-owned sprites use, so it sorts and\n * Y-sorts alongside them, but its slot in the pick map stays empty: `app.twoD.pickAt` resolves\n * `SpriteRenderer` components, and a tile is not one. Pick a tile with `Tilemap.worldToCell`\n * instead, which is exact and costs no draw-order search.\n *\n * @param sortingLayer - The sorting layer's name.\n * @param atlas - The atlas the sprite draws from.\n * @param blend - The blend mode.\n * @param screenSpace - Whether the layer ignores the camera.\n * @param scratch - The reusable props record, already written.\n * @returns The key and the handle.\n *\n * @internal\n */\n placeRaw(\n sortingLayer: string,\n atlas: SpriteAtlasAsset,\n blend: SpriteBlendName,\n screenSpace: boolean,\n scratch: SpriteScratch,\n ): { readonly key: string; readonly handle: LiteSprite2DHandle } {\n const key = spriteLayerKey(sortingLayer, atlas.address, blend, screenSpace);\n const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas);\n const handle = addSprite(record.layer, scratch);\n const index = spriteIndexOf(handle);\n if (index >= 0) {\n record.components[index] = null;\n }\n return { key, handle };\n }\n\n /**\n * Removes a sprite added by {@link SpriteLayerRegistry.placeRaw}.\n *\n * @param key - The key the sprite was placed under.\n * @param handle - The handle.\n *\n * @internal\n */\n removeRaw(key: string, handle: LiteSprite2DHandle): void {\n const record = this.#records.get(key);\n const index = spriteIndexOf(handle);\n if (record !== undefined && index >= 0) {\n const last = record.components.length - 1;\n record.components[index] = record.components[last] ?? null;\n record.components.length = Math.max(0, last);\n }\n removeSprite(handle);\n }\n\n /**\n * Applies a sprite's `orderInLayer` to the layer holding it.\n *\n * @remarks\n * Lite's Y-sort bias setter **throws** on a layer that has no Y-sort state\n * (`lib/sprite/sprite-2d-y-sort.js`, `setSprite2DYSortBias`), so the bias is only written to a\n * layer that is actually sorting. On a layer that is not, `orderInLayer` falls back to ordering\n * by insertion, which is exactly what `docs/architecture/11-2d-toolkit.md` §1 specifies:\n * \"applied as a Y-sort bias when Y-sort is on, or as sub-ordering by insertion when off\"*.\n *\n * @param key - The key of the layer holding the sprite.\n * @param handle - The sprite.\n * @param orderInLayer - The component's `orderInLayer`.\n *\n * @internal\n */\n applyOrderInLayer(key: string, handle: LiteSprite2DHandle, orderInLayer: number): void {\n if (this.#records.get(key)?.ySort === true) {\n setYSortOrder(handle, orderInLayer);\n }\n }\n\n /**\n * Resolves a pick hit back to the component that owns the sprite.\n *\n * @param layer - The Lite layer the hit is in.\n * @param spriteIndex - The dense index the hit reports.\n * @returns The component, or `null` when the slot is unmapped.\n *\n * @internal\n */\n componentAt(layer: LiteSprite2DLayer, spriteIndex: number): SpriteRenderer | null {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record?.layer === layer) {\n return record.components[spriteIndex] ?? null;\n }\n }\n return null;\n }\n\n /**\n * Empties every layer and drops them all.\n *\n * @internal\n */\n clear(): void {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined) {\n clearLayer(record.layer);\n this.#onLayerRemoved(record.layer);\n }\n }\n this.#records.clear();\n this.#ordered = [];\n }\n\n /**\n * Finds or creates the layer a key names.\n *\n * @param key - The composite key.\n * @param sortingLayer - The sorting layer's name.\n * @param blend - The blend mode the layer draws with.\n * @param screenSpace - Whether the layer ignores the camera.\n * @param atlas - The atlas to bind the layer to.\n * @returns The record.\n */\n #ensure(\n key: string,\n sortingLayer: string,\n blend: SpriteBlendName,\n screenSpace: boolean,\n atlas: SpriteAtlasAsset,\n ): LayerRecord {\n const existing = this.#records.get(key);\n if (existing !== undefined) {\n return existing;\n }\n const liteAtlas = atlas.lite.atlas;\n if (liteAtlas === null) {\n throw new Error(\"a sprite layer needs an uploaded atlas; this app is headless\");\n }\n const base = this.#sortingLayers.orderOf(sortingLayer);\n // Sub-layers of one sorting layer are ordered by creation, which is stable across a run and\n // never crosses into the next sorting layer's slice.\n const order = base + this.#countIn(sortingLayer);\n const layer = createLayer(liteAtlas, {\n blend,\n order,\n capacity: INITIAL_LAYER_CAPACITY,\n customShader: this.#shaderFor(sortingLayer),\n });\n const ySort = !screenSpace && this.#ySort[sortingLayer] === true;\n if (ySort) {\n setYSort(layer, true);\n }\n const record: LayerRecord = {\n key,\n sortingLayer,\n layer,\n screenSpace,\n ySort,\n components: [],\n };\n this.#records.set(key, record);\n this.#ordered.push(record);\n this.#ordered.sort(byOrder);\n this.#onLayerCreated(layer);\n return record;\n }\n\n /**\n * How many layers a sorting layer already has, so the next one gets the next sub-order.\n *\n * @param sortingLayer - The sorting layer's name.\n * @returns The count.\n */\n #countIn(sortingLayer: string): number {\n let count = 0;\n for (const record of this.#records.values()) {\n if (record.sortingLayer === sortingLayer) {\n count += 1;\n }\n }\n return count;\n }\n}\n\n/**\n * Orders two layer records by their Lite draw order.\n *\n * @param left - One record.\n * @param right - The other.\n * @returns The comparison.\n */\nfunction byOrder(left: LayerRecord, right: LayerRecord): number {\n return left.layer.order - right.layer.order;\n}\n","import { compileLayerShader, visibleBounds } from \"../lite/sprite-layer.js\";\nimport { ParallaxLayer } from \"../sprite/parallax-layer.js\";\nimport { SpriteLayerEffect } from \"../sprite/sprite-layer-effect.js\";\nimport { TilemapRenderer } from \"../tilemap/tilemap-renderer.js\";\nimport { SpriteLayerRegistry } from \"./layer-registry.js\";\nimport { SortingLayerTable } from \"./sorting-layers.js\";\nimport type { Camera2D } from \"../camera/camera-2d.js\";\nimport type { LiteBounds2D, LiteSprite2DLayer, LiteSpriteCustomShader, LiteSpriteRenderer } from \"../lite/types.js\";\nimport type { TwoDSettings } from \"../settings.js\";\nimport type { App, Disconnect, SceneInstance, World } from \"@ignifx/core\";\n\n/**\n * The mutable state one app's 2D toolkit carries between frames: the resolved settings, the layer\n * registry, the Lite sprite renderer, and the active camera.\n *\n * It exists as its own object rather than as fields on the service because the sync system, the\n * animation system, and the service all need it, and none of them owns the others.\n *\n * ## Why the renderer is created lazily\n *\n * Lite requires the sprite renderer to be registered **after** `registerScene`, so that it\n * composites on top (`index.d.ts` 12205-12209). `@ignifx/core` registers the render scene inside\n * `app.start()`, *after* every extension's `onStart` has already run, and emits no signal when it\n * does — `RendererImpl.isSceneRegistered` is internal. So there is no hook an extension can use.\n * {@link TwoDRuntime.ensureRenderer} closes that gap: the sync system calls it at the top of every\n * `PreRender`, and the first such call happens inside Lite's own frame callback, which only runs\n * once the scene is registered and the loop is going.\n */\n\n/**\n * The Babylon Lite objects `app.twoD` owns.\n *\n * @public\n */\nexport interface TwoDLiteHandles {\n /** The sprite rendering context, or `null` under a headless app or before the first frame. */\n readonly renderer: LiteSpriteRenderer | null;\n}\n\n/**\n * What {@link TwoDRuntime} needs to build itself.\n *\n * @internal\n */\nexport interface TwoDRuntimeOptions {\n /** The app the runtime belongs to. */\n readonly app: App;\n /** The resolved `twoD` settings, options merged over the section. */\n readonly settings: TwoDSettings;\n /** The project's sorting layers, back to front. */\n readonly sortingLayers: readonly string[];\n /** Creates and registers the Lite sprite renderer; `null` under a headless app. */\n readonly createRenderer: (() => LiteSpriteRenderer) | null;\n /** Adds a layer to the renderer's draw list. */\n readonly attachLayer: (renderer: LiteSpriteRenderer, layer: LiteSprite2DLayer) => void;\n /** Removes a layer from the renderer's draw list. */\n readonly detachLayer: (renderer: LiteSpriteRenderer, layer: LiteSprite2DLayer) => void;\n /** Tears the renderer down. */\n readonly destroyRenderer: (renderer: LiteSpriteRenderer) => void;\n}\n\n/**\n * One app's 2D runtime state.\n *\n * @internal\n */\nexport class TwoDRuntime {\n readonly #app: App;\n\n #settings: TwoDSettings;\n\n readonly #sortingLayers: SortingLayerTable;\n\n readonly #registry: SpriteLayerRegistry;\n\n readonly #options: TwoDRuntimeOptions;\n\n #renderer: LiteSpriteRenderer | null = null;\n\n #hasTriedRenderer = false;\n\n #camera: Camera2D | null = null;\n\n #parallax: readonly ParallaxLayer[] = [];\n\n #syncedThisFrame = 0;\n\n #spriteCount = 0;\n\n /** Reused by {@link TwoDRuntime.cameraBounds}. */\n readonly #bounds: LiteBounds2D = { minX: 0, minY: 0, maxX: 0, maxY: 0 };\n\n /** Reused when collecting layers for a bounds read. */\n readonly #boundsLayers: LiteSprite2DLayer[] = [];\n\n /** The effects seen this frame, by sorting layer. */\n readonly #effects = new Map<string, SpriteLayerEffect>();\n\n /** Compiled shaders, cached by WGSL body so one source compiles once. */\n readonly #shaders = new Map<string, LiteSpriteCustomShader>();\n\n /** Reused by {@link TwoDRuntime.writeEffectParams}. */\n readonly #params = new Float32Array(4);\n\n /** Applies a scene file's `settings.twoD` block and spawns its tile objects. */\n #onSceneLoaded: ((scene: SceneInstance) => void) | null = null;\n\n /** Detaches the scene hook when the world goes away. */\n #disconnectScene: Disconnect | null = null;\n\n /**\n * Builds the runtime.\n *\n * @param options - The app, the settings, the sorting layers, and the Lite hooks.\n */\n constructor(options: TwoDRuntimeOptions) {\n this.#app = options.app;\n this.#settings = options.settings;\n this.#options = options;\n this.#sortingLayers = new SortingLayerTable(options.sortingLayers);\n this.#registry = new SpriteLayerRegistry(\n this.#sortingLayers,\n options.settings.ySort,\n (layer: LiteSprite2DLayer): void => {\n const renderer = this.#renderer;\n if (renderer !== null) {\n options.attachLayer(renderer, layer);\n }\n },\n (layer: LiteSprite2DLayer): void => {\n const renderer = this.#renderer;\n if (renderer !== null) {\n options.detachLayer(renderer, layer);\n }\n },\n );\n this.#registry.setShaderProvider((sortingLayer: string): LiteSpriteCustomShader | null =>\n this.#shaderFor(sortingLayer),\n );\n }\n\n /**\n * The resolved settings.\n *\n * @returns The `twoD` settings, after any scene-file override.\n */\n get settings(): TwoDSettings {\n return this.#settings;\n }\n\n /**\n * How many pixels one world metre spans.\n *\n * @returns The conversion factor.\n */\n get pixelsPerUnit(): number {\n return this.#settings.pixelsPerUnit;\n }\n\n /**\n * The sorting-layer resolver.\n *\n * @returns The table.\n */\n get sortingLayers(): SortingLayerTable {\n return this.#sortingLayers;\n }\n\n /**\n * The layer pool.\n *\n * @returns The registry.\n */\n get layers(): SpriteLayerRegistry {\n return this.#registry;\n }\n\n /**\n * The Lite sprite renderer, or `null`.\n *\n * @returns The renderer, or `null` under a headless app or before the first frame.\n */\n get renderer(): LiteSpriteRenderer | null {\n return this.#renderer;\n }\n\n /**\n * The camera the last frame drew through, or `null`.\n *\n * @returns The camera.\n */\n get mainCamera(): Camera2D | null {\n return this.#camera;\n }\n\n /**\n * How many sprites the last frame actually wrote to Lite.\n *\n * @returns The count.\n */\n get syncedLastFrame(): number {\n return this.#syncedThisFrame;\n }\n\n /**\n * How many `SpriteRenderer` components the last frame walked.\n *\n * @returns The count.\n */\n get spriteCount(): number {\n return this.#spriteCount;\n }\n\n /**\n * The surface width the views are sized against, in pixels.\n *\n * @returns The width; `0` under a headless app.\n */\n get viewportWidthPx(): number {\n const surface = this.#app.renderer.surface;\n return surface === null ? 0 : surface.width;\n }\n\n /**\n * The surface height the views are sized against, in pixels.\n *\n * @returns The height; `0` under a headless app.\n */\n get viewportHeightPx(): number {\n const surface = this.#app.renderer.surface;\n return surface === null ? 0 : surface.height;\n }\n\n /**\n * Installs the callback that reacts to a scene load.\n *\n * @remarks\n * The extension cannot connect `world.onSceneLoaded` itself: `register` runs before the world\n * exists, and `onStart` runs only when a game calls `app.start()` — which a headless tool or a\n * test may never do. `System.onWorldCreated` is the one hook that fires for every world, started\n * or not, so the sync system routes it here.\n *\n * @param handler - What to run for each loaded scene.\n */\n setSceneHandler(handler: (scene: SceneInstance) => void): void {\n this.#onSceneLoaded = handler;\n }\n\n /**\n * Connects the scene hook to a world.\n *\n * @param world - The world that was just created.\n */\n attachWorld(world: World): void {\n this.#disconnectScene?.();\n this.#disconnectScene = world.onSceneLoaded.connect((scene: SceneInstance): void => {\n this.#onSceneLoaded?.(scene);\n });\n }\n\n /**\n * Disconnects the scene hook.\n */\n detachWorld(): void {\n this.#disconnectScene?.();\n this.#disconnectScene = null;\n }\n\n /**\n * Replaces the settings, which a scene file's `settings.twoD` block does at load time.\n *\n * @param settings - The new settings.\n */\n applySettings(settings: TwoDSettings): void {\n this.#settings = settings;\n }\n\n /**\n * Records the frame's camera.\n *\n * @param camera - The camera, or `null`.\n */\n setMainCamera(camera: Camera2D | null): void {\n this.#camera = camera;\n }\n\n /**\n * Records the parallax components the sync system should offset views for.\n *\n * @param layers - The components.\n */\n setParallaxLayers(layers: readonly ParallaxLayer[]): void {\n this.#parallax = layers;\n }\n\n /**\n * Offsets each parallax layer's view by the camera's motion times `1 - factor`\n * (`docs/architecture/11-2d-toolkit.md` §2.6).\n */\n applyParallax(): void {\n const camera = this.#camera;\n if (camera === null || this.#parallax.length === 0) {\n return;\n }\n const entries = this.#registry.describe();\n for (let index = 0; index < this.#parallax.length; index += 1) {\n const layer = this.#parallax[index];\n if (layer === undefined || !layer.isEnabledInHierarchy) {\n continue;\n }\n layer.applyTo(entries, camera, this.#settings.pixelsPerUnit);\n }\n }\n\n /**\n * The layer-pixel rectangle the camera can currently see, for chunk culling.\n *\n * @remarks\n * Read off the first world layer's view, which the sync system has already written this frame.\n * Every world layer carries the same view, so any of them answers; `null` means there is no world\n * layer yet, in which case a tilemap builds every chunk and culls from the next frame on.\n *\n * @returns The bounds, or `null`.\n */\n cameraBounds(): LiteBounds2D | null {\n const layers = this.#registry.collectLayers(true, this.#boundsLayers);\n const first = layers[0];\n if (first === undefined || this.viewportWidthPx === 0) {\n return null;\n }\n return visibleBounds(first.view, this.viewportWidthPx, this.viewportHeightPx, this.#bounds);\n }\n\n /**\n * Advances every animated tile on the 2D animation clock.\n *\n * @remarks\n * Implements `AnimatedTilemapSink`, which is what lets the animation system drive tilemaps\n * without importing the renderer.\n *\n * @param world - The world holding the tilemaps.\n * @param deltaSeconds - The scaled frame delta.\n */\n advanceAnimatedTiles(world: World, deltaSeconds: number): void {\n const renderers = world.components(TilemapRenderer);\n for (let index = 0; index < renderers.length; index += 1) {\n const renderer = renderers[index];\n if (renderer !== undefined && renderer.isEnabledInHierarchy && renderer.advanceAnimation(deltaSeconds)) {\n renderer.invalidate();\n }\n }\n }\n\n /**\n * Records the enabled `SpriteLayerEffect` of each sorting layer, so the registry can reach one\n * when it creates a layer.\n *\n * @param world - The world to walk.\n */\n collectEffects(world: World): void {\n const effects = world.components(SpriteLayerEffect);\n this.#effects.clear();\n for (let index = 0; index < effects.length; index += 1) {\n const effect = effects[index];\n if (effect !== undefined && effect.isEnabledInHierarchy) {\n this.#effects.set(effect.sortingLayer, effect);\n }\n }\n const parallax: ParallaxLayer[] = [];\n const layers = world.components(ParallaxLayer);\n for (let index = 0; index < layers.length; index += 1) {\n const layer = layers[index];\n if (layer !== undefined) {\n parallax.push(layer);\n }\n }\n this.setParallaxLayers(parallax);\n }\n\n /**\n * Writes every effect's `fx.params` vec4 onto its sorting layer's Lite layers.\n */\n writeEffectParams(): void {\n for (const [sortingLayer, effect] of this.#effects) {\n effect.writeParams(this.#params);\n this.#registry.writeShaderParams(sortingLayer, this.#params);\n }\n }\n\n /**\n * The compiled custom shader a sorting layer's Lite layers are created with.\n *\n * @param sortingLayer - The sorting layer's name.\n * @returns The shader, or `null` when no effect covers the layer.\n */\n #shaderFor(sortingLayer: string): LiteSpriteCustomShader | null {\n const effect = this.#effects.get(sortingLayer);\n if (effect === undefined) {\n return null;\n }\n const source = effect.source();\n const cached = this.#shaders.get(source);\n if (cached !== undefined) {\n return cached;\n }\n const compiled = compileLayerShader(source);\n this.#shaders.set(source, compiled);\n return compiled;\n }\n\n /**\n * Publishes the frame's sync counters.\n *\n * @param synced - How many sprites were written.\n * @param total - How many sprite components were walked.\n */\n reportSynced(synced: number, total: number): void {\n this.#syncedThisFrame = synced;\n this.#spriteCount = total;\n }\n\n /**\n * Creates and registers the Lite sprite renderer, once, on the first frame that can.\n *\n * @remarks\n * Idempotent, and a no-op under a headless app or once a first attempt has failed. See the\n * module's own remarks for why this cannot happen in `onStart`.\n */\n ensureRenderer(): void {\n if (this.#hasTriedRenderer || this.#options.createRenderer === null) {\n return;\n }\n this.#hasTriedRenderer = true;\n const renderer = this.#options.createRenderer();\n this.#renderer = renderer;\n // Layers created before the renderer existed have to be attached now, in draw order.\n const entries = this.#registry.describe();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry !== undefined) {\n this.#options.attachLayer(renderer, entry.layer);\n }\n }\n }\n\n /**\n * Drops every layer and the renderer.\n */\n dispose(): void {\n this.detachWorld();\n this.#registry.clear();\n const renderer = this.#renderer;\n this.#renderer = null;\n if (renderer !== null) {\n this.#options.destroyRenderer(renderer);\n }\n }\n}\n","import type { TileCollisionInfo, TilemapCollisionChunk, TilemapCollisionData } from \"./collision-data.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The greedy merge that turns a grid of per-tile collision shapes into the handful of polygons a 2D\n * physics backend actually wants (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * A tilemap with ten thousand solid cells must not become ten thousand colliders: Rapier would\n * spend its whole broad-phase on them and the island solver would never sleep. Merging a solid\n * region into one polygon per rectangle is the standard fix, and it is worth doing at rebuild time\n * because a rebuild is rare and a step is not.\n */\n\n/**\n * The grid {@link mergeTileCollisions} walks.\n *\n * @public\n */\nexport interface CollisionMergeOptions {\n /** The edge length of one cell, in metres. */\n readonly cellSize: number;\n /** The edge length of one chunk, in cells; `32` is what `TilemapRenderer` uses. */\n readonly chunkSize: number;\n /** The grid's width, in cells. */\n readonly width: number;\n /** The grid's height, in cells. */\n readonly height: number;\n}\n\n/**\n * One maximal horizontal run of full-cell solid tiles inside a chunk, in chunk-local cells.\n */\ninterface SolidRun {\n /** The run's first column, chunk-local. */\n readonly start: number;\n /** The run's last column, chunk-local and inclusive. */\n readonly end: number;\n /** Whether an earlier row has already absorbed this run into a taller block. */\n consumed: boolean;\n}\n\n/**\n * Whether a tile's collider fills its whole cell and is not a one-way platform — the only shape the\n * rectangle merge can absorb.\n *\n * @param info - The tile's collision info, in cell-local metres.\n * @param cellSize - The edge length of one cell, in metres.\n * @returns Whether the tile is a plain, full-cell solid.\n *\n * @example\n * ```ts\n * isFullCellSolid({ shape: { kind: \"box\", x: 0, y: 0, width: 1, height: 1 }, oneWay: false, properties: {} }, 1);\n * // true\n * ```\n *\n * @public\n */\nexport function isFullCellSolid(info: TileCollisionInfo, cellSize: number): boolean {\n if (info.oneWay) {\n return false;\n }\n const shape = info.shape;\n return (\n shape.kind === \"box\" && shape.x === 0 && shape.y === 0 && shape.width === cellSize && shape.height === cellSize\n );\n}\n\n/**\n * Merges a grid of per-tile collision shapes into chunked, world-space polygons.\n *\n * @remarks\n * **Coordinates.** `infoAt` is called with cell coordinates in which `y = 0` is the **bottom** row,\n * because the ignifx 2D world is +Y up; a caller reading a `TilemapLayerDefinition`, whose rows run\n * top-first, indexes it as `(height - 1 - y) * width + x`. Everything this function emits is world\n * metres relative to the tilemap's origin, so cell `(x, y)` spans\n * `[x·cellSize, (x+1)·cellSize] × [y·cellSize, (y+1)·cellSize]`.\n *\n * **The merge.** Each chunk is handled independently, so a later edit rebuilds one chunk rather than\n * the map. Inside a chunk, cells that {@link isFullCellSolid} accepts go into a boolean grid and are\n * merged in two greedy passes: first every row is cut into maximal horizontal runs, then a run\n * extends upwards for as long as the row above holds a run with exactly the same span, which is\n * marked consumed. Each surviving block is emitted as one counter-clockwise rectangle. It is the\n * classic row-then-column greedy mesher: linear in cells plus a small scan per row, and optimal for\n * rectangles while deliberately not optimal in general — an L-shape comes out as two rectangles, not\n * one six-vertex polygon, and that is the trade the algorithm makes for being O(n).\n *\n * Anything the rectangle pass cannot absorb — a partial box, a slope polygon — is emitted as its own\n * polygon, translated into world metres. Its winding is already counter-clockwise, because\n * `tileCollisionInfo` guarantees it.\n *\n * **One-way platforms.** A one-way tile contributes no polygon at all; it contributes its collider's\n * **top edge** to `oneWayEdges`. The winding follows the same rule as a polygon: the solid material\n * is to the **left** of `from → to`. For a directed edge `d = to − from`, \"left\" is `d` rotated a\n * quarter turn counter-clockwise, `(−dy, dx)`. An upward-facing platform is solid *below* its\n * surface — that is the half you cannot pass through once you have landed — so we need\n * `(−dy, dx) = (0, −1)`, giving `dy = 0` and `dx = −1`. The edge therefore runs from its **right**\n * end to its **left** end.\n *\n * Chunks that end up with neither a polygon nor a one-way edge are omitted entirely.\n *\n * @param infoAt - The per-cell collision info, in cell coordinates with `y = 0` at the bottom.\n * @param options - The cell size, chunk size, and grid extent.\n * @param version - The version stamp to carry into the result; callers increment it per rebuild.\n * @returns The chunked collision data.\n *\n * @example\n * ```ts\n * const data = mergeTileCollisions((x, y) => tileCollisionInfo(map, tileAt(x, y)), {\n * cellSize: map.cellSize,\n * chunkSize: 32,\n * width: map.width,\n * height: map.height,\n * }, 1);\n * ```\n *\n * @public\n */\nexport function mergeTileCollisions(\n infoAt: (x: number, y: number) => TileCollisionInfo,\n options: CollisionMergeOptions,\n version: number,\n): TilemapCollisionData {\n const { cellSize, chunkSize, width, height } = options;\n const chunks: TilemapCollisionChunk[] = [];\n if (cellSize <= 0 || chunkSize <= 0 || width <= 0 || height <= 0) {\n return { cellSize, chunkSize, chunks, version };\n }\n const chunksX = Math.ceil(width / chunkSize);\n const chunksY = Math.ceil(height / chunkSize);\n for (let chunkY = 0; chunkY < chunksY; chunkY += 1) {\n for (let chunkX = 0; chunkX < chunksX; chunkX += 1) {\n const chunk = mergeChunk(infoAt, options, chunkX, chunkY);\n if (chunk !== null) {\n chunks.push(chunk);\n }\n }\n }\n return { cellSize, chunkSize, chunks, version };\n}\n\n/**\n * Merges one chunk of the grid.\n *\n * @param infoAt - The per-cell collision info.\n * @param options - The cell size, chunk size, and grid extent.\n * @param chunkX - The chunk's column index.\n * @param chunkY - The chunk's row index.\n * @returns The chunk, or `null` when it carries no geometry.\n */\nfunction mergeChunk(\n infoAt: (x: number, y: number) => TileCollisionInfo,\n options: CollisionMergeOptions,\n chunkX: number,\n chunkY: number,\n): TilemapCollisionChunk | null {\n const { cellSize, chunkSize, width, height } = options;\n const originX = chunkX * chunkSize;\n const originY = chunkY * chunkSize;\n const columns = Math.min(chunkSize, width - originX);\n const rows = Math.min(chunkSize, height - originY);\n const polygons: (readonly Vec2Like[])[] = [];\n const oneWayEdges: (readonly [Vec2Like, Vec2Like])[] = [];\n const solid = new Uint8Array(columns * rows);\n\n for (let localY = 0; localY < rows; localY += 1) {\n for (let localX = 0; localX < columns; localX += 1) {\n const cellX = originX + localX;\n const cellY = originY + localY;\n const info = infoAt(cellX, cellY);\n const shape = info.shape;\n if (shape.kind === \"none\") {\n continue;\n }\n if (info.oneWay) {\n const edge = topEdge(shape, cellX * cellSize, cellY * cellSize);\n if (edge !== null) {\n oneWayEdges.push(edge);\n }\n continue;\n }\n if (isFullCellSolid(info, cellSize)) {\n solid[localY * columns + localX] = 1;\n continue;\n }\n polygons.push(translateShape(shape, cellX * cellSize, cellY * cellSize));\n }\n }\n\n mergeSolidRuns(solid, columns, rows, originX, originY, cellSize, polygons);\n\n if (polygons.length === 0 && oneWayEdges.length === 0) {\n return null;\n }\n return { chunkX, chunkY, polygons, oneWayEdges };\n}\n\n/**\n * Runs the row-then-column greedy merge over the chunk's full-cell solid mask.\n *\n * @param solid - The `columns * rows` mask, row-major with row `0` at the bottom.\n * @param columns - The chunk's width in cells.\n * @param rows - The chunk's height in cells.\n * @param originX - The chunk's first column, in grid cells.\n * @param originY - The chunk's first row, in grid cells.\n * @param cellSize - The edge length of one cell, in metres.\n * @param out - The polygon list to append merged rectangles to.\n */\nfunction mergeSolidRuns(\n solid: Uint8Array,\n columns: number,\n rows: number,\n originX: number,\n originY: number,\n cellSize: number,\n out: (readonly Vec2Like[])[],\n): void {\n const runsByRow: SolidRun[][] = [];\n for (let localY = 0; localY < rows; localY += 1) {\n const runs: SolidRun[] = [];\n let localX = 0;\n while (localX < columns) {\n if (solid[localY * columns + localX] !== 1) {\n localX += 1;\n continue;\n }\n const start = localX;\n while (localX + 1 < columns && solid[localY * columns + localX + 1] === 1) {\n localX += 1;\n }\n runs.push({ start, end: localX, consumed: false });\n localX += 1;\n }\n runsByRow.push(runs);\n }\n\n for (let localY = 0; localY < rows; localY += 1) {\n const runs = runsByRow[localY];\n if (runs === undefined) {\n continue;\n }\n for (let index = 0; index < runs.length; index += 1) {\n const run = runs[index];\n if (run === undefined || run.consumed) {\n continue;\n }\n let top = localY;\n while (top + 1 < rows) {\n const above = findRun(runsByRow[top + 1], run.start, run.end);\n if (above === null) {\n break;\n }\n above.consumed = true;\n top += 1;\n }\n const left = (originX + run.start) * cellSize;\n const right = (originX + run.end + 1) * cellSize;\n const bottom = (originY + localY) * cellSize;\n const ceiling = (originY + top + 1) * cellSize;\n out.push([\n { x: left, y: bottom },\n { x: right, y: bottom },\n { x: right, y: ceiling },\n { x: left, y: ceiling },\n ]);\n }\n }\n}\n\n/**\n * Finds an unconsumed run with exactly the given span.\n *\n * @param runs - The candidate row's runs.\n * @param start - The span's first column.\n * @param end - The span's last column.\n * @returns The matching run, or `null`.\n */\nfunction findRun(runs: readonly SolidRun[] | undefined, start: number, end: number): SolidRun | null {\n if (runs === undefined) {\n return null;\n }\n for (let index = 0; index < runs.length; index += 1) {\n const run = runs[index];\n if (run !== undefined && !run.consumed && run.start === start && run.end === end) {\n return run;\n }\n }\n return null;\n}\n\n/**\n * Moves a cell-local shape into world metres.\n *\n * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.\n * @param offsetX - The cell's left edge, in world metres.\n * @param offsetY - The cell's bottom edge, in world metres.\n * @returns The outline, counter-clockwise, in world metres.\n */\nfunction translateShape(shape: TileCollisionInfo[\"shape\"], offsetX: number, offsetY: number): readonly Vec2Like[] {\n if (shape.kind === \"box\") {\n const left = offsetX + shape.x;\n const bottom = offsetY + shape.y;\n const right = left + shape.width;\n const top = bottom + shape.height;\n return [\n { x: left, y: bottom },\n { x: right, y: bottom },\n { x: right, y: top },\n { x: left, y: top },\n ];\n }\n if (shape.kind === \"polygon\") {\n const points: Vec2Like[] = [];\n for (let index = 0; index < shape.points.length; index += 1) {\n const point = shape.points[index];\n if (point !== undefined) {\n points.push({ x: offsetX + point.x, y: offsetY + point.y });\n }\n }\n return points;\n }\n return [];\n}\n\n/**\n * The top edge of a one-way tile's collider, wound so the solid side is to the left.\n *\n * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.\n * @param offsetX - The cell's left edge, in world metres.\n * @param offsetY - The cell's bottom edge, in world metres.\n * @returns The `[from, to]` pair, right end first, or `null` when the shape has no width.\n */\nfunction topEdge(\n shape: TileCollisionInfo[\"shape\"],\n offsetX: number,\n offsetY: number,\n): readonly [Vec2Like, Vec2Like] | null {\n if (shape.kind === \"box\") {\n if (shape.width <= 0) {\n return null;\n }\n const left = offsetX + shape.x;\n const right = left + shape.width;\n const top = offsetY + shape.y + shape.height;\n return [\n { x: right, y: top },\n { x: left, y: top },\n ];\n }\n if (shape.kind === \"polygon\") {\n let left = Number.POSITIVE_INFINITY;\n let right = Number.NEGATIVE_INFINITY;\n let top = Number.NEGATIVE_INFINITY;\n for (let index = 0; index < shape.points.length; index += 1) {\n const point = shape.points[index];\n if (point === undefined) {\n continue;\n }\n left = Math.min(left, point.x);\n right = Math.max(right, point.x);\n top = Math.max(top, point.y);\n }\n if (!(right > left)) {\n return null;\n }\n return [\n { x: offsetX + right, y: offsetY + top },\n { x: offsetX + left, y: offsetY + top },\n ];\n }\n return null;\n}\n","import { resolveRelative } from \"../assets/relative.js\";\nimport { defineTilemap, TILEMAP_ASSET_TYPE, TILEMAP_FILE_EXTENSIONS } from \"./definition.js\";\nimport type { TilemapDefinition, TilemapInput } from \"./definition.js\";\nimport type { AssetLoader, LoaderContext } from \"@ignifx/core\";\n\n/**\n * The `tilemap` asset type and its loader (`docs/architecture/05-assets-and-loading.md` §5,\n * `11-2d-toolkit.md` §2.5).\n *\n * A `.tilemap.json` document is pure data — tile ids, tilesets, objects — so the loader needs no\n * device and behaves identically under a headless app, which is what lets a headless test assert\n * collision geometry and object spawning. The atlases the tilesets name are loaded by\n * `TilemapRenderer`, not here: a map with six tilesets in a scene that only shows one chunk should\n * not upload six textures at load time.\n */\n\n/**\n * A loaded tilemap document.\n *\n * @example\n * ```ts\n * const map = await app.assets.load<TilemapAsset>(\"2d/level-1.tilemap.json\").promise;\n * map.definition.layers.length; // 2\n * ```\n *\n * @public\n */\nexport class TilemapAsset {\n /** The type name the asset service registers tilemaps under. */\n static assetType: string = TILEMAP_ASSET_TYPE;\n\n /** The address the document was loaded from. */\n readonly address: string;\n\n /** The parsed document, with every tile layer decoded to a dense array. */\n readonly definition: TilemapDefinition;\n\n /** Each tileset's atlas address, resolved against this document's address. */\n readonly atlasAddresses: readonly string[];\n\n /**\n * Wraps a parsed document. The `tilemap` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The parsed document.\n *\n * @internal\n */\n constructor(address: string, definition: TilemapDefinition) {\n this.address = address;\n this.definition = definition;\n const atlases: string[] = [];\n for (let index = 0; index < definition.tilesets.length; index += 1) {\n const tileset = definition.tilesets[index];\n atlases.push(tileset === undefined ? \"\" : resolveRelative(address, tileset.atlas));\n }\n this.atlasAddresses = atlases;\n }\n\n /**\n * The atlas address a tileset's tiles come from.\n *\n * @param tilesetIndex - The tileset's index in the document.\n * @returns The address, or `\"\"` when the index is out of range.\n */\n atlasFor(tilesetIndex: number): string {\n return this.atlasAddresses[tilesetIndex] ?? \"\";\n }\n}\n\n/**\n * Builds the loader for `.tilemap.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createTilemapLoader());\n * ```\n *\n * @public\n */\nexport function createTilemapLoader(): AssetLoader<TilemapAsset> {\n return {\n type: TILEMAP_ASSET_TYPE,\n extensions: TILEMAP_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<TilemapAsset> {\n const raw = await ctx.fetchJson<TilemapInput>();\n return new TilemapAsset(ctx.address, defineTilemap(raw, ctx.address));\n },\n };\n}\n","import { asset, Component, createDefaults, defineSchema, f32, Signal, u32 } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { mergeTileCollisions } from \"./collision-merge.js\";\nimport { tileCollisionInfo } from \"./definition.js\";\nimport { TilemapAsset } from \"./tilemap-asset.js\";\nimport type { TileCollisionInfo, TilemapCollisionData } from \"./collision-data.js\";\nimport type { TilemapDefinition } from \"./definition.js\";\nimport type { AssetHandle, ComponentHooks, MutableVec2, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `Tilemap` (`docs/architecture/11-2d-toolkit.md` §2.5): the grid of tile ids a level is built\n * from, its cell arithmetic, and the merged collision geometry `@ignifx/physics-2d` consumes.\n *\n * The component holds no Lite object — `TilemapRenderer` draws it — so a headless app carries the\n * full grid and the full collision surface. That is what makes a level's collision testable\n * without a GPU, and what lets a server run the same map the client draws.\n *\n * ## Coordinates\n *\n * Cell `(0, 0)` is the **bottom-left** of the map, because ignifx 2D is +Y up (ADR-0011). The\n * document's own layers are stored top row first, as every editor writes them, and the component\n * flips on the way in. `worldToCell`/`cellToWorld` are relative to the tilemap entity's own\n * transform, so moving the entity moves the whole map.\n */\n\n/**\n * How many cells one chunk spans by default (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * @public\n */\nexport const DEFAULT_CHUNK_SIZE = 32;\n\n/**\n * One tile change, as {@link Tilemap.onTileChanged} reports it.\n *\n * @public\n */\nexport interface TileChange {\n /** The layer's index in the document. */\n readonly layer: number;\n /** The cell's column, with `0` at the left. */\n readonly x: number;\n /** The cell's row, with `0` at the **bottom**. */\n readonly y: number;\n /** The tile id that was there. */\n readonly previous: number;\n /** The tile id that is there now. */\n readonly current: number;\n}\n\n/**\n * A tilemap.\n *\n * @example\n * ```ts\n * const level = app.world.createEntity({ name: \"level\" }).addComponent(Tilemap);\n * level.map = app.assets.load<TilemapAsset>(\"2d/level-1.tilemap.json\").retain();\n * level.setTile(0, 3, 2, 0); // carve a hole in the ground layer\n * ```\n *\n * @public\n */\nexport class Tilemap extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/Tilemap\";\n\n /** One tilemap per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = tilemapSchema();\n\n /** The `.tilemap.json` document. */\n declare map: AssetHandle<TilemapAsset> | null;\n\n /** How many cells one chunk spans on each axis. */\n declare chunkSize: number;\n\n /** The metres one cell spans, overriding the document's own; `0` uses the document's. */\n declare cellSizeOverride: number;\n\n /** The mutable tile grids, bottom row first, one per document layer. */\n #grids: Int32Array[] = [];\n\n /** The document the grids were built from, so a swapped asset rebuilds them. */\n #built: TilemapAsset | null = null;\n\n /** The merged collision surface, rebuilt lazily after a change. */\n #collision: TilemapCollisionData = EMPTY_COLLISION;\n\n /** Whether the collision surface needs rebuilding. */\n #collisionDirty = true;\n\n /** Bumped on every collision rebuild, so a physics backend can skip unchanged frames. */\n #version = 0;\n\n readonly #onTileChanged = new Signal<TileChange>();\n\n readonly #onCollisionChanged = new Signal();\n\n /**\n * Builds a tilemap with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(Tilemap.schema));\n }\n\n /**\n * Drops the grids, so a recycled component does not inherit the previous one's.\n */\n onAttach(): void {\n this.#grids = [];\n this.#built = null;\n this.#collision = EMPTY_COLLISION;\n this.#collisionDirty = true;\n }\n\n /**\n * Releases the grids.\n */\n onDetach(): void {\n this.#grids = [];\n this.#built = null;\n }\n\n /**\n * Emitted whenever `setTile` changes a cell.\n *\n * @returns The signal.\n */\n get onTileChanged(): Signal<TileChange> {\n return this.#onTileChanged;\n }\n\n /**\n * Emitted after the merged collision surface has been rebuilt.\n *\n * @remarks\n * `@ignifx/physics-2d` connects to this and rebuilds only the chunks whose geometry moved. The\n * rebuild is lazy: the signal fires on the first read of {@link Tilemap.collisionData} after a\n * change, not on the `setTile` call itself, so a script that rewrites a thousand tiles in one\n * frame pays for one merge.\n *\n * @returns The signal.\n */\n get onCollisionChanged(): Signal {\n return this.#onCollisionChanged;\n }\n\n /**\n * The loaded document, or `null` while it is still loading.\n *\n * @returns The asset.\n */\n get asset(): TilemapAsset | null {\n const handle = this.map;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * The parsed document, or `null`.\n *\n * @returns The definition.\n */\n get definition(): TilemapDefinition | null {\n return this.asset?.definition ?? null;\n }\n\n /**\n * How many metres one cell spans.\n *\n * @returns The cell size; `0` when nothing has loaded.\n */\n get cellSize(): number {\n if (this.cellSizeOverride > 0) {\n return this.cellSizeOverride;\n }\n return this.definition?.cellSize ?? 0;\n }\n\n /**\n * How many layers the document has.\n *\n * @returns The layer count.\n */\n get layerCount(): number {\n return this.definition?.layers.length ?? 0;\n }\n\n /**\n * The merged collision surface, rebuilt if a tile changed since the last read.\n *\n * @remarks\n * The shape is the contract `@ignifx/physics-2d` consumes: chunked, in world metres relative to\n * the tilemap entity's origin, with adjacent full-cell tiles merged into as few counter-clockwise\n * rectangles as possible.\n *\n * @returns The collision data.\n */\n get collisionData(): TilemapCollisionData {\n if (this.#collisionDirty) {\n this.#rebuildCollision();\n }\n return this.#collision;\n }\n\n /**\n * Reads a tile.\n *\n * @param layer - The layer's index in the document.\n * @param x - The cell's column, with `0` at the left.\n * @param y - The cell's row, with `0` at the bottom.\n * @returns The tile id, or `0` for an empty or out-of-range cell.\n */\n getTile(layer: number, x: number, y: number): number {\n this.#ensureGrids();\n const definition = this.definition;\n const grid = this.#grids[layer];\n const declared = definition?.layers[layer];\n if (grid === undefined || declared === undefined || !inRange(x, y, declared.width, declared.height)) {\n return 0;\n }\n return grid[y * declared.width + x] ?? 0;\n }\n\n /**\n * Writes a tile.\n *\n * @param layer - The layer's index in the document.\n * @param x - The cell's column, with `0` at the left.\n * @param y - The cell's row, with `0` at the bottom.\n * @param tileId - The tile id, or `0` to clear the cell.\n * @throws IgnifxError with code `IGX-1111` when the cell is outside the layer.\n */\n setTile(layer: number, x: number, y: number, tileId: number): void {\n this.#ensureGrids();\n const definition = this.definition;\n const grid = this.#grids[layer];\n const declared = definition?.layers[layer];\n if (grid === undefined || declared === undefined || !inRange(x, y, declared.width, declared.height)) {\n throw twoDError(\n TwoDErrorCode.tileOutOfRange,\n `Cell ${String(x)},${String(y)} is outside layer ${String(layer)}.`,\n {\n context: { x, y, layer },\n hint: \"Check the cell against Tilemap.layerSize; cell (0, 0) is the bottom-left.\",\n },\n );\n }\n const offset = y * declared.width + x;\n const previous = grid[offset] ?? 0;\n if (previous === tileId) {\n return;\n }\n grid[offset] = tileId;\n if (declared.collision) {\n this.#collisionDirty = true;\n }\n this.#onTileChanged.emit({ layer, x, y, previous, current: tileId });\n }\n\n /**\n * A layer's size, in cells.\n *\n * @param layer - The layer's index.\n * @returns The size, or a zero size for an unknown layer.\n */\n layerSize(layer: number): Vec2Like {\n const declared = this.definition?.layers[layer];\n return declared === undefined ? ZERO : { x: declared.width, y: declared.height };\n }\n\n /**\n * Converts a world point into the cell containing it.\n *\n * @remarks\n * The point is in world metres; the map's own origin is the tilemap entity's position, so a moved\n * or scaled tilemap still answers correctly. The result is floored, so a point exactly on a cell\n * boundary belongs to the cell above and to the right of it.\n *\n * @param point - The world point, in metres.\n * @param out - The vector to write.\n * @returns `out`, holding integer cell coordinates that may be outside the map.\n */\n worldToCell<TOut extends MutableVec2>(point: Vec2Like, out: TOut): TOut {\n const size = this.cellSize;\n const matrix = this.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n if (size <= 0) {\n out.x = 0;\n out.y = 0;\n return out;\n }\n out.x = Math.floor((point.x - originX) / size);\n out.y = Math.floor((point.y - originY) / size);\n return out;\n }\n\n /**\n * Converts a cell into the world point at its **centre**.\n *\n * @param x - The cell's column.\n * @param y - The cell's row, with `0` at the bottom.\n * @param out - The vector to write.\n * @returns `out`, in world metres.\n */\n cellToWorld<TOut extends MutableVec2>(x: number, y: number, out: TOut): TOut {\n const size = this.cellSize;\n const matrix = this.entity.transform.worldMatrix;\n out.x = (matrix[12] ?? 0) + (x + 0.5) * size;\n out.y = (matrix[13] ?? 0) + (y + 0.5) * size;\n return out;\n }\n\n /**\n * The collision footprint of whatever is at a cell, across every collision layer.\n *\n * @param x - The cell's column.\n * @param y - The cell's row, with `0` at the bottom.\n * @returns The topmost non-empty collider, or a `\"none\"` shape.\n */\n collisionAt(x: number, y: number): TileCollisionInfo {\n const definition = this.definition;\n if (definition === null) {\n return NO_COLLISION;\n }\n for (let layer = definition.layers.length - 1; layer >= 0; layer -= 1) {\n const declared = definition.layers[layer];\n if (declared === undefined || !declared.collision) {\n continue;\n }\n const info = tileCollisionInfo(definition, this.getTile(layer, x, y));\n if (info.shape.kind !== \"none\") {\n return info;\n }\n }\n return NO_COLLISION;\n }\n\n /**\n * Forces the collision surface to be rebuilt on the next read.\n *\n * @internal\n */\n invalidateCollision(): void {\n this.#collisionDirty = true;\n }\n\n /**\n * Builds the mutable grids from the document, flipping each layer bottom-row-first.\n */\n #ensureGrids(): void {\n const loaded = this.asset;\n if (loaded === null || loaded === this.#built) {\n return;\n }\n this.#built = loaded;\n this.#collisionDirty = true;\n const grids: Int32Array[] = [];\n const layers = loaded.definition.layers;\n for (let index = 0; index < layers.length; index += 1) {\n const layer = layers[index];\n if (layer === undefined) {\n grids.push(new Int32Array(0));\n continue;\n }\n const grid = new Int32Array(layer.width * layer.height);\n for (let row = 0; row < layer.height; row += 1) {\n // The document stores the top row first; cell row 0 is the bottom.\n const source = (layer.height - 1 - row) * layer.width;\n for (let column = 0; column < layer.width; column += 1) {\n grid[row * layer.width + column] = layer.tiles[source + column] ?? 0;\n }\n }\n grids.push(grid);\n }\n this.#grids = grids;\n }\n\n /**\n * Merges every collision layer's tiles into chunked polygons.\n */\n #rebuildCollision(): void {\n this.#ensureGrids();\n this.#collisionDirty = false;\n const definition = this.definition;\n const size = this.cellSize;\n if (definition === null || size <= 0) {\n this.#collision = EMPTY_COLLISION;\n return;\n }\n this.#version += 1;\n this.#collision = mergeTileCollisions(\n (x: number, y: number): TileCollisionInfo => this.collisionAt(x, y),\n { cellSize: size, chunkSize: Math.max(1, this.chunkSize), width: definition.width, height: definition.height },\n this.#version,\n );\n this.#onCollisionChanged.emit();\n }\n}\n\n/** The cell size a tilemap with nothing loaded reports. */\nconst ZERO: Vec2Like = Object.freeze({ x: 0, y: 0 });\n\n/** The collision surface of a tilemap with nothing loaded. */\nconst EMPTY_COLLISION: TilemapCollisionData = Object.freeze({\n cellSize: 0,\n chunkSize: 0,\n chunks: Object.freeze([]),\n version: 0,\n});\n\n/** The answer for a cell that carries no collider. */\nconst NO_COLLISION: TileCollisionInfo = Object.freeze({\n shape: Object.freeze({ kind: \"none\" as const }),\n oneWay: false,\n properties: Object.freeze({}),\n});\n\n/**\n * Whether a cell is inside a layer.\n *\n * @param x - The column.\n * @param y - The row.\n * @param width - The layer width, in cells.\n * @param height - The layer height, in cells.\n * @returns `true` when the cell exists.\n */\nfunction inRange(x: number, y: number, width: number, height: number): boolean {\n return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < width && y < height;\n}\n\n/**\n * The `Tilemap` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction tilemapSchema(): Schema {\n return defineSchema({\n map: asset(TilemapAsset, { tooltip: \"The .tilemap.json document.\" }),\n chunkSize: u32(DEFAULT_CHUNK_SIZE, { min: 1, tooltip: \"How many cells one render and collision chunk spans.\" }),\n cellSizeOverride: f32(0, { min: 0, tooltip: \"Metres per cell, overriding the document's own; 0 uses it.\" }),\n });\n}\n","import { Vec2 } from \"@ignifx/core\";\nimport { Camera2D } from \"../camera/camera-2d.js\";\nimport { centreView, createSpriteScratch, updateSprite, writeScratch, writeView } from \"../lite/sprite-layer.js\";\nimport { pivotedPositionToRef, spriteRotationToLite, viewRotationToLite, worldToPixelsToRef } from \"../math/coords.js\";\nimport { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\nimport { TilemapRenderer } from \"../tilemap/tilemap-renderer.js\";\nimport { Tilemap } from \"../tilemap/tilemap.js\";\nimport type { SpriteLayerRegistry } from \"./layer-registry.js\";\nimport type { TwoDRuntime } from \"./runtime.js\";\nimport type { SpriteScratch } from \"../lite/sprite-layer.js\";\nimport type { MutableVec2, System, SystemContext, Vec2Like, World } from \"@ignifx/core\";\n\n/**\n * The 2D sync system (`docs/architecture/11-2d-toolkit.md` §2.2,\n * `01-lifecycle-and-time.md` §3): once per frame, in `PreRender`, it selects the active\n * `Camera2D`, writes every world layer's view, and pushes every sprite whose transform or fields\n * changed into its Lite layer.\n *\n * ## Ordering\n *\n * `docs/architecture/11-2d-toolkit.md` §2.2 asks for `PreRender` order `-400`, but\n * `@ignifx/audio`'s spatial pump already occupies that exact slot\n * (`AUDIO_PUMP_ORDER`, `docs/architecture/10-audio.md` §5). Equal orders are broken by\n * registration order, which makes the interleaving depend on the order a game lists its\n * extensions in. The two systems touch nothing in common, so the tie would be harmless — but a\n * frame order that changes with an argument list is not something to leave in place, so 2D takes\n * {@link TWO_D_SYNC_ORDER} instead: after physics interpolation at `-500` has written the frame's\n * final transforms, before audio at `-400`, and well before core's render sync at `900`.\n *\n * ## Cost\n *\n * A sprite that did not move and whose fields did not change costs one integer comparison\n * (`Transform.worldMatrixVersion`), and an entity marked `isStatic` costs that comparison only\n * until its first sync. That is what keeps a 100x100 tilemap at zero per-frame sync cost once its\n * chunks are up (spike S6.1).\n */\n\n/**\n * The `PreRender` order the 2D sync system runs at.\n *\n * @remarks\n * `-450`, not the `-400` `docs/architecture/11-2d-toolkit.md` §2.2 names, because audio's pump\n * already holds `-400`. See the module's own remarks.\n *\n * @public\n */\nexport const TWO_D_SYNC_ORDER = -450;\n\n/**\n * Writes sprites and camera views into Babylon Lite once per frame.\n *\n * @public\n */\nexport class TwoDSyncSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name = \"ignifx/2d-sync\";\n\n readonly #runtime: TwoDRuntime;\n\n readonly #scratch: SpriteScratch = createSpriteScratch();\n\n readonly #pixels: MutableVec2 = new Vec2();\n\n readonly #position: MutableVec2 = new Vec2();\n\n readonly #boundsMin: MutableVec2 = new Vec2();\n\n readonly #boundsMax: MutableVec2 = new Vec2();\n\n /** Sprites seen this frame, so the ones that vanished can be dropped. */\n readonly #seen = new Set<SpriteRenderer>();\n\n /** Sprites that were placed in a layer on a previous frame. */\n readonly #placed = new Set<SpriteRenderer>();\n\n /**\n * Builds the system. The extension does this; a game never constructs one.\n *\n * @param runtime - The 2D runtime state: settings, the layer registry, and the Lite renderer.\n *\n * @internal\n */\n constructor(runtime: TwoDRuntime) {\n this.#runtime = runtime;\n }\n\n /**\n * Runs one frame's synchronisation.\n *\n * @param ctx - The world, clock, phase, and delta.\n */\n update(ctx: SystemContext): void {\n this.#runtime.ensureRenderer();\n this.#runtime.collectEffects(ctx.world);\n const camera = selectCamera(ctx.world);\n this.#runtime.setMainCamera(camera);\n this.#syncSprites(ctx.world);\n this.#syncViews(camera);\n this.#syncTilemaps(ctx.world);\n this.#runtime.writeEffectParams();\n }\n\n /**\n * Connects the scene hook to a new world.\n *\n * @remarks\n * This is the only hook that fires for every world. `register` runs before the world exists and\n * `onStart` runs only when a game calls `app.start()`, so a headless tool that loads a scene\n * without ever starting a loop would otherwise never see its `settings.twoD` block.\n *\n * @param world - The new world.\n */\n onWorldCreated(world: World): void {\n this.#runtime.attachWorld(world);\n }\n\n /**\n * Drops every layer when the world goes away.\n *\n * @param _world - The world being disposed.\n */\n onWorldDisposed(_world: World): void {\n this.#runtime.detachWorld();\n this.#placed.clear();\n this.#seen.clear();\n }\n\n /**\n * Brings each `TilemapRenderer`'s materialised chunks in line with what the camera can see.\n *\n * @remarks\n * This runs **after** the views have been written, because the chunk window is derived from the\n * camera's visible bounds and those live on a layer's view. A frame where the camera did not move\n * and no tile changed builds nothing.\n *\n * @param world - The world to walk.\n */\n #syncTilemaps(world: World): void {\n const runtime = this.#runtime;\n const renderers = world.components(TilemapRenderer);\n if (renderers.length === 0) {\n return;\n }\n const bounds = runtime.cameraBounds();\n for (let index = 0; index < renderers.length; index += 1) {\n const renderer = renderers[index];\n if (renderer === undefined || !renderer.isEnabledInHierarchy) {\n continue;\n }\n const map = renderer.entity.getComponent(Tilemap);\n if (map === null) {\n continue;\n }\n renderer.sync(map, runtime.layers, bounds, runtime.pixelsPerUnit);\n }\n }\n\n /**\n * Reconciles every `SpriteRenderer` against its Lite layer.\n *\n * @param world - The world to walk.\n */\n #syncSprites(world: World): void {\n const registry = this.#runtime.layers;\n const pixelsPerUnit = this.#runtime.pixelsPerUnit;\n const sprites = world.components(SpriteRenderer);\n this.#seen.clear();\n let synced = 0;\n for (let index = 0; index < sprites.length; index += 1) {\n const sprite = sprites[index];\n if (sprite === undefined) {\n continue;\n }\n this.#seen.add(sprite);\n const atlas = sprite.atlas;\n if (atlas === null || atlas.lite.atlas === null) {\n // Still loading, failed, or headless: nothing to draw, and nothing to pay for.\n continue;\n }\n const entity = sprite.entity;\n const isStatic = entity.isStatic;\n const matrixVersion = entity.transform.worldMatrixVersion;\n const placement = sprite.placement();\n const key = layerKeyOf(sprite, atlas.address);\n if (placement !== null && placement.key !== key) {\n // The sorting layer, atlas, blend, or space changed: the sprite moves, handle and all.\n registry.remove(sprite);\n this.#placed.delete(sprite);\n sprite.invalidate();\n }\n if (sprite.placement() !== null && !sprite.needsSync(isStatic, matrixVersion)) {\n continue;\n }\n this.#writeSprite(sprite, atlas.frameCount, pixelsPerUnit);\n const current = sprite.placement();\n if (current === null) {\n registry.place(sprite, atlas, this.#scratch);\n this.#placed.add(sprite);\n const placed = sprite.placement();\n if (placed !== null) {\n registry.applyOrderInLayer(placed.key, placed.handle, sprite.orderInLayer);\n }\n } else {\n updateSprite(current.handle, this.#scratch);\n registry.applyOrderInLayer(current.key, current.handle, sprite.orderInLayer);\n }\n sprite.markSynced(\n isStatic,\n matrixVersion,\n this.#boundsMin.x,\n this.#boundsMin.y,\n this.#boundsMax.x,\n this.#boundsMax.y,\n );\n synced += 1;\n }\n this.#dropVanished(registry);\n this.#runtime.reportSynced(synced, sprites.length);\n }\n\n /**\n * Removes sprites whose components are gone from the world.\n *\n * @param registry - The layer registry.\n */\n #dropVanished(registry: SpriteLayerRegistry): void {\n if (this.#placed.size === 0) {\n return;\n }\n for (const sprite of this.#placed) {\n if (!this.#seen.has(sprite) || sprite.isDestroyed) {\n registry.remove(sprite);\n this.#placed.delete(sprite);\n }\n }\n }\n\n /**\n * Writes one sprite's props into the reusable scratch record, and its world AABB into the two\n * scratch vectors the caller reads back.\n *\n * @param sprite - The component.\n * @param frameCount - How many frames the atlas has, so an out-of-range frame draws frame 0.\n * @param pixelsPerUnit - The pixels one metre spans.\n */\n #writeSprite(sprite: SpriteRenderer, frameCount: number, pixelsPerUnit: number): void {\n const atlas = sprite.atlas;\n const frame = sprite.frame >= 0 && sprite.frame < frameCount ? sprite.frame : 0;\n const info = atlas?.frame(frame) ?? null;\n const frameWidth = info?.widthPx ?? 0;\n const frameHeight = info?.heightPx ?? 0;\n const transform = sprite.entity.transform;\n const matrix = transform.worldMatrix;\n // Read the world matrix directly: `position2D`, `rotation2D` and `localScale2D` all allocate,\n // and `rotation2D` is the *local* angle, not the world one (`transform.ts` 349).\n const worldX = matrix[12] ?? 0;\n const worldY = matrix[13] ?? 0;\n const scaleX = Math.hypot(matrix[0] ?? 1, matrix[1] ?? 0);\n const scaleY = Math.hypot(matrix[4] ?? 0, matrix[5] ?? 1);\n const rotationDegrees = Math.atan2(matrix[1] ?? 0, matrix[0] ?? 1) * RAD_TO_DEG;\n const rotation = spriteRotationToLite(rotationDegrees);\n const widthPx = frameWidth * scaleX;\n const heightPx = frameHeight * scaleY;\n const anchor = worldToPixelsToRef(worldX, worldY, pixelsPerUnit, this.#pixels);\n const pivot = sprite.pivotOverride ?? info?.pivot ?? CENTRE_PIVOT;\n const placed = pivotedPositionToRef(anchor.x, anchor.y, pivot, widthPx, heightPx, rotation, this.#position);\n const tint = sprite.color;\n writeScratch(\n this.#scratch,\n placed.x,\n placed.y,\n widthPx,\n heightPx,\n frame,\n rotation,\n tint.r,\n tint.g,\n tint.b,\n tint.a,\n sprite.flipX,\n sprite.flipY,\n sprite.isEnabledInHierarchy,\n );\n // The world AABB of the unrotated quad, which `SpriteRenderer.bounds` reports.\n const halfWidth = widthPx / (2 * pixelsPerUnit);\n const halfHeight = heightPx / (2 * pixelsPerUnit);\n const centreX = worldX + ((0.5 - pivot.x) * widthPx) / pixelsPerUnit;\n const centreY = worldY - ((0.5 - pivot.y) * heightPx) / pixelsPerUnit;\n this.#boundsMin.x = centreX - halfWidth;\n this.#boundsMin.y = centreY - halfHeight;\n this.#boundsMax.x = centreX + halfWidth;\n this.#boundsMax.y = centreY + halfHeight;\n }\n\n /**\n * Writes the camera's view onto every world layer, and the identity view onto screen-space ones.\n *\n * @param camera - The active camera, or `null`.\n */\n #syncViews(camera: Camera2D | null): void {\n const runtime = this.#runtime;\n const width = runtime.viewportWidthPx;\n const height = runtime.viewportHeightPx;\n if (camera === null) {\n runtime.layers.forEachLayer((layer): void => {\n writeView(layer.view, 0, 0, 1, 0);\n });\n return;\n }\n const transform = camera.entity.transform;\n const matrix = transform.worldMatrix;\n camera.resolve(matrix[12] ?? 0, matrix[13] ?? 0, width, height, runtime.pixelsPerUnit);\n const centre = worldToPixelsToRef(camera.centre.x, camera.centre.y, runtime.pixelsPerUnit, this.#pixels);\n const rotation = viewRotationToLite(Math.atan2(matrix[1] ?? 0, matrix[0] ?? 1) * RAD_TO_DEG);\n const zoom = camera.zoom;\n const centreX = centre.x;\n const centreY = centre.y;\n runtime.layers.forEachLayer((layer, screenSpace): void => {\n if (screenSpace) {\n writeView(layer.view, 0, 0, 1, 0);\n return;\n }\n centreView(layer.view, centreX, centreY, width, height, zoom, rotation);\n });\n runtime.applyParallax();\n }\n}\n\n/** Degrees per radian, so the sync loop does not import a constant it would only divide by. */\nconst RAD_TO_DEG = 180 / Math.PI;\n\n/** The pivot used when neither the component nor the frame declares one. */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * The layer key a sprite currently belongs to.\n *\n * @param sprite - The component.\n * @param atlasAddress - Its atlas's address.\n * @returns The key.\n */\nfunction layerKeyOf(sprite: SpriteRenderer, atlasAddress: string): string {\n return `${sprite.sortingLayer}|${atlasAddress}|${sprite.blend}|${sprite.screenSpace ? \"screen\" : \"world\"}`;\n}\n\n/**\n * Picks the camera the frame draws through: the highest-priority enabled `Camera2D`.\n *\n * @param world - The world to search.\n * @returns The camera, or `null` when the world has none enabled.\n *\n * @public\n */\nexport function selectCamera(world: World): Camera2D | null {\n const cameras = world.components(Camera2D);\n let best: Camera2D | null = null;\n for (let index = 0; index < cameras.length; index += 1) {\n const camera = cameras[index];\n if (camera === undefined || !camera.isEnabledInHierarchy) {\n continue;\n }\n if (best === null || camera.priority > best.priority) {\n best = camera;\n }\n }\n return best;\n}\n","import { Vec2 } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { pickSprite, screenToLayer, visibleBounds } from \"../lite/sprite-layer.js\";\nimport { pixelsToWorldToRef } from \"../math/coords.js\";\nimport type { SpriteLayerEntry } from \"./layer-registry.js\";\nimport type { TwoDLiteHandles, TwoDRuntime } from \"./runtime.js\";\nimport type { Camera2D } from \"../camera/camera-2d.js\";\nimport type { LiteBounds2D, LiteSprite2DLayer } from \"../lite/types.js\";\nimport type { TwoDMode, TwoDSettings } from \"../settings.js\";\nimport type { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\nimport type { Entity, MutableVec2, Vec2Like, World } from \"@ignifx/core\";\n\n/**\n * `app.twoD` (`docs/architecture/11-2d-toolkit.md` §1 and §5): the 2D toolkit's runtime surface.\n *\n * Everything a game reaches for that is not attached to an entity lives here — the pixels-per-unit\n * conversion, the camera the frame is drawn through, sprite picking, the tile-object factory\n * registry, the per-layer diagnostics, and the Lite escape hatch.\n */\n\n/**\n * What `app.twoD.pickAt` returns.\n *\n * @public\n */\nexport interface TwoDPick {\n /** The entity carrying the sprite that was hit. */\n readonly entity: Entity;\n /** The sprite component that was hit. */\n readonly component: SpriteRenderer;\n /** Where inside the sprite's quad the hit landed, in `[0, 1]`. */\n readonly u: number;\n /** Where inside the sprite's quad the hit landed, in `[0, 1]`. */\n readonly v: number;\n}\n\n/**\n * Builds the entities a tilemap's objects layer describes.\n *\n * @public\n */\nexport type TileObjectFactory = (context: TileObjectContext) => Entity | null;\n\n/**\n * What a {@link TileObjectFactory} is handed.\n *\n * @public\n */\nexport interface TileObjectContext {\n /** The world to create the entity in. */\n readonly world: World;\n /** The object's name, as the map wrote it. */\n readonly name: string;\n /** The object's type, which selected this factory. */\n readonly type: string;\n /** The object's bottom-left corner, in world metres relative to the tilemap entity. */\n readonly position: Vec2Like;\n /** The object's size, in world metres. */\n readonly size: Vec2Like;\n /** The object's custom properties. */\n readonly properties: Readonly<Record<string, string | number | boolean>>;\n /** The tilemap entity the object came from, so a factory can parent to it. */\n readonly tilemap: Entity;\n}\n\n/**\n * A caller-owned world-space box, so reading the camera's bounds allocates nothing.\n *\n * @public\n */\nexport interface WorldBox {\n /** The lower corner, in world metres. */\n readonly min: MutableVec2;\n /** The upper corner, in world metres. */\n readonly max: MutableVec2;\n}\n\n/**\n * The 2D service.\n *\n * @example\n * ```ts\n * const hit = app.twoD.pickAt(pointer.x, pointer.y);\n * if (hit !== null) {\n * hit.entity.destroy();\n * }\n * ```\n *\n * @public\n */\nexport class TwoDService {\n readonly #runtime: TwoDRuntime;\n\n readonly #factories = new Map<string, TileObjectFactory>();\n\n /** Reused by `pickAt`, so picking allocates nothing. */\n readonly #pickLayers: LiteSprite2DLayer[] = [];\n\n /** Reused by `visibleWorldBounds`. */\n readonly #bounds: LiteBounds2D = { minX: 0, minY: 0, maxX: 0, maxY: 0 };\n\n /** Reused by `pickAt`, so picking allocates nothing. */\n readonly #pickPoint = { x: 0, y: 0 };\n\n /** A one-element array reused by `pickAt`, because Lite's picker takes a list. */\n readonly #oneLayer: LiteSprite2DLayer[] = [];\n\n /**\n * Builds the service.\n *\n * @param runtime - The app's 2D runtime state.\n *\n * @internal\n */\n constructor(runtime: TwoDRuntime) {\n this.#runtime = runtime;\n }\n\n /**\n * How many pixels one world metre spans (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * @returns The conversion factor; `100` unless the project or a scene changed it.\n */\n get pixelsPerUnit(): number {\n return this.#runtime.pixelsPerUnit;\n }\n\n /**\n * Whether sprites are the whole frame or composite over the 3D scene.\n *\n * @returns The mode.\n */\n get mode(): TwoDMode {\n return this.#runtime.settings.mode;\n }\n\n /**\n * The resolved `twoD` settings, after any scene-file override.\n *\n * @returns The settings.\n */\n get settings(): TwoDSettings {\n return this.#runtime.settings;\n }\n\n /**\n * The camera the last frame was drawn through: the highest-priority enabled `Camera2D`.\n *\n * @returns The camera, or `null` when the world has none enabled.\n */\n get mainCamera(): Camera2D | null {\n return this.#runtime.mainCamera;\n }\n\n /**\n * The project's sorting layers, back to front.\n *\n * @returns The names.\n */\n get sortingLayers(): readonly string[] {\n return this.#runtime.sortingLayers.names;\n }\n\n /**\n * Every Lite sprite layer in draw order, for diagnostics and tests.\n *\n * @remarks\n * The snapshot is freshly allocated on each read; it is a debugging surface, not a per-frame one.\n *\n * @returns The layers.\n */\n get layers(): readonly SpriteLayerEntry[] {\n return this.#runtime.layers.describe();\n }\n\n /**\n * The Babylon Lite objects the toolkit owns. Unstable escape hatch\n * (`CONSTITUTION.md` §3.4).\n *\n * @returns The sprite rendering context, or `null` under a headless app or before the first frame.\n */\n get lite(): TwoDLiteHandles {\n return { renderer: this.#runtime.renderer };\n }\n\n /**\n * How many sprites the last frame actually wrote to Lite.\n *\n * @remarks\n * This is the number spike S6.1 watches: on a steady frame with a static tilemap it is the count\n * of sprites that genuinely moved, not the count that exist.\n *\n * @returns The count.\n */\n get syncedLastFrame(): number {\n return this.#runtime.syncedLastFrame;\n }\n\n /**\n * How many `SpriteRenderer` components the last frame walked.\n *\n * @returns The count.\n */\n get spriteCount(): number {\n return this.#runtime.spriteCount;\n }\n\n /**\n * Picks the topmost sprite under a viewport pixel (`docs/architecture/11-2d-toolkit.md` §5).\n *\n * @remarks\n * Picking is a CPU test against every world layer's instance data, in draw order — no GPU\n * readback and no frame of latency, which is what makes it usable from a click handler. It\n * resolves only `SpriteRenderer` components: a tilemap's tiles have no component, so use\n * `Tilemap.worldToCell` for those.\n *\n * @param xPx - The viewport x, in pixels from the left edge.\n * @param yPx - The viewport y, in pixels from the top edge.\n * @returns The hit, or `null` for a miss.\n */\n pickAt(xPx: number, yPx: number): TwoDPick | null {\n const layers = this.#runtime.layers.collectLayers(false, this.#pickLayers);\n // Front to back, one layer at a time: Lite's picker compares the point against each sprite's\n // stored `positionPx` without applying the view, so the point has to be unprojected through\n // *that* layer's view — and a world layer and a screen-space layer do not share one.\n for (let index = layers.length - 1; index >= 0; index -= 1) {\n const layer = layers[index];\n if (layer === undefined) {\n continue;\n }\n const point = screenToLayer(layer.view, xPx, yPx, this.#pickPoint);\n this.#oneLayer[0] = layer;\n const hit = pickSprite(this.#oneLayer, point.x, point.y);\n if (hit === null) {\n continue;\n }\n const component = this.#runtime.layers.componentAt(hit.layer, hit.spriteIndex);\n if (component !== null && component.pickable && !component.isDestroyed) {\n return { entity: component.entity, component, u: hit.u, v: hit.v };\n }\n }\n return null;\n }\n\n /**\n * The world-space rectangle the camera can currently see.\n *\n * @param out - The box to write: its `min` takes the lower corner and its `max` the upper.\n * @returns `true` when a camera and a layer existed to measure against.\n */\n visibleWorldBounds(out: WorldBox): boolean {\n const layers = this.#runtime.layers.collectLayers(true, this.#pickLayers);\n const first = layers[0];\n if (first === undefined) {\n return false;\n }\n visibleBounds(first.view, this.#runtime.viewportWidthPx, this.#runtime.viewportHeightPx, this.#bounds);\n const ppu = this.#runtime.pixelsPerUnit;\n // Layer pixels run +Y down, so the bounds' maxY is the world minimum.\n pixelsToWorldToRef(this.#bounds.minX, this.#bounds.maxY, ppu, out.min);\n pixelsToWorldToRef(this.#bounds.maxX, this.#bounds.minY, ppu, out.max);\n return true;\n }\n\n /**\n * Registers the factory that turns one kind of tilemap object into an entity\n * (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * @param type - The object `type` the map writes.\n * @param factory - Builds the entity, or returns `null` to spawn nothing.\n * @throws IgnifxError with code `IGX-1110` when a factory for the type is already registered.\n *\n * @example\n * ```ts\n * app.twoD.registerTileObjectFactory(\"spawn\", ({ world, position }) => {\n * const player = world.createEntity({ name: \"player\" });\n * player.transform.position2D = new Vec2(position.x, position.y);\n * return player;\n * });\n * ```\n */\n registerTileObjectFactory(type: string, factory: TileObjectFactory): void {\n if (this.#factories.has(type)) {\n throw twoDError(\n TwoDErrorCode.duplicateObjectFactory,\n `A tile object factory for ${type} is already registered.`,\n {\n context: { type },\n hint: \"Unregister the first one, or give the second object type its own name.\",\n },\n );\n }\n this.#factories.set(type, factory);\n }\n\n /**\n * Removes a tile-object factory.\n *\n * @param type - The object type.\n * @returns `true` when a factory was registered.\n */\n unregisterTileObjectFactory(type: string): boolean {\n return this.#factories.delete(type);\n }\n\n /**\n * The factory registered for an object type.\n *\n * @param type - The object type.\n * @returns The factory, or `null`.\n *\n * @internal\n */\n tileObjectFactory(type: string): TileObjectFactory | null {\n return this.#factories.get(type) ?? null;\n }\n\n /**\n * Converts a viewport pixel into a world point through the active camera.\n *\n * @param xPx - The viewport x.\n * @param yPx - The viewport y.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, or the origin when no camera is active.\n */\n screenToWorld(xPx: number, yPx: number, out: MutableVec2 = new Vec2()): MutableVec2 {\n const camera = this.#runtime.mainCamera;\n if (camera === null) {\n out.x = 0;\n out.y = 0;\n return out;\n }\n return camera.screenToWorld(xPx, yPx, out);\n }\n\n /**\n * Converts a world point into a viewport pixel through the active camera.\n *\n * @param point - The world point, in metres.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, or the origin when no camera is active.\n */\n worldToScreen(point: Vec2Like, out: MutableVec2 = new Vec2()): MutableVec2 {\n const camera = this.#runtime.mainCamera;\n if (camera === null) {\n out.x = 0;\n out.y = 0;\n return out;\n }\n return camera.worldToScreen(point, out);\n }\n}\n","import { bool, defineSchema, enumOf, f32, map } from \"@ignifx/core\";\nimport type { Schema } from \"@ignifx/core\";\n\n/**\n * The `twoD` project settings section (`docs/architecture/04-extensions.md` §5,\n * `11-2d-toolkit.md` §1 and §7). Everything here is what a game writes in `ignifx.config.ts` or in\n * a scene file's `settings.twoD` block; the knobs a game changes per frame live on `app.twoD` and\n * on `Camera2D` instead.\n */\n\n/**\n * The section name as it appears in `ignifx.config.ts` and in a scene file's `settings` block.\n *\n * @public\n */\nexport const TWO_D_SETTINGS_SECTION = \"twoD\";\n\n/**\n * Every rendering mode the 2D toolkit supports, in the order an inspector should list them\n * (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * @public\n */\nexport const TWO_D_MODES = [\"sprite\", \"mixed\"] as const;\n\n/**\n * How 2D composites with the 3D render scene.\n *\n * @remarks\n * `\"sprite\"` is a pure 2D game: sprites are the only thing drawn. `\"mixed\"` is 2.5D — the render\n * scene draws first and the sprite pass composites on top without clearing, so meshes and sprites\n * share a frame.\n *\n * @public\n */\nexport type TwoDMode = (typeof TWO_D_MODES)[number];\n\n/**\n * The resolved `twoD` settings section.\n *\n * @example\n * ```ts\n * // ignifx.config.ts\n * export default defineConfig({\n * sortingLayers: { sortingLayers: [\"Background\", \"Default\", \"Foreground\"] },\n * twoD: { mode: \"sprite\", pixelsPerUnit: 16, ySort: { Default: true } },\n * });\n * ```\n *\n * @public\n */\nexport interface TwoDSettings {\n /** Whether sprites are the whole frame (`\"sprite\"`) or composite over the 3D scene (`\"mixed\"`). */\n readonly mode: TwoDMode;\n /** How many pixels one world metre spans. Defaults to `100`. */\n readonly pixelsPerUnit: number;\n /**\n * Which sorting layers draw back-to-front by world Y rather than by `orderInLayer`. A layer the\n * record does not mention does not Y-sort.\n */\n readonly ySort: Readonly<Record<string, boolean>>;\n}\n\n/**\n * The values used for everything a project omits.\n *\n * @returns The default `twoD` section.\n *\n * @public\n */\nexport function defaultTwoDSettings(): TwoDSettings {\n return { mode: \"sprite\", pixelsPerUnit: 100, ySort: {} };\n}\n\n/**\n * The schema the `twoD` section is validated against, in `ignifx.config.ts` and in a scene file\n * alike.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function twoDSettingsSchema(): Schema {\n return defineSchema({\n mode: enumOf(TWO_D_MODES, \"sprite\"),\n pixelsPerUnit: f32(100, { min: Number.EPSILON }),\n ySort: map(bool(false)),\n });\n}\n","import { Tilemap } from \"./tilemap.js\";\nimport type { TwoDService } from \"../service/two-d-service.js\";\nimport type { App, Entity, SceneInstance } from \"@ignifx/core\";\n\n/**\n * Spawning the entities a tilemap's objects layer describes\n * (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * A map editor's objects layer is a list of *intentions* — \"a player starts here\", \"this rectangle\n * is a trigger\" — and only the game knows what each one becomes. `app.twoD.registerTileObjectFactory`\n * is where a game says so, and this module is what runs those factories when a scene carrying a\n * `Tilemap` finishes loading.\n *\n * Objects are spawned **once per scene load**, on `world.onSceneLoaded`, after `awake` and\n * `onEnable` have flushed (`world.ts` 596-597), so a factory can reach any component the scene\n * declared.\n */\n\n/**\n * Runs the registered factory for every object in every `Tilemap` in a scene.\n *\n * @remarks\n * An object whose `type` has no registered factory is skipped silently: a map routinely carries\n * markers a given game does not use, and refusing to load the scene over one would make maps and\n * code impossible to version independently. A factory that throws is reported to `app.onError`\n * and the remaining objects still spawn, which is the same containment the frame loop gives a\n * script callback.\n *\n * A `Tilemap` whose document has not finished loading spawns nothing now; the next scene load, or\n * an explicit {@link spawnTilemapObjects} call, does it.\n *\n * @param app - The app.\n * @param service - The 2D service holding the factory registry.\n * @param scene - The scene that just loaded.\n *\n * @internal\n */\nexport function spawnTileObjects(app: App, service: TwoDService, scene: SceneInstance): void {\n const tilemaps = app.world.components(Tilemap);\n for (let index = 0; index < tilemaps.length; index += 1) {\n const tilemap = tilemaps[index];\n if (tilemap === undefined || tilemap.entity.scene !== scene) {\n continue;\n }\n spawnTilemapObjects(app, service, tilemap);\n }\n}\n\n/**\n * Runs the registered factory for every object in one tilemap.\n *\n * @param app - The app.\n * @param service - The 2D service holding the factory registry.\n * @param tilemap - The tilemap whose objects layer to walk.\n * @returns The entities that were created, in document order.\n *\n * @example\n * ```ts\n * app.twoD.registerTileObjectFactory(\"spawn\", ({ world, position }) => {\n * const player = world.createEntity({ name: \"player\" });\n * player.transform.position2D = new Vec2(position.x, position.y);\n * return player;\n * });\n * ```\n *\n * @public\n */\nexport function spawnTilemapObjects(app: App, service: TwoDService, tilemap: Tilemap): readonly Entity[] {\n const definition = tilemap.definition;\n if (definition === null) {\n return EMPTY;\n }\n const matrix = tilemap.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n const spawned: Entity[] = [];\n for (let index = 0; index < definition.objects.length; index += 1) {\n const object = definition.objects[index];\n if (object === undefined) {\n continue;\n }\n const factory = service.tileObjectFactory(object.type);\n if (factory === null) {\n continue;\n }\n try {\n const entity = factory({\n world: app.world,\n name: object.name,\n type: object.type,\n position: { x: originX + object.x, y: originY + object.y },\n size: { x: object.width, y: object.height },\n properties: object.properties,\n tilemap: tilemap.entity,\n });\n if (entity !== null) {\n spawned.push(entity);\n }\n } catch (error: unknown) {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: tilemap.entity, component: tilemap });\n }\n }\n return spawned;\n}\n\n/** The result of spawning from a tilemap with nothing loaded. */\nconst EMPTY: readonly Entity[] = Object.freeze([]);\n","/**\n * The package's own version, reported as `Extension.version`\n * (`docs/architecture/04-extensions.md` §1). First-party packages ship one version line, so this\n * tracks `package.json` and the release tooling bumps both together.\n */\n\n/**\n * The `@ignifx/2d` version this build was cut from.\n *\n * @public\n */\nexport const VERSION = \"0.0.0\";\n","import { decodeProps, defineExtension, Phase } from \"@ignifx/core\";\nimport { TWO_D_ANIMATION_ORDER, TwoDAnimationSystem } from \"./animation/animation-system.js\";\nimport { createSpriteAnimationLoader } from \"./animation/loader.js\";\nimport { SpriteAnimator } from \"./animation/sprite-animator.js\";\nimport { createSpriteAtlasLoader } from \"./atlas/loader.js\";\nimport { defineTwoDAppProperty } from \"./augmentation.js\";\nimport { Camera2DFollow } from \"./camera/camera-2d-follow.js\";\nimport { Camera2D } from \"./camera/camera-2d.js\";\nimport { TWO_D_ERROR_MESSAGES } from \"./errors.js\";\nimport {\n attachLayer,\n createRegisteredSpriteRenderer,\n destroySpriteRenderer,\n detachLayer,\n enableSpriteDeviceLostRecovery,\n} from \"./lite/gpu/sprite-renderer.js\";\nimport { TwoDRuntime } from \"./service/runtime.js\";\nimport { TWO_D_SYNC_ORDER, TwoDSyncSystem } from \"./service/sync-system.js\";\nimport { TwoDService } from \"./service/two-d-service.js\";\nimport { defaultTwoDSettings, TWO_D_SETTINGS_SECTION, twoDSettingsSchema } from \"./settings.js\";\nimport { ParallaxLayer } from \"./sprite/parallax-layer.js\";\nimport { SpriteLayerEffect } from \"./sprite/sprite-layer-effect.js\";\nimport { SpriteRenderer } from \"./sprite/sprite-renderer.js\";\nimport { spawnTileObjects } from \"./tilemap/spawn-objects.js\";\nimport { createTilemapLoader } from \"./tilemap/tilemap-asset.js\";\nimport { TilemapRenderer } from \"./tilemap/tilemap-renderer.js\";\nimport { Tilemap } from \"./tilemap/tilemap.js\";\nimport { VERSION } from \"./version.js\";\nimport type { LiteSpriteRenderer } from \"./lite/types.js\";\nimport type { TwoDMode, TwoDSettings } from \"./settings.js\";\nimport type {\n App,\n Extension,\n ExtensionContext,\n JsonObject,\n JsonValue,\n SceneInstance,\n SortingLayersSettings,\n} from \"@ignifx/core\";\n\n/**\n * The `@ignifx/2d` extension (`docs/architecture/04-extensions.md` §1,\n * `11-2d-toolkit.md` §1). Registering it is the whole installation: `twoD()` gives a game\n * `app.twoD`, seven components, the `Camera2DFollow` script, three asset types, the `twoD` settings\n * section, and the two systems that drive sprites — the `PreRender` sync and the `PostUpdate`\n * animation clock.\n */\n\n/**\n * What `twoD()` accepts. Every field overrides the matching `twoD` settings section value.\n *\n * @public\n */\nexport interface TwoDOptions {\n /** Whether sprites are the whole frame (`\"sprite\"`) or composite over the 3D scene (`\"mixed\"`). */\n readonly mode?: TwoDMode;\n /** How many pixels one world metre spans. */\n readonly pixelsPerUnit?: number;\n /** Which sorting layers draw back-to-front by world Y. */\n readonly ySort?: Readonly<Record<string, boolean>>;\n}\n\n/**\n * Merges the extension's options over the resolved settings section.\n *\n * @param settings - The resolved `twoD` section.\n * @param options - What the game passed to `twoD(...)`.\n * @returns The effective settings.\n */\nfunction mergeSettings(settings: TwoDSettings, options: TwoDOptions): TwoDSettings {\n return {\n mode: options.mode ?? settings.mode,\n pixelsPerUnit: options.pixelsPerUnit ?? settings.pixelsPerUnit,\n ySort: options.ySort ?? settings.ySort,\n };\n}\n\n/**\n * The components the extension registers, in the order the API report lists them.\n *\n * @returns The classes.\n */\nfunction components(): readonly [\n typeof Camera2D,\n typeof SpriteRenderer,\n typeof SpriteAnimator,\n typeof Tilemap,\n typeof TilemapRenderer,\n typeof ParallaxLayer,\n typeof SpriteLayerEffect,\n typeof Camera2DFollow,\n] {\n return [\n Camera2D,\n SpriteRenderer,\n SpriteAnimator,\n Tilemap,\n TilemapRenderer,\n ParallaxLayer,\n SpriteLayerEffect,\n Camera2DFollow,\n ];\n}\n\n/**\n * Whether a JSON value is an object rather than an array, a primitive, or absent.\n *\n * @param value - The value read out of the scene file.\n * @returns `true` when the value can be decoded as a settings block.\n */\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads a scene file's `settings.twoD` block over the project's own settings.\n *\n * @remarks\n * `docs/architecture/11-2d-toolkit.md` §7 asks that a scene be able to override the mode, the PPU,\n * and the Y-sort table. `@ignifx/core` carries the block through to `SceneInstance.settings` as raw\n * JSON and fires `world.onSceneLoaded` once it is populated (`world.ts` 590 and 597) — but there is\n * no *validated* per-scene settings mechanism, no schema hook and no `IGX-0408` path, so the\n * extension validates its own block with `decodeProps` against the same schema\n * `registerSettings` uses. An invalid block is reported to `app.onError` and ignored rather than\n * taking the scene load down with it.\n *\n * @param app - The app.\n * @param runtime - The runtime whose settings the block replaces.\n * @param base - The settings the project resolved, which the block is applied over.\n * @param scene - The scene that just loaded.\n */\nfunction applySceneSettings(app: App, runtime: TwoDRuntime, base: TwoDSettings, scene: SceneInstance): void {\n const block = scene.settings?.[TWO_D_SETTINGS_SECTION];\n if (!isJsonObject(block)) {\n return;\n }\n const decoded = decodeProps(twoDSettingsSchema(), block, {\n entity: (): null => null,\n component: (): null => null,\n asset: (): null => null,\n });\n if (decoded.issues.length > 0) {\n app.onError.emit({\n error: new Error(`settings.twoD in ${scene.name} has ${String(decoded.issues.length)} invalid field(s)`),\n source: \"extension\",\n phase: null,\n entity: null,\n component: null,\n });\n return;\n }\n // `decodeProps` fills every absent field with its schema default, so an omitted key would\n // otherwise silently reset the project's value to 100 rather than leaving it alone. Only the\n // keys the block actually wrote may override.\n const value = decoded.value as Partial<TwoDSettings>;\n runtime.applySettings({\n mode: Object.hasOwn(block, \"mode\") && value.mode !== undefined ? value.mode : base.mode,\n pixelsPerUnit:\n Object.hasOwn(block, \"pixelsPerUnit\") && value.pixelsPerUnit !== undefined\n ? value.pixelsPerUnit\n : base.pixelsPerUnit,\n ySort: Object.hasOwn(block, \"ySort\") && value.ySort !== undefined ? value.ySort : base.ySort,\n });\n}\n\n/**\n * Registers everything the package contributes.\n *\n * @param ctx - The registration surface.\n * @param options - What the game passed to `twoD(...)`.\n */\nfunction registerTwoD(ctx: ExtensionContext, options: TwoDOptions): void {\n ctx.registerErrorCodes(TWO_D_ERROR_MESSAGES);\n ctx.registerSettings<TwoDSettings>(TWO_D_SETTINGS_SECTION, twoDSettingsSchema(), defaultTwoDSettings());\n const settings = mergeSettings(ctx.settings<TwoDSettings>(TWO_D_SETTINGS_SECTION), options);\n const app = ctx.app;\n const sorting = app.settings.section<SortingLayersSettings>(\"sortingLayers\").sortingLayers;\n const isHeadless = app.isHeadless;\n const runtime = new TwoDRuntime({\n app,\n settings,\n sortingLayers: sorting,\n createRenderer: isHeadless\n ? null\n : (): LiteSpriteRenderer =>\n // `clear: false` in \"mixed\" mode so the render scene's colour survives underneath\n // (`index.d.ts` 12222); in \"sprite\" mode the sprite pass owns the frame and clears it.\n createRegisteredSpriteRenderer(app.lite.engine, settings.mode === \"sprite\", BLACK),\n attachLayer,\n detachLayer,\n destroyRenderer: destroySpriteRenderer,\n });\n const service = new TwoDService(runtime);\n ctx.registerService(TwoDService, service);\n defineTwoDAppProperty(ctx, service);\n ctx.registerSystem(new TwoDSyncSystem(runtime), { phase: Phase.PreRender, order: TWO_D_SYNC_ORDER });\n ctx.registerSystem(new TwoDAnimationSystem(runtime), { phase: Phase.PostUpdate, order: TWO_D_ANIMATION_ORDER });\n ctx.registerAssetLoader(createSpriteAtlasLoader());\n ctx.registerAssetLoader(createSpriteAnimationLoader());\n ctx.registerAssetLoader(createTilemapLoader());\n ctx.registerComponents(components());\n runtime.setSceneHandler((scene: SceneInstance): void => {\n applySceneSettings(app, runtime, settings, scene);\n spawnTileObjects(app, service, scene);\n });\n ctx.onDispose((): void => {\n runtime.dispose();\n });\n}\n\n/** The clear colour a `\"sprite\"`-mode frame starts from. */\nconst BLACK = Object.freeze({ r: 0, g: 0, b: 0, a: 1 });\n\n/**\n * Turns on device-lost recovery.\n *\n * @remarks\n * Recovery is enabled here, in `onStart`, and **before any atlas or layer exists**, because Lite\n * requires it: *\"Enable this before creating or loading sprite textures so their recovery sources\n * are retained\"* (`index.d.ts` 4372). `onStart` runs after every extension registered and after\n * the engine exists, but before the first frame — the only window where both conditions hold.\n *\n * @param app - The app being started.\n */\nfunction startTwoD(app: App): void {\n if (!app.isHeadless && app.renderer.features.deviceLostRecovery) {\n enableSpriteDeviceLostRecovery(\n app.lite.engine,\n (): void => {\n app.log.info(\"2D sprite resources recovered after device loss.\");\n },\n (error: unknown): void => {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: null, component: null });\n },\n );\n }\n}\n\n/**\n * The `@ignifx/2d` extension factory.\n *\n * @param options - Overrides for the `twoD` settings section.\n * @returns The extension descriptor to pass to `createApp`.\n *\n * @example\n * ```ts\n * const app = await createApp({\n * canvas,\n * extensions: [twoD({ pixelsPerUnit: 16, ySort: { Default: true } })],\n * });\n * ```\n *\n * @public\n */\nexport const twoD: (options?: TwoDOptions) => Extension = defineExtension<TwoDOptions | undefined>((raw) => {\n // `defineExtension` hands the factory whatever the caller passed, which is `undefined` when the\n // game wrote `twoD()`; the typed signature cannot express that, so the default lands here.\n const options: TwoDOptions = raw ?? {};\n return {\n name: \"@ignifx/2d\",\n version: VERSION,\n engine: \">=0.0.0 <1.0.0\",\n requires: [\"@ignifx/core\"],\n register(ctx: ExtensionContext): void {\n registerTwoD(ctx, options);\n },\n onStart(app: App): void {\n startTwoD(app);\n },\n };\n});\n","import { array, bool, defineSchema, enumOf, f32, i32, map, record, str, u32, vec2 } from \"@ignifx/core\";\nimport { SPRITE_ANIMATION_FORMAT, SPRITE_ANIMATION_FORMAT_VERSION } from \"./animation/definition.js\";\nimport { SPRITE_ATLAS_FORMAT, SPRITE_ATLAS_FORMAT_VERSION } from \"./atlas/definition.js\";\nimport { TILEMAP_FORMAT, TILEMAP_FORMAT_VERSION } from \"./tilemap/definition.js\";\nimport type { Schema } from \"@ignifx/core\";\n\n/**\n * Declarative schemas for the three file formats `@ignifx/2d` reads\n * (`docs/architecture/06-serialization-and-scene-format.md` §6).\n *\n * These exist for **documentation and tooling**, not for the loaders: a loader validates with its\n * own `defineX` function, which produces an actionable `IGX-11##` message naming the offending\n * frame or clip. The schema here is what `pnpm docs:schemas` renders into\n * `skills/ignifx/references/formats/`, and what a JSON Schema for an editor is generated from.\n *\n * The two descriptions are deliberately kept in one package so they cannot drift apart in a\n * release; a test asserts that a fixture accepted by the loader also validates against the schema.\n */\n\n/**\n * The `ignifx.spriteatlas` document schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function spriteAtlasFileSchema(): Schema {\n return defineSchema({\n format: str(SPRITE_ATLAS_FORMAT, { tooltip: \"Always ignifx.spriteatlas.\" }),\n formatVersion: u32(SPRITE_ATLAS_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n image: str(\"\", { tooltip: \"The image address, relative to this document.\" }),\n sampling: enumOf([\"linear\", \"nearest\"] as const, \"linear\", { tooltip: \"Min/mag filter; nearest for pixel art.\" }),\n premultipliedAlpha: bool(false, { tooltip: \"Whether the image's RGB is already multiplied by its alpha.\" }),\n frames: array(\n record({\n name: str(\"\", { tooltip: \"The frame's name; what #frame: addresses.\" }),\n x: f32(0, { min: 0, tooltip: \"The left edge, in image pixels.\" }),\n y: f32(0, { min: 0, tooltip: \"The top edge, in image pixels.\" }),\n w: f32(0, { min: 0, tooltip: \"The width, in image pixels.\" }),\n h: f32(0, { min: 0, tooltip: \"The height, in image pixels.\" }),\n pivot: vec2({ x: 0.5, y: 0.5 }, { tooltip: \"Pivot in [0,1] of the frame; [0,0] is top-left.\" }),\n sourceSize: vec2({ x: 0, y: 0 }, { tooltip: \"The untrimmed size, when the packer trimmed the frame.\" }),\n }),\n [],\n {\n tooltip:\n \"The frames, in the order they are indexed. Each is a record of \" +\n \"name (str, what #frame: addresses), x/y (f32, the top-left corner in image pixels), \" +\n \"w/h (f32, the size in image pixels), pivot (vec2 in [0,1] of the frame; [0,0] is top-left) \" +\n \"and sourceSize (vec2, the untrimmed size when the packer trimmed the frame).\",\n },\n ),\n });\n}\n\n/**\n * The `ignifx.spriteanimation` document schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function spriteAnimationFileSchema(): Schema {\n return defineSchema({\n format: str(SPRITE_ANIMATION_FORMAT, { tooltip: \"Always ignifx.spriteanimation.\" }),\n formatVersion: u32(SPRITE_ANIMATION_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n atlas: str(\"\", { tooltip: \"The .atlas.json address, relative to this document.\" }),\n clips: array(\n record({\n name: str(\"\", { tooltip: \"The clip's name; what SpriteAnimator.play takes.\" }),\n frames: array(str(), [], {\n tooltip: \"Atlas frame names, in play order; they need not be adjacent in the atlas.\",\n }),\n from: str(\"\", {\n tooltip:\n \"The atlas frame whose INDEX starts the range, when frames is empty. \" +\n \"Every atlas index between from and to is played, so the two must bracket a contiguous run.\",\n }),\n to: str(\"\", {\n tooltip: \"The atlas frame whose INDEX ends the range, inclusive; an index below from plays it backwards.\",\n }),\n fps: f32(12, { min: Number.EPSILON, tooltip: \"Frames per second.\" }),\n loop: bool(true, { tooltip: \"Whether the clip restarts at its end.\" }),\n events: array(\n record({\n frame: u32(0, { tooltip: \"The zero-based index within the clip, not the atlas.\" }),\n name: str(\"\", { tooltip: \"The name emitted on SpriteAnimator.onEvent.\" }),\n }),\n [],\n { tooltip: \"Events fired as the clip passes a frame.\" },\n ),\n }),\n [],\n {\n tooltip:\n \"The clips; the first is the default. Each is a record of \" +\n \"name (str, what SpriteAnimator.play takes), \" +\n \"frames (array of atlas frame names in play order, which need not be adjacent), \" +\n \"from/to (str: an INCLUSIVE range over atlas INDICES used when frames is empty — every index \" +\n \"between the two endpoints is played, in atlas order, so a range over non-adjacent frames plays \" +\n \"everything in between; to before from plays it backwards), \" +\n \"fps (f32, default 12), loop (bool, default true) and \" +\n \"events (array of { frame: u32 index within the clip, not the atlas; name: str }).\",\n },\n ),\n });\n}\n\n/**\n * The `ignifx.tilemap` document schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function tilemapFileSchema(): Schema {\n return defineSchema({\n format: str(TILEMAP_FORMAT, { tooltip: \"Always ignifx.tilemap.\" }),\n formatVersion: u32(TILEMAP_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n tileWidth: f32(32, { min: Number.EPSILON, tooltip: \"One cell's width, in pixels.\" }),\n tileHeight: f32(32, { min: Number.EPSILON, tooltip: \"One cell's height, in pixels.\" }),\n cellSize: f32(0.32, { min: Number.EPSILON, tooltip: \"One cell's size, in world metres.\" }),\n width: u32(0, { tooltip: \"The map's width, in cells.\" }),\n height: u32(0, { tooltip: \"The map's height, in cells.\" }),\n tilesets: array(\n record({\n name: str(\"\", { tooltip: \"The tileset's name; the frame-name prefix.\" }),\n atlas: str(\"\", { tooltip: \"The .atlas.json address; empty means collision-only.\" }),\n firstId: u32(1, { min: 1, tooltip: \"The global id of this tileset's first tile.\" }),\n }),\n [],\n { tooltip: \"The tilesets, ascending by firstId.\" },\n ),\n layers: array(\n record({\n name: str(\"\", { tooltip: \"The layer's name.\" }),\n sortingLayer: str(\"Default\", { tooltip: \"Which sorting layer the tiles draw on.\" }),\n orderInLayer: i32(0, { tooltip: \"Sub-order within the sorting layer.\" }),\n opacity: f32(1, { min: 0, max: 1, tooltip: \"The layer's alpha.\" }),\n parallax: vec2({ x: 1, y: 1 }, { tooltip: \"Fraction of the camera's motion the layer follows.\" }),\n collision: bool(false, { tooltip: \"Whether this layer's tiles contribute colliders.\" }),\n width: u32(0, { tooltip: \"The layer's width, in cells.\" }),\n height: u32(0, { tooltip: \"The layer's height, in cells.\" }),\n tiles: array(u32(), [], { tooltip: \"Tile ids, row-major, top row first; 0 is empty.\" }),\n }),\n [],\n { tooltip: \"The tile layers, back to front.\" },\n ),\n objects: array(\n record({\n name: str(\"\", { tooltip: \"The object's name.\" }),\n type: str(\"\", { tooltip: \"The object's type; what selects a TileObjectFactory.\" }),\n x: f32(0, { tooltip: \"The bottom-left corner, in world metres.\" }),\n y: f32(0, { tooltip: \"The bottom-left corner, in world metres.\" }),\n width: f32(0, { min: 0, tooltip: \"The width, in world metres.\" }),\n height: f32(0, { min: 0, tooltip: \"The height, in world metres.\" }),\n }),\n [],\n { tooltip: \"The objects layer.\" },\n ),\n properties: map(str(), { tooltip: \"The map's custom properties.\" }),\n });\n}\n","import { describeSchema, toJsonSchema } from \"@ignifx/core\";\nimport { SPRITE_ANIMATION_FORMAT } from \"./animation/definition.js\";\nimport { SpriteAnimator } from \"./animation/sprite-animator.js\";\nimport { SPRITE_ATLAS_FORMAT } from \"./atlas/definition.js\";\nimport { Camera2D } from \"./camera/camera-2d.js\";\nimport { spriteAtlasFileSchema, spriteAnimationFileSchema, tilemapFileSchema } from \"./file-schemas.js\";\nimport { ParallaxLayer } from \"./sprite/parallax-layer.js\";\nimport { SpriteLayerEffect } from \"./sprite/sprite-layer-effect.js\";\nimport { SpriteRenderer } from \"./sprite/sprite-renderer.js\";\nimport { TILEMAP_FORMAT } from \"./tilemap/definition.js\";\nimport { TilemapRenderer } from \"./tilemap/tilemap-renderer.js\";\nimport { Tilemap } from \"./tilemap/tilemap.js\";\nimport type { JsonSchemaObject, SchemaDescription } from \"@ignifx/core\";\n\n/**\n * The documentation harness's view of everything `@ignifx/2d` declares\n * (`scripts/README.md`, \"Schema discovery convention\";\n * `docs/architecture/16-docs-harness-and-skill.md` §3).\n *\n * The **function** form is what a package uses rather than a `schemas` object, because building the\n * record means calling `describeSchema` and module scope holds declarations only\n * (`CONSTITUTION.md` §3.5).\n */\n\n/**\n * Describes the `ignifx.spriteatlas` file format.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeSpriteAtlasFormat(): SchemaDescription {\n return describeSchema(\"ignifx/spriteatlas-file\", spriteAtlasFileSchema(), {\n title: \"Sprite atlas\",\n format: SPRITE_ATLAS_FORMAT,\n description: \"An image plus the frame rectangles inside it, in pixels with a top-left origin.\",\n });\n}\n\n/**\n * Describes the `ignifx.spriteanimation` file format.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeSpriteAnimationFormat(): SchemaDescription {\n return describeSchema(\"ignifx/spriteanimation-file\", spriteAnimationFileSchema(), {\n title: \"Sprite animation\",\n format: SPRITE_ANIMATION_FORMAT,\n description:\n \"Clips of atlas frames with a rate, a loop flag, and frame events. A clip names its frames \" +\n \"either as an explicit `frames` list of atlas frame names, played in the order written and \" +\n \"free to skip around the sheet, or as a `from`/`to` pair — and that pair is an **inclusive \" +\n \"range over atlas indices**, not two endpoints joined by name: every index between the two is \" +\n \"played, in atlas order, so a range whose endpoints are not adjacent in the sheet plays \" +\n \"whatever the packer put between them. Use `frames` for a run that is not contiguous.\",\n });\n}\n\n/**\n * Describes the `ignifx.tilemap` file format.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeTilemapFormat(): SchemaDescription {\n return describeSchema(\"ignifx/tilemap-file\", tilemapFileSchema(), {\n title: \"Tilemap\",\n format: TILEMAP_FORMAT,\n description: \"Tile size, layers of tile ids, tilesets with colliders, and an objects layer.\",\n });\n}\n\n/**\n * The JSON Schema a tool validates a `.atlas.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function spriteAtlasJsonSchema(): JsonSchemaObject {\n return toJsonSchema(spriteAtlasFileSchema());\n}\n\n/**\n * The JSON Schema a tool validates a `.spriteanim.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function spriteAnimationJsonSchema(): JsonSchemaObject {\n return toJsonSchema(spriteAnimationFileSchema());\n}\n\n/**\n * The JSON Schema a tool validates a `.tilemap.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function tilemapJsonSchema(): JsonSchemaObject {\n return toJsonSchema(tilemapFileSchema());\n}\n\n/**\n * Describes every component and file format this package declares, for the documentation harness.\n *\n * @returns The records, keyed by namespaced type id.\n *\n * @example\n * ```ts\n * describeTwoDSchemas()[\"ignifx/Camera2D\"].fields[\"orthographicSize\"].default; // 5\n * ```\n *\n * @public\n */\nexport function describeTwoDSchemas(): Readonly<Record<string, SchemaDescription>> {\n return {\n \"ignifx/Camera2D\": describeSchema(\"ignifx/Camera2D\", Camera2D.schema, {\n description: \"The 2D camera: orthographic size in metres, pixel-perfect snapping, bounds, and follow fields.\",\n }),\n \"ignifx/SpriteRenderer\": describeSchema(\"ignifx/SpriteRenderer\", SpriteRenderer.schema, {\n description: \"One sprite drawn from one frame of one atlas, on one sorting layer.\",\n }),\n \"ignifx/SpriteAnimator\": describeSchema(\"ignifx/SpriteAnimator\", SpriteAnimator.schema, {\n description: \"Plays a clip of atlas frames on ignifx's clock, respecting timeScale and pause.\",\n }),\n \"ignifx/Tilemap\": describeSchema(\"ignifx/Tilemap\", Tilemap.schema, {\n description: \"A grid of tile ids with cell arithmetic and merged collision geometry.\",\n }),\n \"ignifx/TilemapRenderer\": describeSchema(\"ignifx/TilemapRenderer\", TilemapRenderer.schema, {\n description: \"Draws a Tilemap's cells as sprites, materialising only the chunks the camera sees.\",\n }),\n \"ignifx/ParallaxLayer\": describeSchema(\"ignifx/ParallaxLayer\", ParallaxLayer.schema, {\n description: \"Scrolls one sorting layer at a fraction of the camera's speed.\",\n }),\n \"ignifx/SpriteLayerEffect\": describeSchema(\"ignifx/SpriteLayerEffect\", SpriteLayerEffect.schema, {\n description: \"A per-layer WGSL fragment effect with an fx.params vec4.\",\n }),\n \"ignifx/spriteatlas-file\": describeSpriteAtlasFormat(),\n \"ignifx/spriteanimation-file\": describeSpriteAnimationFormat(),\n \"ignifx/tilemap-file\": describeTilemapFormat(),\n };\n}\n\n/**\n * The name `pnpm docs:schemas` discovers this package's schemas under.\n *\n * @returns The same records {@link describeTwoDSchemas} returns.\n *\n * @public\n */\nexport function describeSchemas(): Readonly<Record<string, SchemaDescription>> {\n return describeTwoDSchemas();\n}\n","import { twoDError, TwoDErrorCode } from \"../../errors.js\";\nimport { DEFAULT_PIXELS_PER_UNIT } from \"../../math/coords.js\";\nimport { defineTilemap } from \"../definition.js\";\nimport type {\n TileColliderDefinition,\n TileDefinition,\n TilemapDefinition,\n TilemapLayerInput,\n TilemapObjectDefinition,\n TilesetDefinition,\n} from \"../definition.js\";\n\n/**\n * The **LDtk** importer: turns an `.ldtk` project into an `ignifx.tilemap` document for one of its\n * levels (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * Like the Tiled importer this is a pure function over parsed JSON. LDtk models a *project* of many\n * levels where ignifx models one map, so the importer picks a single level — by identifier, or the\n * first one — and flattens it.\n */\n\n/**\n * A parallax multiplier pair, structurally the `Vec2Like` the tilemap format stores. Declaring it\n * here rather than importing `Vec2Like` keeps this module's type imports to a single specifier,\n * which is the shape the formatter and the import-order rule agree on.\n */\ninterface ParallaxFactor {\n /** The horizontal multiplier; `1` moves with the camera. */\n readonly x: number;\n /** The vertical multiplier; `1` moves with the camera. */\n readonly y: number;\n}\n\n/** The name reported in `IGX-1109` context so a developer knows which importer complained. */\nconst IMPORTER_NAME = \"ldtk\";\n\n/** The layer types this importer understands; anything else is an `IGX-1109`. */\nconst SUPPORTED_LAYER_TYPES: readonly string[] = Object.freeze([\"Tiles\", \"IntGrid\", \"Entities\"]);\n\n/**\n * The name given to the synthetic tileset that carries IntGrid colliders.\n *\n * @public\n */\nexport const LDTK_INTGRID_TILESET_NAME = \"intgrid\";\n\n/**\n * The default meaning of an LDtk IntGrid value, in cell-normalised top-left-origin units.\n *\n * @remarks\n * `1` is \"solid\" — the whole cell collides. `2` is \"one-way\" — the top quarter of the cell collides,\n * and only from above. Those two conventions cover the LDtk projects people actually ship, and\n * anything else is project-specific, so {@link LdtkImportOptions.intGridColliders} replaces this\n * table wholesale. An IntGrid value with no entry still gets a tile id and a frame; it simply does\n * not collide.\n *\n * @public\n */\nexport const LDTK_DEFAULT_INTGRID_COLLIDERS: Readonly<Record<number, TileColliderDefinition>> = Object.freeze({\n 1: { kind: \"box\", x: 0, y: 0, width: 1, height: 1 },\n 2: { kind: \"box\", x: 0, y: 0, width: 1, height: 0.25, oneWay: true },\n});\n\n/**\n * How {@link importLdtkLevel} maps LDtk's conventions onto ignifx's.\n *\n * @public\n */\nexport interface LdtkImportOptions {\n /** The pixels one world metre spans. Defaults to `100`, matching `twoD.pixelsPerUnit`. */\n readonly pixelsPerUnit?: number;\n /** The `identifier` of the level to import. Defaults to the project's first level. */\n readonly level?: string;\n /** The sorting layer every layer lands in. Defaults to `\"Default\"`. */\n readonly sortingLayer?: string;\n /**\n * Maps an LDtk tileset's `relPath` onto the address of the ignifx `.atlas.json` generated from it.\n * Defaults to swapping the file extension for `.atlas.json`.\n */\n readonly atlasFor?: (relPath: string) => string;\n /** Replaces {@link LDTK_DEFAULT_INTGRID_COLLIDERS} for this import. */\n readonly intGridColliders?: Readonly<Record<number, TileColliderDefinition>>;\n}\n\n/**\n * Imports one level of an LDtk project.\n *\n * @remarks\n * Three LDtk conventions need translating, and each is a place a naive importer goes wrong:\n *\n * - **Layer order is reversed.** LDtk stores `layerInstances` front-to-back — index `0` is the\n * layer drawn on *top*. ignifx layers are back-to-front, so the list is reversed and\n * `orderInLayer` follows the reversed index.\n * - **Tile layers are sparse.** `gridTiles` is a list of `{ px, t }` placements, not a grid; the\n * importer expands it into the dense `__cWid * __cHei` array the tilemap format wants, filling\n * the gaps with `0`. `t` is a tile index *within its tileset*, so the global id is\n * `tileset.firstId + t`. A layer's `pxOffsetX`/`pxOffsetY` shift the grid; a dense grid has no\n * sub-cell placement, so the offset is rounded to whole cells.\n * - **IntGrid layers are collision, not art.** An `intGridCsv` becomes a layer with\n * `collision: true` whose ids point into a synthetic, art-less tileset named\n * {@link LDTK_INTGRID_TILESET_NAME}; see {@link LDTK_DEFAULT_INTGRID_COLLIDERS} for the value\n * mapping and {@link LdtkImportOptions.intGridColliders} for overriding it.\n *\n * A tileset's `customData` entries are read as JSON, and an entry that parses to an object with\n * `solid: true` gives its tile a full-cell box collider. Data that is not JSON, or that says\n * something else, is ignored rather than treated as an error — `customData` is a free-form field\n * and other tools put other things in it.\n *\n * Per-tile flips (`gridTiles[].f`) are dropped, as they are in the Tiled importer: the tilemap\n * format has no per-cell flip yet.\n *\n * @param ldtk - The parsed `.ldtk` project.\n * @param options - The level to pick, pixels-per-unit, the sorting layer, and the mappings.\n * @returns The `ignifx.tilemap` document for that level.\n * @throws IgnifxError with code `IGX-1109` when the project has no levels, when\n * {@link LdtkImportOptions.level} names a level that is not there, or when a layer's type is not\n * `Tiles`, `IntGrid` or `Entities`; and `IGX-1105` when what it decodes to is not a valid tilemap.\n *\n * @example\n * ```ts\n * const map = importLdtkLevel(JSON.parse(await readFile(\"world.ldtk\", \"utf8\")), { level: \"Cave\" });\n * ```\n *\n * @public\n */\nexport function importLdtkLevel(ldtk: unknown, options: LdtkImportOptions = {}): TilemapDefinition {\n const fail = (reason: string): never => {\n throw twoDError(TwoDErrorCode.unsupportedImport, `The LDtk importer cannot read this document: ${reason}.`, {\n context: { importer: IMPORTER_NAME, reason },\n hint: \"Re-save the project from LDtk 1.5 or later with the default (single-file) JSON layout.\",\n });\n };\n if (!isRecord(ldtk)) {\n return fail(\"it is not a JSON object\");\n }\n const levels = readArray(ldtk, \"levels\");\n if (levels.length === 0) {\n return fail(\"the project declares no levels\");\n }\n const wanted = options.level;\n const level = wanted === undefined ? firstRecord(levels) : findLevel(levels, wanted);\n if (level === null) {\n return fail(wanted === undefined ? \"its first level is not an object\" : `it declares no level named ${wanted}`);\n }\n\n const pixelsPerUnit = options.pixelsPerUnit ?? DEFAULT_PIXELS_PER_UNIT;\n const sortingLayer = options.sortingLayer ?? \"Default\";\n const atlasFor = options.atlasFor ?? defaultAtlasFor;\n const intGridColliders = options.intGridColliders ?? LDTK_DEFAULT_INTGRID_COLLIDERS;\n const defs = isRecord(ldtk[\"defs\"]) ? ldtk[\"defs\"] : null;\n const layerDefs = defs === null ? [] : readArray(defs, \"layers\");\n\n // LDtk stores layers front-to-back; ignifx draws index 0 first, so the list is reversed once here\n // and every downstream index — including `orderInLayer` — is in ignifx order.\n const instances: Readonly<Record<string, unknown>>[] = [];\n const rawInstances = readArray(level, \"layerInstances\");\n for (let index = rawInstances.length - 1; index >= 0; index -= 1) {\n const instance = rawInstances[index];\n if (isRecord(instance)) {\n const type = readString(instance, \"__type\", \"\");\n if (!SUPPORTED_LAYER_TYPES.includes(type)) {\n return fail(`layer ${readString(instance, \"__identifier\", \"?\")} has the unsupported type ${type}`);\n }\n instances.push(instance);\n }\n }\n\n const gridSize = resolveGridSize(instances, ldtk);\n const levelWidthPx = readNumber(level, \"pxWid\", 0);\n const levelHeightPx = readNumber(level, \"pxHei\", 0);\n const width = Math.max(1, Math.round(levelWidthPx / gridSize));\n const height = Math.max(1, Math.round(levelHeightPx / gridSize));\n\n const tilesets: TilesetDefinition[] = [];\n const tilesetsByUid = new Map<number, TilesetDefinition>();\n let nextFirstId = 1;\n const rawTilesets = defs === null ? [] : readArray(defs, \"tilesets\");\n for (let index = 0; index < rawTilesets.length; index += 1) {\n const raw = rawTilesets[index];\n if (!isRecord(raw)) {\n continue;\n }\n const tileset = readTileset(raw, nextFirstId, atlasFor);\n nextFirstId += tileset.tiles.length;\n tilesets.push(tileset);\n tilesetsByUid.set(readNumber(raw, \"uid\", -1), tileset);\n }\n\n const intGridTileset = buildIntGridTileset(instances, nextFirstId, intGridColliders);\n if (intGridTileset !== null) {\n tilesets.push(intGridTileset);\n }\n\n const layers: TilemapLayerInput[] = [];\n const objects: TilemapObjectDefinition[] = [];\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance === undefined) {\n continue;\n }\n const type = readString(instance, \"__type\", \"\");\n if (type === \"Entities\") {\n readEntities(instance, levelHeightPx, pixelsPerUnit, objects);\n continue;\n }\n const parallax = readParallax(layerDefs, readNumber(instance, \"layerDefUid\", -1));\n if (type === \"IntGrid\" && intGridTileset !== null) {\n layers.push(readIntGridLayer(instance, layers.length, sortingLayer, parallax, intGridTileset.firstId));\n continue;\n }\n if (type === \"Tiles\") {\n const tileset = tilesetsByUid.get(readNumber(instance, \"__tilesetDefUid\", -1)) ?? null;\n layers.push(readTilesLayer(instance, layers.length, sortingLayer, parallax, tileset));\n }\n }\n\n return defineTilemap(\n {\n tileWidth: gridSize,\n tileHeight: gridSize,\n cellSize: gridSize / pixelsPerUnit,\n width,\n height,\n tilesets,\n layers,\n objects,\n properties: fieldInstancesToRecord(level[\"fieldInstances\"]),\n },\n \"<ldtk>\",\n );\n}\n\n/**\n * Flattens LDtk's `[{ __identifier, __type, __value }]` field instances into a plain record.\n *\n * @remarks\n * Only `string`, `number` and `boolean` values survive. LDtk's richer field types — points, entity\n * references, arrays, enum tuples — have no equivalent in the tilemap format's flat property record\n * and are dropped rather than stringified.\n *\n * @param fields - The value of a `fieldInstances` field, or anything else.\n * @returns The flattened record; empty when `fields` is not a field-instance array.\n *\n * @example\n * ```ts\n * fieldInstancesToRecord([{ __identifier: \"facing\", __type: \"String\", __value: \"left\" }]);\n * // { facing: \"left\" }\n * ```\n *\n * @public\n */\nexport function fieldInstancesToRecord(fields: unknown): Readonly<Record<string, string | number | boolean>> {\n if (!isUnknownArray(fields)) {\n return {};\n }\n const out: Record<string, string | number | boolean> = {};\n for (let index = 0; index < fields.length; index += 1) {\n const field = fields[index];\n if (!isRecord(field)) {\n continue;\n }\n const name = field[\"__identifier\"];\n const value = field[\"__value\"];\n if (typeof name !== \"string\" || name === \"\") {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[name] = value;\n }\n }\n return out;\n}\n\n/**\n * Swaps a file extension for `.atlas.json`, the default {@link LdtkImportOptions.atlasFor}.\n *\n * @param relPath - The image path the editor recorded.\n * @returns The atlas address.\n */\nfunction defaultAtlasFor(relPath: string): string {\n const slash = Math.max(relPath.lastIndexOf(\"/\"), relPath.lastIndexOf(\"\\\\\"));\n const dot = relPath.lastIndexOf(\".\");\n return dot > slash ? `${relPath.slice(0, dot)}.atlas.json` : `${relPath}.atlas.json`;\n}\n\n/**\n * The first entry of a list that is an object.\n *\n * @param values - The parsed list.\n * @returns The first object, or `null`.\n */\nfunction firstRecord(values: readonly unknown[]): Readonly<Record<string, unknown>> | null {\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index];\n if (isRecord(value)) {\n return value;\n }\n }\n return null;\n}\n\n/**\n * Finds a level by its `identifier`.\n *\n * @param levels - The project's levels.\n * @param identifier - The level name to match.\n * @returns The level, or `null` when the project has no such level.\n */\nfunction findLevel(levels: readonly unknown[], identifier: string): Readonly<Record<string, unknown>> | null {\n for (let index = 0; index < levels.length; index += 1) {\n const level = levels[index];\n if (isRecord(level) && readString(level, \"identifier\", \"\") === identifier) {\n return level;\n }\n }\n return null;\n}\n\n/**\n * Picks the cell size of the level: the first layer's `__gridSize`, else the project default.\n *\n * @param instances - The level's layer instances, already filtered to objects.\n * @param project - The project root, for `defaultGridSize`.\n * @returns The grid size in pixels; never zero.\n */\nfunction resolveGridSize(\n instances: readonly Readonly<Record<string, unknown>>[],\n project: Readonly<Record<string, unknown>>,\n): number {\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance === undefined) {\n continue;\n }\n const size = readNumber(instance, \"__gridSize\", 0);\n if (size > 0) {\n return size;\n }\n }\n const fallback = readNumber(project, \"defaultGridSize\", 0);\n return fallback > 0 ? fallback : 16;\n}\n\n/**\n * Reads one LDtk tileset definition, including its `customData` colliders.\n *\n * @param raw - The tileset definition.\n * @param firstId - The global id this tileset's tile `0` takes.\n * @param atlasFor - The image-to-atlas address mapping.\n * @returns The tileset definition.\n */\nfunction readTileset(\n raw: Readonly<Record<string, unknown>>,\n firstId: number,\n atlasFor: (relPath: string) => string,\n): TilesetDefinition {\n const name = readString(raw, \"identifier\", `tileset${String(firstId)}`);\n const gridSize = Math.max(1, readNumber(raw, \"tileGridSize\", 16));\n const columns = readNumber(raw, \"__cWid\", Math.floor(readNumber(raw, \"pxWid\", 0) / gridSize));\n const rows = readNumber(raw, \"__cHei\", Math.floor(readNumber(raw, \"pxHei\", 0) / gridSize));\n const solid = new Set<number>();\n const customData = readArray(raw, \"customData\");\n for (let index = 0; index < customData.length; index += 1) {\n const entry = customData[index];\n if (isRecord(entry) && isSolidCustomData(entry[\"data\"])) {\n solid.add(readNumber(entry, \"tileId\", -1));\n }\n }\n const tiles: TileDefinition[] = [];\n const tileCount = Math.max(0, columns * rows);\n for (let localId = 0; localId < tileCount; localId += 1) {\n const frame = `${name}_${String(localId)}`;\n tiles.push(\n solid.has(localId)\n ? { id: localId, frame, collider: { kind: \"box\", x: 0, y: 0, width: 1, height: 1 } }\n : { id: localId, frame },\n );\n }\n return { name, atlas: atlasFor(readString(raw, \"relPath\", \"\")), firstId, tiles };\n}\n\n/**\n * Decides whether an LDtk `customData` payload marks its tile solid.\n *\n * @param data - The raw `data` string.\n * @returns Whether it parses as JSON with a `solid: true` field.\n */\nfunction isSolidCustomData(data: unknown): boolean {\n if (typeof data !== \"string\" || data === \"\") {\n return false;\n }\n try {\n const parsed: unknown = JSON.parse(data);\n return isRecord(parsed) && parsed[\"solid\"] === true;\n } catch {\n // `customData` is free-form; other tools store plain text in it. Not JSON simply means \"no\n // collider\", which is the same answer as an absent entry.\n return false;\n }\n}\n\n/**\n * Builds the synthetic, art-less tileset the IntGrid layers point into.\n *\n * @param instances - The level's layer instances, in ignifx order.\n * @param firstId - The global id the synthetic tile for IntGrid value `1` takes.\n * @param colliders - The IntGrid value to collider mapping.\n * @returns The tileset, or `null` when the level has no IntGrid data.\n */\nfunction buildIntGridTileset(\n instances: readonly Readonly<Record<string, unknown>>[],\n firstId: number,\n colliders: Readonly<Record<number, TileColliderDefinition>>,\n): TilesetDefinition | null {\n let maxValue = 0;\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance === undefined || readString(instance, \"__type\", \"\") !== \"IntGrid\") {\n continue;\n }\n const csv = readArray(instance, \"intGridCsv\");\n for (let cell = 0; cell < csv.length; cell += 1) {\n const value = csv[cell];\n if (typeof value === \"number\" && value > maxValue) {\n maxValue = value;\n }\n }\n }\n if (maxValue <= 0) {\n return null;\n }\n const tiles: TileDefinition[] = [];\n for (let value = 1; value <= maxValue; value += 1) {\n const frame = `${LDTK_INTGRID_TILESET_NAME}_${String(value)}`;\n const collider = colliders[value];\n tiles.push(collider === undefined ? { id: value - 1, frame } : { id: value - 1, frame, collider });\n }\n // The atlas address is deliberately empty: an IntGrid layer is collision, not art, and there is\n // no image to cut frames from.\n return { name: LDTK_INTGRID_TILESET_NAME, atlas: \"\", firstId, tiles };\n}\n\n/**\n * Converts an LDtk parallax factor pair into an ignifx parallax multiplier.\n *\n * @remarks\n * LDtk's `parallaxFactorX` is an offset *fraction*: `0` means the layer sits still relative to the\n * level, and a positive factor makes it lag the camera. ignifx's `parallax` is a speed multiplier\n * where `1` moves with the camera, so the two are related by `multiplier = 1 - factor`.\n *\n * @param layerDefs - The project's `defs.layers`.\n * @param uid - The `layerDefUid` to look up.\n * @returns The parallax multiplier.\n */\nfunction readParallax(layerDefs: readonly unknown[], uid: number): ParallaxFactor {\n for (let index = 0; index < layerDefs.length; index += 1) {\n const def = layerDefs[index];\n if (isRecord(def) && readNumber(def, \"uid\", -1) === uid) {\n return { x: 1 - readNumber(def, \"parallaxFactorX\", 0), y: 1 - readNumber(def, \"parallaxFactorY\", 0) };\n }\n }\n return { x: 1, y: 1 };\n}\n\n/**\n * Expands an LDtk `Tiles` layer's sparse `gridTiles` into a dense tile array.\n *\n * @param instance - The layer instance.\n * @param order - The layer's position in ignifx order.\n * @param sortingLayer - The sorting layer to place it in.\n * @param parallax - The parallax multiplier.\n * @param tileset - The tileset the layer draws from, or `null` when it names none.\n * @returns The layer input.\n */\nfunction readTilesLayer(\n instance: Readonly<Record<string, unknown>>,\n order: number,\n sortingLayer: string,\n parallax: ParallaxFactor,\n tileset: TilesetDefinition | null,\n): TilemapLayerInput {\n const columns = Math.max(0, readNumber(instance, \"__cWid\", 0));\n const rows = Math.max(0, readNumber(instance, \"__cHei\", 0));\n const gridSize = Math.max(1, readNumber(instance, \"__gridSize\", 1));\n const offsetX = Math.round(readNumber(instance, \"pxOffsetX\", 0) / gridSize);\n const offsetY = Math.round(readNumber(instance, \"pxOffsetY\", 0) / gridSize);\n const firstId = tileset === null ? 1 : tileset.firstId;\n const tiles = Array.from({ length: columns * rows }, (): number => 0);\n const gridTiles = readArray(instance, \"gridTiles\");\n for (let index = 0; index < gridTiles.length; index += 1) {\n const gridTile = gridTiles[index];\n if (!isRecord(gridTile)) {\n continue;\n }\n const px = gridTile[\"px\"];\n if (!isUnknownArray(px)) {\n continue;\n }\n const rawX = px[0];\n const rawY = px[1];\n if (typeof rawX !== \"number\" || typeof rawY !== \"number\") {\n continue;\n }\n const cellX = Math.floor(rawX / gridSize) + offsetX;\n const cellY = Math.floor(rawY / gridSize) + offsetY;\n if (cellX < 0 || cellY < 0 || cellX >= columns || cellY >= rows) {\n continue;\n }\n tiles[cellY * columns + cellX] = firstId + readNumber(gridTile, \"t\", 0);\n }\n return {\n name: readString(instance, \"__identifier\", `Layer ${String(order)}`),\n sortingLayer,\n orderInLayer: order,\n opacity: readNumber(instance, \"__opacity\", 1),\n parallax,\n collision: false,\n width: columns,\n height: rows,\n tiles,\n };\n}\n\n/**\n * Turns an LDtk `IntGrid` layer's `intGridCsv` into a collision layer over the synthetic tileset.\n *\n * @param instance - The layer instance.\n * @param order - The layer's position in ignifx order.\n * @param sortingLayer - The sorting layer to place it in.\n * @param parallax - The parallax multiplier.\n * @param firstId - The synthetic tileset's `firstId`.\n * @returns The layer input.\n */\nfunction readIntGridLayer(\n instance: Readonly<Record<string, unknown>>,\n order: number,\n sortingLayer: string,\n parallax: ParallaxFactor,\n firstId: number,\n): TilemapLayerInput {\n const columns = Math.max(0, readNumber(instance, \"__cWid\", 0));\n const rows = Math.max(0, readNumber(instance, \"__cHei\", 0));\n const csv = readArray(instance, \"intGridCsv\");\n const tiles = Array.from({ length: columns * rows }, (): number => 0);\n for (let index = 0; index < tiles.length && index < csv.length; index += 1) {\n const value = csv[index];\n if (typeof value === \"number\" && value > 0) {\n tiles[index] = firstId + (value - 1);\n }\n }\n return {\n name: readString(instance, \"__identifier\", `Layer ${String(order)}`),\n sortingLayer,\n orderInLayer: order,\n opacity: readNumber(instance, \"__opacity\", 1),\n parallax,\n collision: true,\n width: columns,\n height: rows,\n tiles,\n };\n}\n\n/**\n * Converts an LDtk `Entities` layer into tilemap objects.\n *\n * @remarks\n * `px` is the entity's **pivot** in level pixels from the level's top-left, so the box's top-left is\n * `px - pivot * size`; the layer's `pxOffset` shifts it, and the +Y flip then puts the bottom edge\n * at `(levelHeightPx - top - height) / ppu`.\n *\n * @param instance - The layer instance.\n * @param levelHeightPx - The level's height in pixels.\n * @param pixelsPerUnit - The pixels one world metre spans.\n * @param out - The object list to append to.\n */\nfunction readEntities(\n instance: Readonly<Record<string, unknown>>,\n levelHeightPx: number,\n pixelsPerUnit: number,\n out: TilemapObjectDefinition[],\n): void {\n const offsetX = readNumber(instance, \"pxOffsetX\", 0);\n const offsetY = readNumber(instance, \"pxOffsetY\", 0);\n const entities = readArray(instance, \"entityInstances\");\n for (let index = 0; index < entities.length; index += 1) {\n const entity = entities[index];\n if (!isRecord(entity)) {\n continue;\n }\n const identifier = readString(entity, \"__identifier\", \"\");\n const entityWidth = readNumber(entity, \"width\", 0);\n const entityHeight = readNumber(entity, \"height\", 0);\n const px = entity[\"px\"];\n const pivot = entity[\"__pivot\"];\n const pivotX = isUnknownArray(pivot) && typeof pivot[0] === \"number\" ? pivot[0] : 0;\n const pivotY = isUnknownArray(pivot) && typeof pivot[1] === \"number\" ? pivot[1] : 0;\n const pivotPxX = isUnknownArray(px) && typeof px[0] === \"number\" ? px[0] : 0;\n const pivotPxY = isUnknownArray(px) && typeof px[1] === \"number\" ? px[1] : 0;\n const left = pivotPxX + offsetX - pivotX * entityWidth;\n const top = pivotPxY + offsetY - pivotY * entityHeight;\n const properties = fieldInstancesToRecord(entity[\"fieldInstances\"]);\n const named = properties[\"name\"];\n out.push({\n name: typeof named === \"string\" && named !== \"\" ? named : identifier,\n type: identifier,\n x: left / pixelsPerUnit,\n y: (levelHeightPx - top - entityHeight) / pixelsPerUnit,\n width: entityWidth / pixelsPerUnit,\n height: entityHeight / pixelsPerUnit,\n properties,\n });\n }\n}\n\n/**\n * Narrows an unknown JSON value to a plain object.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown JSON value to an array without widening its elements to `any`.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Reads a numeric field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a finite number.\n * @returns The number.\n */\nfunction readNumber(source: Readonly<Record<string, unknown>>, key: string, fallback: number): number {\n const value = source[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Reads a string field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a string.\n * @returns The string.\n */\nfunction readString(source: Readonly<Record<string, unknown>>, key: string, fallback: string): string {\n const value = source[key];\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Reads an array field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @returns The array, or an empty one when the field is missing or not an array.\n */\nfunction readArray(source: Readonly<Record<string, unknown>>, key: string): readonly unknown[] {\n const value = source[key];\n return isUnknownArray(value) ? value : [];\n}\n","import { twoDError, TwoDErrorCode } from \"../../errors.js\";\nimport { DEFAULT_PIXELS_PER_UNIT } from \"../../math/coords.js\";\nimport { defineTilemap } from \"../definition.js\";\nimport type {\n TileAnimationFrame,\n TileColliderDefinition,\n TileDefinition,\n TilemapDefinition,\n TilemapLayerInput,\n TilemapObjectDefinition,\n TilesetDefinition,\n} from \"../definition.js\";\n\n/**\n * The **Tiled** importer: turns a `.tmj` (Tiled's JSON map format) into an `ignifx.tilemap`\n * document (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * It is a pure function over already-parsed JSON — no file system, no network, no asset system — so\n * it runs identically in the Vite plugin, in a CLI importer and in a test. Orthogonal maps only;\n * isometric and hexagonal are post-MVP and are rejected rather than silently mangled.\n */\n\n/** The three high bits Tiled packs the horizontal, vertical and diagonal flip flags into. */\nconst TILED_GID_MASK = 0x1fffffff;\n\n/** The name reported in `IGX-1109` context so a developer knows which importer complained. */\nconst IMPORTER_NAME = \"tiled\";\n\n/**\n * How {@link importTiledMap} maps Tiled's conventions onto ignifx's.\n *\n * @public\n */\nexport interface TiledImportOptions {\n /** The pixels one world metre spans. Defaults to `100`, matching `twoD.pixelsPerUnit`. */\n readonly pixelsPerUnit?: number;\n /** The sorting layer every tile layer lands in unless it says otherwise. Defaults to `\"Default\"`. */\n readonly sortingLayer?: string;\n /**\n * Maps a Tiled tileset's `image` path onto the address of the ignifx `.atlas.json` that was\n * generated from it. Defaults to swapping the file extension for `.atlas.json`.\n */\n readonly atlasFor?: (imageSource: string) => string;\n}\n\n/**\n * Flattens Tiled's `[{ name, type, value }]` property arrays into a plain record.\n *\n * @remarks\n * Only `string`, `number` and `boolean` values survive; Tiled's `object` and `class` property types\n * carry editor-side references that mean nothing at runtime, and are dropped rather than stringified\n * into something that looks meaningful but is not. `color` and `file` properties are strings in the\n * JSON and come through as strings.\n *\n * @param properties - The value of a Tiled `properties` field, or anything else.\n * @returns The flattened record; empty when `properties` is not a Tiled property array.\n *\n * @example\n * ```ts\n * tiledPropertiesToRecord([{ name: \"biome\", type: \"string\", value: \"cave\" }]); // { biome: \"cave\" }\n * ```\n *\n * @public\n */\nexport function tiledPropertiesToRecord(properties: unknown): Readonly<Record<string, string | number | boolean>> {\n if (!isUnknownArray(properties)) {\n return {};\n }\n const out: Record<string, string | number | boolean> = {};\n for (let index = 0; index < properties.length; index += 1) {\n const entry = properties[index];\n if (!isRecord(entry)) {\n continue;\n }\n const name = entry[\"name\"];\n const value = entry[\"value\"];\n if (typeof name !== \"string\" || name === \"\") {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[name] = value;\n }\n }\n return out;\n}\n\n/**\n * Imports a Tiled JSON map.\n *\n * @remarks\n * Three Tiled features are rejected outright with `IGX-1109` rather than approximated: a non\n * orthogonal `orientation`, an `infinite` map (whose layers are chunked rather than dense), and\n * base64/compressed layer `data` (which arrives as a string). Everything else degrades quietly —\n * image layers and group layers are skipped, and unknown properties are carried through.\n *\n * Tiled stores the horizontal, vertical and diagonal flip flags in the top three bits of every\n * global tile id. ignifx has no per-cell flip yet, so those bits are **masked off** and the tile\n * draws unflipped; without the mask a flipped tile would resolve to a nonsensical tileset.\n *\n * The frame names this importer emits are `<tilesetName>_<localTileIndex>` — the same names\n * the grid-atlas generator gives the frames it cuts out of the tileset image, which is the contract\n * that lets `TilemapRenderer` look a tile's sprite up without a side table.\n *\n * @param tmj - The parsed `.tmj` document.\n * @param options - Pixels-per-unit, the default sorting layer, and the atlas address mapping.\n * @returns The `ignifx.tilemap` document.\n * @throws IgnifxError with code `IGX-1109` when the document is not an orthogonal, finite,\n * uncompressed Tiled map, and `IGX-1105` when what it decodes to is not a valid tilemap.\n *\n * @example\n * ```ts\n * const map = importTiledMap(JSON.parse(await readFile(\"cave.tmj\", \"utf8\")), { pixelsPerUnit: 32 });\n * ```\n *\n * @public\n */\nexport function importTiledMap(tmj: unknown, options: TiledImportOptions = {}): TilemapDefinition {\n const fail = (reason: string): never => {\n throw twoDError(TwoDErrorCode.unsupportedImport, `The Tiled importer cannot read this document: ${reason}.`, {\n context: { importer: IMPORTER_NAME, reason },\n hint: \"Re-export the map from Tiled as an orthogonal, finite map with uncompressed CSV layer data.\",\n });\n };\n if (!isRecord(tmj)) {\n return fail(\"it is not a JSON object\");\n }\n const orientation = readString(tmj, \"orientation\", \"orthogonal\");\n if (orientation !== \"orthogonal\") {\n return fail(`its orientation is ${orientation}, and only orthogonal maps are supported`);\n }\n if (tmj[\"infinite\"] === true) {\n return fail(\"it is an infinite map, whose layers are stored as chunks rather than a dense grid\");\n }\n\n const pixelsPerUnit = options.pixelsPerUnit ?? DEFAULT_PIXELS_PER_UNIT;\n const defaultSortingLayer = options.sortingLayer ?? \"Default\";\n const atlasFor = options.atlasFor ?? defaultAtlasFor;\n const tileWidth = readNumber(tmj, \"tilewidth\", 0);\n const tileHeight = readNumber(tmj, \"tileheight\", tileWidth);\n const width = readNumber(tmj, \"width\", 0);\n const height = readNumber(tmj, \"height\", 0);\n const mapHeightPx = height * tileHeight;\n\n const tilesets: TilesetDefinition[] = [];\n const rawTilesets = readArray(tmj, \"tilesets\");\n for (let index = 0; index < rawTilesets.length; index += 1) {\n const raw = rawTilesets[index];\n if (!isRecord(raw)) {\n continue;\n }\n if (typeof raw[\"source\"] === \"string\") {\n return fail(`tileset ${String(index)} is an external .tsx reference, which this importer cannot resolve`);\n }\n tilesets.push(readTileset(raw, index, tileWidth, tileHeight, atlasFor));\n }\n\n const layers: TilemapLayerInput[] = [];\n const objects: TilemapObjectDefinition[] = [];\n const rawLayers = readArray(tmj, \"layers\");\n for (let index = 0; index < rawLayers.length; index += 1) {\n const raw = rawLayers[index];\n if (!isRecord(raw)) {\n continue;\n }\n const type = readString(raw, \"type\", \"\");\n if (type === \"tilelayer\") {\n layers.push(readTileLayer(raw, layers.length, width, height, defaultSortingLayer, fail));\n continue;\n }\n if (type === \"objectgroup\") {\n readObjectLayer(raw, mapHeightPx, pixelsPerUnit, objects);\n }\n // Image layers and group layers carry nothing the tilemap format models; skipping them is\n // friendlier than refusing a map that merely has a reference image pinned to it.\n }\n\n return defineTilemap(\n {\n tileWidth,\n tileHeight,\n cellSize: tileWidth / pixelsPerUnit,\n width,\n height,\n tilesets,\n layers,\n objects,\n properties: tiledPropertiesToRecord(tmj[\"properties\"]),\n },\n \"<tiled>\",\n );\n}\n\n/**\n * Swaps a file extension for `.atlas.json`, the default {@link TiledImportOptions.atlasFor}.\n *\n * @param imageSource - The image path the editor recorded.\n * @returns The atlas address.\n */\nfunction defaultAtlasFor(imageSource: string): string {\n const slash = Math.max(imageSource.lastIndexOf(\"/\"), imageSource.lastIndexOf(\"\\\\\"));\n const dot = imageSource.lastIndexOf(\".\");\n return dot > slash ? `${imageSource.slice(0, dot)}.atlas.json` : `${imageSource}.atlas.json`;\n}\n\n/**\n * Reads one embedded Tiled tileset.\n *\n * @param raw - The tileset object.\n * @param index - Its position in the `tilesets` array, used to name an unnamed tileset.\n * @param tileWidth - The map's tile width in pixels, for normalising colliders.\n * @param tileHeight - The map's tile height in pixels, for normalising colliders.\n * @param atlasFor - The image-to-atlas address mapping.\n * @returns The tileset definition.\n */\nfunction readTileset(\n raw: Readonly<Record<string, unknown>>,\n index: number,\n tileWidth: number,\n tileHeight: number,\n atlasFor: (imageSource: string) => string,\n): TilesetDefinition {\n const name = readString(raw, \"name\", `tileset${String(index)}`);\n const image = readString(raw, \"image\", \"\");\n const tileCount = readNumber(raw, \"tilecount\", 0);\n const overrides = new Map<number, Readonly<Record<string, unknown>>>();\n const rawTiles = readArray(raw, \"tiles\");\n for (let tileIndex = 0; tileIndex < rawTiles.length; tileIndex += 1) {\n const entry = rawTiles[tileIndex];\n if (isRecord(entry)) {\n overrides.set(readNumber(entry, \"id\", -1), entry);\n }\n }\n const tiles: TileDefinition[] = [];\n for (let localId = 0; localId < tileCount; localId += 1) {\n tiles.push(readTile(overrides.get(localId), localId, name, tileWidth, tileHeight));\n }\n return { name, atlas: atlasFor(image), firstId: readNumber(raw, \"firstgid\", 1), tiles };\n}\n\n/**\n * Reads one tile of a Tiled tileset, filling in the parts Tiled only writes when they are not empty.\n *\n * @param entry - The `tiles[]` override for this local id, when there is one.\n * @param localId - The tile's index within its tileset.\n * @param tilesetName - The frame-name prefix.\n * @param tileWidth - The map's tile width in pixels.\n * @param tileHeight - The map's tile height in pixels.\n * @returns The tile definition.\n */\nfunction readTile(\n entry: Readonly<Record<string, unknown>> | undefined,\n localId: number,\n tilesetName: string,\n tileWidth: number,\n tileHeight: number,\n): TileDefinition {\n const frame = `${tilesetName}_${String(localId)}`;\n if (entry === undefined) {\n return { id: localId, frame };\n }\n const properties = tiledPropertiesToRecord(entry[\"properties\"]);\n const oneWay = properties[\"oneWay\"] === true;\n const collider = readCollider(entry[\"objectgroup\"], tileWidth, tileHeight, oneWay);\n const animation = readAnimation(entry[\"animation\"], tilesetName);\n return {\n id: localId,\n frame,\n ...(collider === null ? {} : { collider }),\n ...(Object.keys(properties).length === 0 ? {} : { properties }),\n ...(animation === null ? {} : { animation }),\n };\n}\n\n/**\n * Turns a per-tile `objectgroup` into a cell-normalised collider.\n *\n * @remarks\n * Tiled lets an artist draw any number of shapes on a tile; the tilemap format models one, so the\n * first shape wins. A shape with a `polygon` array becomes a polygon collider (its points are\n * relative to the object's own origin, so the object position is added back in); anything else with\n * a positive size becomes a box. Both stay in the editor's top-left-origin normalised space —\n * `tileCollisionInfo` performs the flip into metres.\n *\n * @param objectGroup - The tile's `objectgroup` field.\n * @param tileWidth - The map's tile width in pixels.\n * @param tileHeight - The map's tile height in pixels.\n * @param oneWay - Whether the tile's `oneWay` property is set.\n * @returns The collider, or `null` when the tile declares none and is not a bare one-way tile.\n */\nfunction readCollider(\n objectGroup: unknown,\n tileWidth: number,\n tileHeight: number,\n oneWay: boolean,\n): TileColliderDefinition | null {\n const group = isRecord(objectGroup) ? objectGroup : null;\n const shapes = group === null ? [] : readArray(group, \"objects\");\n for (let index = 0; index < shapes.length; index += 1) {\n const shape = shapes[index];\n if (!isRecord(shape)) {\n continue;\n }\n const originX = readNumber(shape, \"x\", 0);\n const originY = readNumber(shape, \"y\", 0);\n const polygon = shape[\"polygon\"];\n if (isUnknownArray(polygon)) {\n const points: { readonly x: number; readonly y: number }[] = [];\n for (let pointIndex = 0; pointIndex < polygon.length; pointIndex += 1) {\n const point = polygon[pointIndex];\n if (isRecord(point)) {\n points.push({\n x: (originX + readNumber(point, \"x\", 0)) / tileWidth,\n y: (originY + readNumber(point, \"y\", 0)) / tileHeight,\n });\n }\n }\n if (points.length >= 3) {\n return { kind: \"polygon\", points, ...(oneWay ? { oneWay: true } : {}) };\n }\n continue;\n }\n const shapeWidth = readNumber(shape, \"width\", 0);\n const shapeHeight = readNumber(shape, \"height\", 0);\n if (shapeWidth > 0 && shapeHeight > 0) {\n return {\n kind: \"box\",\n x: originX / tileWidth,\n y: originY / tileHeight,\n width: shapeWidth / tileWidth,\n height: shapeHeight / tileHeight,\n ...(oneWay ? { oneWay: true } : {}),\n };\n }\n }\n // A tile marked one-way but drawn with no shape is still meant to be a platform; giving it the\n // whole cell is the only reading that does what the author asked.\n return oneWay ? { kind: \"box\", x: 0, y: 0, width: 1, height: 1, oneWay: true } : null;\n}\n\n/**\n * Turns Tiled's `[{ tileid, duration }]` animation into {@link TileAnimationFrame}s.\n *\n * @param animation - The tile's `animation` field.\n * @param tilesetName - The frame-name prefix.\n * @returns The frames, or `null` when the tile does not animate.\n */\nfunction readAnimation(animation: unknown, tilesetName: string): readonly TileAnimationFrame[] | null {\n if (!isUnknownArray(animation) || animation.length === 0) {\n return null;\n }\n const frames: TileAnimationFrame[] = [];\n for (let index = 0; index < animation.length; index += 1) {\n const step = animation[index];\n if (!isRecord(step)) {\n continue;\n }\n frames.push({\n frame: `${tilesetName}_${String(readNumber(step, \"tileid\", 0))}`,\n durationMs: readNumber(step, \"duration\", 0),\n });\n }\n return frames.length === 0 ? null : frames;\n}\n\n/**\n * Reads one Tiled tile layer.\n *\n * @param raw - The layer object.\n * @param order - The layer's position among the emitted layers, used as the default draw order.\n * @param mapWidth - The map's width in cells.\n * @param mapHeight - The map's height in cells.\n * @param defaultSortingLayer - The sorting layer to use when the layer names none.\n * @param fail - The `IGX-1109` thrower.\n * @returns The layer input.\n */\nfunction readTileLayer(\n raw: Readonly<Record<string, unknown>>,\n order: number,\n mapWidth: number,\n mapHeight: number,\n defaultSortingLayer: string,\n fail: (reason: string) => never,\n): TilemapLayerInput {\n const name = readString(raw, \"name\", `Layer ${String(order)}`);\n const data = raw[\"data\"];\n if (typeof data === \"string\") {\n fail(\n `layer ${name} stores its data as a string, and compressed layer data is not supported; export uncompressed CSV/array data`,\n );\n }\n if (!isUnknownArray(data)) {\n return fail(`layer ${name} has no tile data array`);\n }\n const tiles: number[] = [];\n for (let index = 0; index < data.length; index += 1) {\n const gid = data[index];\n tiles.push(typeof gid === \"number\" ? gid & TILED_GID_MASK : 0);\n }\n const properties = tiledPropertiesToRecord(raw[\"properties\"]);\n const sortingLayer = properties[\"sortingLayer\"];\n const orderInLayer = properties[\"orderInLayer\"];\n return {\n name,\n sortingLayer: typeof sortingLayer === \"string\" ? sortingLayer : defaultSortingLayer,\n orderInLayer: typeof orderInLayer === \"number\" ? orderInLayer : order,\n opacity: readNumber(raw, \"opacity\", 1),\n parallax: { x: readNumber(raw, \"parallaxx\", 1), y: readNumber(raw, \"parallaxy\", 1) },\n collision: properties[\"collision\"] === true,\n width: readNumber(raw, \"width\", mapWidth),\n height: readNumber(raw, \"height\", mapHeight),\n tiles,\n };\n}\n\n/**\n * Reads one Tiled object layer, appending its objects to the map's flat object list.\n *\n * @remarks\n * Tiled measures an object rectangle from the **map's top-left** in pixels, with `y` at the\n * rectangle's top. ignifx wants world metres with +Y up and `y` at the bottom, so the conversion is\n * `xM = x / ppu` and `yM = (mapHeightPx - y - height) / ppu`.\n *\n * @param raw - The layer object.\n * @param mapHeightPx - The map's height in pixels.\n * @param pixelsPerUnit - The pixels one world metre spans.\n * @param out - The object list to append to.\n */\nfunction readObjectLayer(\n raw: Readonly<Record<string, unknown>>,\n mapHeightPx: number,\n pixelsPerUnit: number,\n out: TilemapObjectDefinition[],\n): void {\n const objects = readArray(raw, \"objects\");\n for (let index = 0; index < objects.length; index += 1) {\n const object = objects[index];\n if (!isRecord(object)) {\n continue;\n }\n const objectHeight = readNumber(object, \"height\", 0);\n out.push({\n name: readString(object, \"name\", \"\"),\n // Tiled 1.9 renamed the object's `type` field to `class`; both spellings are in the wild.\n type: readString(object, \"type\", readString(object, \"class\", \"\")),\n x: readNumber(object, \"x\", 0) / pixelsPerUnit,\n y: (mapHeightPx - readNumber(object, \"y\", 0) - objectHeight) / pixelsPerUnit,\n width: readNumber(object, \"width\", 0) / pixelsPerUnit,\n height: objectHeight / pixelsPerUnit,\n properties: tiledPropertiesToRecord(object[\"properties\"]),\n });\n }\n}\n\n/**\n * Narrows an unknown JSON value to a plain object.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown JSON value to an array without widening its elements to `any`.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Reads a numeric field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a finite number.\n * @returns The number.\n */\nfunction readNumber(source: Readonly<Record<string, unknown>>, key: string, fallback: number): number {\n const value = source[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Reads a string field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a string.\n * @returns The string.\n */\nfunction readString(source: Readonly<Record<string, unknown>>, key: string, fallback: string): string {\n const value = source[key];\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Reads an array field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @returns The array, or an empty one when the field is missing or not an array.\n */\nfunction readArray(source: Readonly<Record<string, unknown>>, key: string): readonly unknown[] {\n const value = source[key];\n return isUnknownArray(value) ? value : [];\n}\n"],"mappings":";;;;;;;;;;;;AAwCA,SAAgB,sBAAsB,KAAuB,SAA4B;CACvF,IAAI,kBAAkB,cAAuB,OAAO;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACbA,MAAa,gBAAgB;;CAE3B,uBAAuB;;CAEvB,kBAAkB;;CAElB,sBAAsB;;CAEtB,oBAAoB;;CAEpB,cAAc;;CAEd,qBAAqB;;CAErB,aAAa;;CAEb,mBAAmB;;CAEnB,wBAAwB;;CAExB,gBAAgB;;CAEhB,oBAAoB;;CAEpB,qBAAqB;AACvB;;;;;;;AAeA,MAAa,uBAAyD,OAAO,OAAO;CAClF,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;AACd,CAAC;;;;;;;;;;;;;;;;;;AAiCD,SAAgB,UAAU,MAAqB,SAAiB,SAAyC;CACvG,OAAO,IAAI,YAAY,MAAM,SAAS;EACpC,GAAI,SAAS,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;EACrE,GAAI,SAAS,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;EAC5D,GAAI,SAAS,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;CACjE,CAAC;AACH;;;;;;;;;;;;;;;;ACxGA,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;;;;;;AAO3C,MAAa,0BAA0B;;;;;;AAOvC,MAAa,+BAAkD,OAAO,OAAO,CAAC,aAAa,CAAC;;;;;;AAO5F,MAAa,+BAA+B;;;;;;;;;;AAmB5C,SAAgB,SAAS,OAA6B,UAA8B;CAClF,IAAI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AAO;CACrB,OAAO,eAAe,KAAK,IAAI,QAAQ,CAAC;AAC1C"}
1
+ {"version":3,"file":"index.js","names":["CENTRE_PIVOT","CENTRE_PIVOT","failImport","isObject","isUnknownArray","isFiniteNumber","readVec2","isUnknownArray","CENTRE_PIVOT","RAD_TO_DEG","IMPORTER_NAME","isRecord","readArray","defaultAtlasFor","readString","readNumber","readTileset","isUnknownArray"],"sources":["../src/augmentation.ts","../src/errors.ts","../src/atlas/definition.ts","../src/atlas/sprite-atlas-asset.ts","../src/lite/sprite-layer.ts","../src/service/sorting-layers.ts","../src/sprite/sprite-renderer.ts","../src/animation/definition.ts","../src/animation/sprite-animation-asset.ts","../src/animation/sprite-animator.ts","../src/animation/animation-system.ts","../src/atlas/importers.ts","../src/animation/importers.ts","../src/assets/relative.ts","../src/animation/loader.ts","../src/lite/atlas.ts","../src/lite/gpu/texture.ts","../src/atlas/loader.ts","../src/math/coords.ts","../src/camera/camera-2d.ts","../src/camera/camera-2d-follow.ts","../src/lite/gpu/sprite-renderer.ts","../src/sprite/parallax-layer.ts","../src/sprite/sprite-layer-effect.ts","../src/tilemap/definition.ts","../src/tilemap/tilemap-renderer.ts","../src/service/layer-registry.ts","../src/service/runtime.ts","../src/tilemap/collision-merge.ts","../src/tilemap/tilemap-asset.ts","../src/tilemap/tilemap.ts","../src/service/sync-system.ts","../src/service/two-d-service.ts","../src/settings.ts","../src/tilemap/spawn-objects.ts","../src/version.ts","../src/extension.ts","../src/file-schemas.ts","../src/schemas.ts","../src/tilemap/importers/ldtk.ts","../src/tilemap/importers/tiled.ts"],"sourcesContent":["import type { TwoDService } from \"./service/two-d-service.js\";\nimport type { ExtensionContext } from \"@ignifx/core\";\n\n/**\n * The typed entry point (`docs/architecture/03-scripting-and-components.md` §7). Declaration\n * merging is what makes `this.app.twoD` fully typed when `@ignifx/2d` is installed and a compile\n * error when it is not.\n *\n * Two mechanics carry over from `@ignifx/input`, both measured rather than assumed:\n *\n * - The module **must** import something from `@ignifx/core`. A `declare module \"@ignifx/core\"`\n * block in a file that never imports the module is `TS2664: Invalid module name in augmentation`\n * under both `tsc --build` and TypeDoc; importing the `ExtensionContext` type used below is\n * enough to bring the module into the program.\n * - The barrel **must** name this module in a bare `import \"./augmentation.js\"`. Declaration\n * bundling drops a module whose only exports are unreferenced from the public surface, which\n * silently takes the augmentation out of `dist/index.d.ts` with it. The bare import is a\n * type-only side effect: the emitted JavaScript keeps no statement for it, so `sideEffects: false`\n * stays honest.\n */\n\ndeclare module \"@ignifx/core\" {\n interface App {\n /**\n * The 2D service (`docs/architecture/11-2d-toolkit.md` §1): the pixels-per-unit conversion, the\n * active `Camera2D`, sprite picking, the sprite-layer diagnostics, and the Lite escape hatch.\n */\n readonly twoD: TwoDService;\n }\n}\n\n/**\n * Defines `app.twoD`, pairing with the augmentation above.\n *\n * @param ctx - The extension registration surface.\n * @param service - The service the property returns.\n * @throws IgnifxError with code `IGX-0401` when something already defined `app.twoD`.\n *\n * @internal\n */\nexport function defineTwoDAppProperty(ctx: ExtensionContext, service: TwoDService): void {\n ctx.defineAppProperty(\"twoD\", (): unknown => service);\n}\n","import { IgnifxError } from \"@ignifx/core\";\nimport type { ErrorContext } from \"@ignifx/core\";\n\n/**\n * The diagnostic codes `@ignifx/2d` owns. The 2D subsystem sits in the `11` range of\n * `docs/architecture/15-devtools-and-diagnostics.md` §1, so every code reads `IGX-11##`.\n *\n * The `11` range is shared with `@ignifx/physics-2d`, which owns `IGX-1101` (registering both\n * `physics()` and `physics2d()` on one world — `docs/architecture/11-2d-toolkit.md` §8) and the\n * codes from `IGX-1130` up. The 2D toolkit owns `IGX-1102` through `IGX-1129`.\n *\n * The table lives here rather than in `@ignifx/core`'s `CoreErrorCode`: an extension owns its own\n * codes and hands them to the app through `ExtensionContext.registerErrorCodes`\n * (`docs/architecture/04-extensions.md` §3).\n */\n\n/**\n * Every diagnostic code `@ignifx/2d` can throw or log, keyed by an intention-revealing name so call\n * sites read as prose and the compiler catches typos (coding standards §5.2).\n *\n * @example\n * ```ts\n * throw twoDError(TwoDErrorCode.unknownSortingLayer, \"Foreground is not a declared sorting layer.\", {\n * context: { sortingLayer: \"Foreground\" },\n * });\n * ```\n *\n * @public\n */\nexport const TwoDErrorCode = {\n /** An atlas frame has no one-pixel extruded border, which a pixel-perfect camera will bleed. */\n atlasFrameNotExtruded: \"IGX-1102\",\n /** A `.atlas.json` file is not an `ignifx.spriteatlas` document this build can read. */\n invalidAtlasFile: \"IGX-1103\",\n /** A `.spriteanim.json` file is not an `ignifx.spriteanimation` document this build can read. */\n invalidAnimationFile: \"IGX-1104\",\n /** A `.tilemap.json` file is not an `ignifx.tilemap` document this build can read. */\n invalidTilemapFile: \"IGX-1105\",\n /** A sprite address names a frame the atlas does not declare. */\n unknownFrame: \"IGX-1106\",\n /** A component named a sorting layer the `sortingLayers` settings section does not declare. */\n unknownSortingLayer: \"IGX-1107\",\n /** `SpriteAnimator.play` named a clip the animation asset does not declare. */\n unknownClip: \"IGX-1108\",\n /** A tilemap importer was handed a document it cannot read, or an unsupported projection. */\n unsupportedImport: \"IGX-1109\",\n /** `app.twoD.registerTileObjectFactory` was called twice for one object type. */\n duplicateObjectFactory: \"IGX-1110\",\n /** A tile coordinate is outside the tilemap layer's bounds. */\n tileOutOfRange: \"IGX-1111\",\n /** A second `twoD()` extension was registered on one app. */\n duplicateExtension: \"IGX-1112\",\n /** A `SpriteLayerEffect` declared the `custom` kind without a WGSL fragment body. */\n missingShaderSource: \"IGX-1113\",\n} as const;\n\n/**\n * The union of the codes the `TwoDErrorCode` table declares.\n *\n * @public\n */\nexport type TwoDErrorCode = (typeof TwoDErrorCode)[keyof typeof TwoDErrorCode];\n\n/**\n * The one-line message template of every code, as `ExtensionContext.registerErrorCodes` wants it.\n * Context keys appear in braces, matching the core table's convention.\n *\n * @public\n */\nexport const TWO_D_ERROR_MESSAGES: Readonly<Record<string, string>> = Object.freeze({\n \"IGX-1102\": \"Atlas frame {frame} has no 1-px extruded border; a pixel-perfect camera will bleed it.\",\n \"IGX-1103\": \"{file} is not an ignifx.spriteatlas document this build can read.\",\n \"IGX-1104\": \"{file} is not an ignifx.spriteanimation document this build can read.\",\n \"IGX-1105\": \"{file} is not an ignifx.tilemap document this build can read.\",\n \"IGX-1106\": \"{atlas} declares no frame named {frame}.\",\n \"IGX-1107\": \"{sortingLayer} is not a sorting layer declared by the sortingLayers settings section.\",\n \"IGX-1108\": \"{asset} declares no clip named {clip}.\",\n \"IGX-1109\": \"{importer} cannot read this document: {reason}.\",\n \"IGX-1110\": \"A tile object factory for {type} is already registered.\",\n \"IGX-1111\": \"Cell {x},{y} is outside layer {layer}.\",\n \"IGX-1112\": \"The twoD() extension is already registered on this app.\",\n \"IGX-1113\": \"A custom SpriteLayerEffect needs a WGSL fragment body in its shader field.\",\n});\n\n/**\n * Options accepted by {@link twoDError}: the same subset of `IgnifxErrorOptions` this package uses.\n *\n * @public\n */\nexport interface TwoDErrorOptions {\n /** Identifiers that locate the failure. */\n readonly context?: ErrorContext;\n /** One sentence telling the developer what to do about it. */\n readonly hint?: string;\n /** The failure being wrapped, when there is one. */\n readonly cause?: unknown;\n}\n\n/**\n * Builds an `IgnifxError` carrying one of this package's codes.\n *\n * @param code - The code from the `TwoDErrorCode` table.\n * @param message - The actionable development sentence.\n * @param options - Context identifiers, a remedy hint, and the wrapped cause.\n * @returns The error to throw or to reject with.\n *\n * @example\n * ```ts\n * throw twoDError(TwoDErrorCode.unknownClip, \"hero.spriteanim.json declares no clip named jump.\", {\n * context: { asset: \"hero.spriteanim.json\", clip: \"jump\" },\n * });\n * ```\n *\n * @public\n */\nexport function twoDError(code: TwoDErrorCode, message: string, options?: TwoDErrorOptions): IgnifxError {\n return new IgnifxError(code, message, {\n ...(options?.context === undefined ? {} : { context: options.context }),\n ...(options?.hint === undefined ? {} : { hint: options.hint }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The `ignifx.spriteatlas` document — the `.atlas.json` file that names an image and the frame\n * rectangles inside it (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `11-2d-toolkit.md` §2.3).\n *\n * Frames are in **image pixels with a top-left origin**, which is what every atlas packer emits.\n * The conversion into Lite's normalised UVs happens in the loader, once.\n */\n\n/**\n * The `format` discriminator every `.atlas.json` document carries.\n *\n * @public\n */\nexport const SPRITE_ATLAS_FORMAT = \"ignifx.spriteatlas\";\n\n/**\n * The document version this build reads and writes.\n *\n * @public\n */\nexport const SPRITE_ATLAS_FORMAT_VERSION = 1;\n\n/**\n * The asset type name the loader registers.\n *\n * @public\n */\nexport const SPRITE_ATLAS_ASSET_TYPE = \"spriteatlas\";\n\n/**\n * The address suffixes that select the sprite-atlas loader.\n *\n * @public\n */\nexport const SPRITE_ATLAS_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".atlas.json\"]);\n\n/**\n * The fragment prefix that addresses one frame: `\"sprites/hero.atlas.json#frame:idle_0\"`.\n *\n * @public\n */\nexport const SPRITE_FRAME_FRAGMENT_PREFIX = \"frame:\";\n\n/**\n * A 2D value as a document may write it: `[x, y]`, the form `@ignifx/core` encodes every `vec2`\n * field into a file as (`schema/encode.ts` line 393), or `{ x, y }`, the form an importer emits.\n *\n * @public\n */\nexport type Vec2Json = Vec2Like | readonly [number, number];\n\n/**\n * Normalises either written form of a 2D value.\n *\n * @param value - What the document wrote, or `undefined`.\n * @param fallback - What to use when the document wrote nothing.\n * @returns The normalised vector.\n *\n * @public\n */\nexport function readVec2(value: Vec2Json | undefined, fallback: Vec2Like): Vec2Like {\n if (value === undefined) {\n return fallback;\n }\n if (isPair(value)) {\n return { x: value[0], y: value[1] };\n }\n return typeof value.x === \"number\" && typeof value.y === \"number\" ? { x: value.x, y: value.y } : fallback;\n}\n\n/**\n * Whether a written 2D value is the `[x, y]` array form.\n *\n * @param value - The value the document carried.\n * @returns `true` when it is a two-number array.\n */\nfunction isPair(value: Vec2Json): value is readonly [number, number] {\n return Array.isArray(value) && typeof value[0] === \"number\" && typeof value[1] === \"number\";\n}\n\n/**\n * One frame rectangle, in image pixels with a top-left origin.\n *\n * @public\n */\nexport interface SpriteFrameDefinition {\n /** The frame's name, unique within the document; what `#frame:` addresses. */\n readonly name: string;\n /** The left edge, in image pixels. */\n readonly x: number;\n /** The top edge, in image pixels. */\n readonly y: number;\n /** The width, in image pixels. */\n readonly w: number;\n /** The height, in image pixels. */\n readonly h: number;\n /**\n * The pivot in `[0, 1]` of the frame — `[0, 0]` top-left, `[0.5, 0.5]` centre, `[1, 1]`\n * bottom-right. Defaults to the centre. Written either as `[x, y]` or as `{ x, y }`.\n */\n readonly pivot?: Vec2Json;\n /** The untrimmed source size, when the packer trimmed transparent margins. Defaults to `w`/`h`. */\n readonly sourceSize?: Vec2Json;\n}\n\n/**\n * The parsed `.atlas.json` document.\n *\n * @example\n * ```ts\n * const atlas = defineSpriteAtlas({\n * image: \"2d/hero.png\",\n * sampling: \"nearest\",\n * frames: [{ name: \"idle_0\", x: 0, y: 0, w: 32, h: 32, pivot: { x: 0.5, y: 1 } }],\n * });\n * ```\n *\n * @public\n */\nexport interface SpriteAtlasDefinition {\n /** Always `\"ignifx.spriteatlas\"`. */\n readonly format: typeof SPRITE_ATLAS_FORMAT;\n /** Always `1` in this build. */\n readonly formatVersion: number;\n /** The address of the image the frames are cut from. */\n readonly image: string;\n /** The min/mag filter. `\"nearest\"` is what pixel art wants. Defaults to `\"linear\"`. */\n readonly sampling: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha: boolean;\n /** The frames, in the order they are indexed. */\n readonly frames: readonly SpriteFrameDefinition[];\n}\n\n/**\n * What {@link defineSpriteAtlas} accepts: the document with every defaulted field optional.\n *\n * @public\n */\nexport interface SpriteAtlasInput {\n /** Always `\"ignifx.spriteatlas\"` when present. */\n readonly format?: string;\n /** The document version. */\n readonly formatVersion?: number;\n /** The address of the image the frames are cut from. */\n readonly image: string;\n /** The min/mag filter. Defaults to `\"linear\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image is premultiplied. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n /** The frames. */\n readonly frames: readonly SpriteFrameDefinition[];\n}\n\n/**\n * Fills in the defaults of an atlas document and checks the invariants a loader relies on.\n *\n * @param input - The document, as authored or as an importer emitted it.\n * @param address - What to name in an error; defaults to `\"<inline>\"`.\n * @returns The complete document.\n * @throws IgnifxError with code `IGX-1103` when the format tag, the version, the image address, or\n * a frame rectangle is wrong, or two frames share a name.\n *\n * @public\n */\nexport function defineSpriteAtlas(input: SpriteAtlasInput, address = \"<inline>\"): SpriteAtlasDefinition {\n const fail = (reason: string): never => {\n throw twoDError(\n TwoDErrorCode.invalidAtlasFile,\n `${address} is not a readable ignifx.spriteatlas document: ${reason}.`,\n {\n context: { file: address },\n hint: \"Regenerate it with `ignifx import atlas`, or check the format and version fields.\",\n },\n );\n };\n if (input.format !== undefined && input.format !== SPRITE_ATLAS_FORMAT) {\n fail(`its format is ${input.format}, not ${SPRITE_ATLAS_FORMAT}`);\n }\n if (input.formatVersion !== undefined && input.formatVersion !== SPRITE_ATLAS_FORMAT_VERSION) {\n fail(\n `its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(SPRITE_ATLAS_FORMAT_VERSION)}`,\n );\n }\n if (typeof input.image !== \"string\" || input.image === \"\") {\n fail(\"it names no image\");\n }\n if (!Array.isArray(input.frames) || input.frames.length === 0) {\n fail(\"it declares no frames\");\n }\n const seen = new Set<string>();\n for (let index = 0; index < input.frames.length; index += 1) {\n const frame = input.frames[index];\n if (frame === undefined || typeof frame.name !== \"string\" || frame.name === \"\") {\n fail(`frame ${String(index)} has no name`);\n continue;\n }\n if (seen.has(frame.name)) {\n fail(`two frames are named ${frame.name}`);\n }\n seen.add(frame.name);\n if (!(frame.w > 0) || !(frame.h > 0)) {\n fail(`frame ${frame.name} has a non-positive size`);\n }\n if (!(frame.x >= 0) || !(frame.y >= 0)) {\n fail(`frame ${frame.name} starts outside the image`);\n }\n }\n const frames: SpriteFrameDefinition[] = [];\n for (let index = 0; index < input.frames.length; index += 1) {\n const frame = input.frames[index];\n if (frame === undefined) {\n continue;\n }\n // Normalise both written forms of a 2D value once, here, so nothing downstream has to care.\n // `sourceSize` keeps its absence: a frame that declares none is untrimmed, and saying so is\n // information an importer round trip should not invent.\n frames.push({\n ...frame,\n pivot: readVec2(frame.pivot, CENTRE_PIVOT),\n ...(frame.sourceSize === undefined ? {} : { sourceSize: readVec2(frame.sourceSize, { x: frame.w, y: frame.h }) }),\n });\n }\n return {\n format: SPRITE_ATLAS_FORMAT,\n formatVersion: SPRITE_ATLAS_FORMAT_VERSION,\n image: input.image,\n sampling: input.sampling ?? \"linear\",\n premultipliedAlpha: input.premultipliedAlpha ?? false,\n frames,\n };\n}\n\n/**\n * The pivot a frame that declares none uses.\n */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * Splits a sprite address into its atlas address and its frame name.\n *\n * @param fragment - The part after `#`, or `null` for a bare atlas address.\n * @returns The frame name, or `null` when the fragment does not select a frame.\n *\n * @example\n * ```ts\n * parseSpriteFragment(\"frame:idle_0\"); // \"idle_0\"\n * ```\n *\n * @public\n */\nexport function parseSpriteFragment(fragment: string | null): string | null {\n if (fragment === null || !fragment.startsWith(SPRITE_FRAME_FRAGMENT_PREFIX)) {\n return null;\n }\n const name = fragment.slice(SPRITE_FRAME_FRAGMENT_PREFIX.length);\n return name === \"\" ? null : name;\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { readVec2, SPRITE_ATLAS_ASSET_TYPE } from \"./definition.js\";\nimport type { SpriteAtlasDefinition } from \"./definition.js\";\nimport type { LiteSpriteAtlas, LiteSpriteFrame } from \"../lite/types.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The value a `.atlas.json` address loads to: the parsed document, the Lite `SpriteAtlas` built\n * from it, and a name-to-index map so `#frame:` addressing is a hash lookup rather than a scan\n * (`docs/architecture/11-2d-toolkit.md` §2.3).\n */\n\n/**\n * The Babylon Lite objects a {@link SpriteAtlasAsset} owns.\n *\n * @public\n */\nexport interface SpriteAtlasAssetLiteHandles {\n /** The Lite atlas, or `null` under a headless app, which uploads nothing. */\n readonly atlas: LiteSpriteAtlas | null;\n}\n\n/**\n * One frame of a loaded atlas, as game code sees it.\n *\n * @public\n */\nexport interface SpriteFrameInfo {\n /** The frame's name. */\n readonly name: string;\n /** Its index in the atlas, which is what Lite addresses frames by. */\n readonly index: number;\n /** Its drawn width, in image pixels. */\n readonly widthPx: number;\n /** Its drawn height, in image pixels. */\n readonly heightPx: number;\n /** Its pivot in `[0, 1]` of the frame, `[0, 0]` top-left. */\n readonly pivot: Vec2Like;\n}\n\n/**\n * A loaded sprite atlas.\n *\n * @remarks\n * Under a headless app the document is parsed and every frame is queryable, but `lite.atlas` is\n * `null` — nothing is uploaded (`docs/architecture/07-rendering.md` §6). That is what lets a\n * headless test assert frame counts, pivots, and animation timing without a GPU.\n *\n * @example\n * ```ts\n * const handle = app.assets.load<SpriteAtlasAsset>(\"2d/hero.atlas.json\");\n * const atlas = await handle.promise;\n * atlas.frameIndex(\"idle_0\"); // 0\n * ```\n *\n * @public\n */\nexport class SpriteAtlasAsset {\n /** The type name the asset service registers sprite atlases under. */\n static assetType: string = SPRITE_ATLAS_ASSET_TYPE;\n\n /** The address the atlas was loaded from. */\n readonly address: string;\n\n /** The parsed `.atlas.json` document. */\n readonly definition: SpriteAtlasDefinition;\n\n #atlas: LiteSpriteAtlas | null;\n\n readonly #indices: ReadonlyMap<string, number>;\n\n readonly #release: (() => void) | null;\n\n /**\n * Wraps a parsed atlas. The `spriteatlas` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The parsed document.\n * @param atlas - The Lite atlas, or `null` under a headless app.\n * @param release - Frees the GPU texture, or `null` when there is nothing to free.\n *\n * @internal\n */\n constructor(\n address: string,\n definition: SpriteAtlasDefinition,\n atlas: LiteSpriteAtlas | null,\n release: (() => void) | null,\n ) {\n this.address = address;\n this.definition = definition;\n this.#atlas = atlas;\n this.#release = release;\n const indices = new Map<string, number>();\n for (let index = 0; index < definition.frames.length; index += 1) {\n const frame = definition.frames[index];\n if (frame !== undefined) {\n indices.set(frame.name, index);\n }\n }\n this.#indices = indices;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch\n * (`CONSTITUTION.md` §3.4).\n *\n * @returns The Lite atlas, or `null` under a headless app.\n */\n get lite(): SpriteAtlasAssetLiteHandles {\n return { atlas: this.#atlas };\n }\n\n /**\n * How many frames the atlas declares.\n *\n * @returns The frame count.\n */\n get frameCount(): number {\n return this.definition.frames.length;\n }\n\n /**\n * Looks a frame up by name.\n *\n * @param name - The frame name.\n * @returns The index, or `-1` when the atlas has no such frame.\n */\n frameIndex(name: string): number {\n return this.#indices.get(name) ?? -1;\n }\n\n /**\n * Looks a frame up by name and refuses to guess.\n *\n * @param name - The frame name.\n * @returns The index.\n * @throws IgnifxError with code `IGX-1106` when the atlas declares no such frame.\n */\n requireFrame(name: string): number {\n const index = this.#indices.get(name);\n if (index === undefined) {\n throw twoDError(TwoDErrorCode.unknownFrame, `${this.address} declares no frame named ${name}.`, {\n context: { atlas: this.address, frame: name },\n hint: `Known frames: ${this.frameNames().join(\", \")}.`,\n });\n }\n return index;\n }\n\n /**\n * Every frame name, in index order.\n *\n * @returns A freshly allocated array.\n */\n frameNames(): readonly string[] {\n const names: string[] = [];\n for (let index = 0; index < this.definition.frames.length; index += 1) {\n const frame = this.definition.frames[index];\n if (frame !== undefined) {\n names.push(frame.name);\n }\n }\n return names;\n }\n\n /**\n * Describes one frame.\n *\n * @param index - The frame index.\n * @returns The frame, or `null` when the index is out of range.\n */\n frame(index: number): SpriteFrameInfo | null {\n const declared = this.definition.frames[index];\n if (declared === undefined) {\n return null;\n }\n // `defineSpriteAtlas` normalised both fields, so they are always `{ x, y }` here.\n const pivot = readVec2(declared.pivot, DEFAULT_PIVOT);\n const source = readVec2(declared.sourceSize, { x: declared.w, y: declared.h });\n return { name: declared.name, index, widthPx: source.x, heightPx: source.y, pivot };\n }\n\n /**\n * The Lite frame record, for the sync system.\n *\n * @param index - The frame index.\n * @returns The record, or `null` under a headless app or for an out-of-range index.\n *\n * @internal\n */\n liteFrame(index: number): LiteSpriteFrame | null {\n return this.#atlas?.frames[index] ?? null;\n }\n\n /**\n * Whether the atlas was uploaded to a device at all.\n *\n * @returns `true` once the GPU texture has been given up, or under a headless app.\n */\n get isReleased(): boolean {\n return this.#atlas === null;\n }\n\n /**\n * Frees the GPU texture. The asset service calls this on unload.\n *\n * @internal\n */\n releaseGpu(): void {\n if (this.#atlas === null) {\n return;\n }\n this.#atlas = null;\n this.#release?.();\n }\n}\n\n/** The pivot a frame that declares none uses: the centre. */\nconst DEFAULT_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * A sprite: one frame of one atlas, which is what `SpriteRenderer.sprite` points at.\n *\n * @remarks\n * A bare `\"2d/hero.atlas.json\"` address resolves to frame `0`; the `#frame:` fragment picks another\n * (`docs/architecture/11-2d-toolkit.md` §2.2). The asset service shares the underlying atlas\n * between every fragment of the same address, so ten sprites off one atlas upload one texture.\n *\n * @public\n */\nexport interface SpriteAsset {\n /** The atlas the frame lives in. */\n readonly atlas: SpriteAtlasAsset;\n /** The frame index. */\n readonly frame: number;\n /** The frame's name. */\n readonly name: string;\n}\n","import {\n addSprite2D,\n clearSprite2DLayer,\n createSprite2DCustomShader,\n createSprite2DLayer,\n disableSprite2DYSort,\n enableSprite2DYSort,\n getSprite2DHandleIndex,\n getSprite2DVisibleBoundsToRef,\n isSprite2DHandleAlive,\n pickSprite2D,\n removeSprite2D,\n setSprite2DShaderParams,\n sprite2DScreenToWorldToRef,\n setSprite2DYSortHandleBias,\n spriteBlendAdditive,\n spriteBlendAlpha,\n spriteBlendMultiply,\n spriteBlendOpaque,\n spriteBlendPremultiplied,\n updateSprite2D,\n} from \"@babylonjs/lite\";\nimport type {\n Bounds2D,\n Sprite2DCustomShader,\n Sprite2DHandle,\n Sprite2DLayer,\n Sprite2DProps,\n Sprite2DView,\n SpriteAtlas,\n SpriteBlendMode,\n SpritePickInfo,\n} from \"@babylonjs/lite\";\n\n/**\n * The CPU half of the Babylon Lite sprite adapter (`docs/architecture/07-rendering.md` §7,\n * `11-2d-toolkit.md` §1). Nothing in this module touches `engine._device`: a `Sprite2DLayer` is a\n * plain object holding a `Float32Array` of instance data, and every sprite mutation writes into\n * that array (verified in `@babylonjs/lite@1.27.0`, `lib/sprite/sprite-2d.js` lines 14-48 for\n * `createSprite2DLayer` and 73-200 for `writeInstance`/`addSprite2DIndex`). GPU buffers are\n * allocated lazily by the renderer at draw time, which is why the device-only calls live in\n * `./gpu/sprite-renderer.ts` instead.\n *\n * That split is what makes the sprite maths unit-testable under Node: a test fabricates a\n * `SpriteAtlas` with {@link createDataAtlas} and exercises everything here on the null engine.\n *\n * Everything except the blend-mode table is `@internal`.\n */\n\n/**\n * The blend modes `SpriteRenderer.blend` accepts, in the order an inspector should list them.\n *\n * @public\n */\nexport const SPRITE_BLEND_MODES = [\"alpha\", \"premultiplied\", \"additive\", \"multiply\", \"opaque\"] as const;\n\n/**\n * How a sprite's colour combines with what is already in the framebuffer\n * (`docs/architecture/11-2d-toolkit.md` §2.2).\n *\n * @public\n */\nexport type SpriteBlendName = (typeof SPRITE_BLEND_MODES)[number];\n\n/**\n * Resolves a blend name to the Lite descriptor `createSprite2DLayer` wants.\n *\n * @remarks\n * The descriptors are the module constants `spriteBlendAlpha` (`index.d.ts` 12108),\n * `spriteBlendPremultiplied` (12153), `spriteBlendAdditive` (12102), `spriteBlendMultiply` (12131)\n * and `spriteBlendOpaque` (12147). `SpriteBlendMode` is a type alias of the opaque\n * `SpriteBlendDescriptor` (12122), so the values are compared by identity, never inspected.\n *\n * @param name - The ignifx blend name.\n * @returns The Lite descriptor.\n *\n * @internal\n */\nexport function blendModeFor(name: SpriteBlendName): SpriteBlendMode {\n switch (name) {\n case \"alpha\": {\n return spriteBlendAlpha;\n }\n case \"premultiplied\": {\n return spriteBlendPremultiplied;\n }\n case \"additive\": {\n return spriteBlendAdditive;\n }\n case \"multiply\": {\n return spriteBlendMultiply;\n }\n case \"opaque\": {\n return spriteBlendOpaque;\n }\n default: {\n return spriteBlendAlpha;\n }\n }\n}\n\n/**\n * What {@link createLayer} accepts.\n *\n * @internal\n */\nexport interface LayerOptions {\n /** The blend mode the whole layer draws with. */\n readonly blend: SpriteBlendName;\n /** The draw order; lower draws first. Derived from the sorting-layer index. */\n readonly order: number;\n /** How many sprites to pre-allocate for. */\n readonly capacity: number;\n /** A per-layer custom fragment shader, or `null`. */\n readonly customShader: Sprite2DCustomShader | null;\n}\n\n/**\n * Creates one Lite sprite layer.\n *\n * @remarks\n * The layer's pivot is pinned to the centre `[0.5, 0.5]`. Lite's sprite pipeline reads **one pivot\n * per layer** out of its uniform block (`lib/sprite/sprite-pipeline.js` lines 25 and 264-265) and\n * ignores `SpriteFrame.pivot` entirely — only the billboard family consumes that\n * (`lib/sprite/billboard-sprite.js` lines 166-167). ignifx therefore keeps the layer centred and\n * offsets each sprite's `positionPx` instead, which is what makes a per-frame pivot and\n * `SpriteRenderer.pivotOverride` possible at all.\n *\n * `depth` stays `\"none\"`: these layers are drawn by a `SpriteRenderer`, not hosted in the render\n * scene's depth buffer (`index.d.ts` 11877).\n *\n * @param atlas - The atlas every sprite in the layer draws from.\n * @param options - Blend, order, capacity, and an optional custom shader.\n * @returns The layer.\n *\n * @internal\n */\nexport function createLayer(atlas: SpriteAtlas, options: LayerOptions): Sprite2DLayer {\n return createSprite2DLayer(atlas, {\n blendMode: blendModeFor(options.blend),\n order: options.order,\n capacity: Math.max(1, options.capacity),\n depth: \"none\",\n pivot: [0.5, 0.5],\n ...(options.customShader === null ? {} : { customShader: options.customShader }),\n });\n}\n\n/**\n * A reusable `Sprite2DProps` record, so a per-frame sync allocates nothing.\n *\n * @remarks\n * `positionPx`, `sizePx`, and `color` are mutable tuples Lite reads and never retains\n * (`writeInstance` copies each component out — `lib/sprite/sprite-2d.js` lines 79-167), so one\n * scratch object can be rewritten and re-submitted every frame (coding standards §7).\n *\n * @internal\n */\nexport interface SpriteScratch {\n /** The props object handed to `addSprite2D`/`updateSprite2D`. */\n readonly props: Sprite2DProps;\n}\n\n/**\n * Builds the reusable props record a sync loop writes through.\n *\n * @returns A fresh scratch record; each sync system owns exactly one.\n *\n * @internal\n */\nexport function createSpriteScratch(): SpriteScratch {\n return {\n props: {\n positionPx: [0, 0],\n sizePx: [0, 0],\n color: [1, 1, 1, 1],\n frame: 0,\n rotation: 0,\n flipX: false,\n flipY: false,\n visible: true,\n },\n };\n}\n\n/**\n * Writes every field of the scratch props record.\n *\n * @param scratch - The reusable record.\n * @param xPx - The sprite's position, in layer pixels.\n * @param yPx - The sprite's position, in layer pixels.\n * @param widthPx - The drawn width, in pixels.\n * @param heightPx - The drawn height, in pixels.\n * @param frame - The atlas frame index.\n * @param rotation - The Lite rotation, in radians.\n * @param r - The red tint, `0` to `1`.\n * @param g - The green tint.\n * @param b - The blue tint.\n * @param a - The alpha.\n * @param flipX - Whether the sprite is mirrored horizontally.\n * @param flipY - Whether the sprite is mirrored vertically.\n * @param visible - Whether the sprite draws at all.\n *\n * @internal\n */\n// oxlint-disable-next-line max-params -- one call per sprite per frame; an options object would allocate.\nexport function writeScratch(\n scratch: SpriteScratch,\n xPx: number,\n yPx: number,\n widthPx: number,\n heightPx: number,\n frame: number,\n rotation: number,\n r: number,\n g: number,\n b: number,\n a: number,\n flipX: boolean,\n flipY: boolean,\n visible: boolean,\n): void {\n const props = scratch.props;\n props.positionPx[0] = xPx;\n props.positionPx[1] = yPx;\n const size = props.sizePx;\n if (size !== undefined) {\n size[0] = widthPx;\n size[1] = heightPx;\n }\n const color = props.color;\n if (color !== undefined) {\n color[0] = r;\n color[1] = g;\n color[2] = b;\n color[3] = a;\n }\n props.frame = frame;\n props.rotation = rotation;\n props.flipX = flipX;\n props.flipY = flipY;\n props.visible = visible;\n}\n\n/**\n * Adds a sprite described by the scratch record.\n *\n * @param layer - The layer to add to.\n * @param scratch - The reusable props record, already written.\n * @returns The stable handle.\n *\n * @internal\n */\nexport function addSprite(layer: Sprite2DLayer, scratch: SpriteScratch): Sprite2DHandle {\n return addSprite2D(layer, scratch.props);\n}\n\n/**\n * Applies the scratch record to an existing sprite.\n *\n * @param handle - The sprite to update.\n * @param scratch - The reusable props record, already written.\n *\n * @internal\n */\nexport function updateSprite(handle: Sprite2DHandle, scratch: SpriteScratch): void {\n updateSprite2D(handle, scratch.props);\n}\n\n/**\n * Removes a sprite, tolerating a handle whose sprite is already gone.\n *\n * @remarks\n * Lite removes by swapping the last sprite into the freed slot\n * (`lib/sprite/sprite-2d-handle.js`, `onRemoveIndex`), so **indices move** while handles do not.\n * Anything that maps a Lite sprite index back to an ignifx component has to apply the same\n * swap rule.\n *\n * @param handle - The sprite to remove.\n * @returns `true` when a sprite was removed.\n *\n * @internal\n */\nexport function removeSprite(handle: Sprite2DHandle): boolean {\n if (!isSprite2DHandleAlive(handle)) {\n return false;\n }\n removeSprite2D(handle);\n return true;\n}\n\n/**\n * Reads the dense index a handle currently occupies.\n *\n * @param handle - The sprite.\n * @returns The index, or `-1` when the sprite is gone.\n *\n * @internal\n */\nexport function spriteIndexOf(handle: Sprite2DHandle): number {\n return isSprite2DHandleAlive(handle) ? getSprite2DHandleIndex(handle) : -1;\n}\n\n/**\n * Removes every sprite from a layer, keeping the layer itself.\n *\n * @param layer - The layer to empty.\n *\n * @internal\n */\nexport function clearLayer(layer: Sprite2DLayer): void {\n clearSprite2DLayer(layer);\n}\n\n/**\n * Turns Y-sorting on or off for a layer.\n *\n * @remarks\n * Lite sorts **ascending** on `positionPx.y + bias` (`lib/sprite/sprite-2d-y-sort.js`, `keyAt` and\n * `comesBefore`). Layer pixels run +Y **down**, so a sprite higher up the screen has the smaller\n * key and draws first — behind — which is exactly the top-down painter's order ignifx wants.\n *\n * @param layer - The layer.\n * @param enabled - Whether to Y-sort.\n *\n * @internal\n */\nexport function setYSort(layer: Sprite2DLayer, enabled: boolean): void {\n if (enabled) {\n enableSprite2DYSort(layer);\n return;\n }\n disableSprite2DYSort(layer);\n}\n\n/**\n * Applies `orderInLayer` as a Y-sort bias on one sprite.\n *\n * @remarks\n * The bias is added to the sprite's pixel Y before sorting, so it has to be large enough to beat\n * any plausible Y difference: {@link Y_SORT_BIAS_STEP} pixels per unit of `orderInLayer`. A\n * negative `orderInLayer` therefore pulls a sprite behind its neighbours and a positive one pushes\n * it in front, which is what `orderInLayer` means when Y-sort is off too.\n *\n * @param handle - The sprite.\n * @param orderInLayer - The component's `orderInLayer`.\n *\n * @internal\n */\nexport function setYSortOrder(handle: Sprite2DHandle, orderInLayer: number): void {\n setSprite2DYSortHandleBias(handle, orderInLayer * Y_SORT_BIAS_STEP);\n}\n\n/**\n * How many layer pixels one unit of `orderInLayer` is worth as a Y-sort bias.\n *\n * @remarks\n * A million pixels is 10 000 world metres at the default PPU of 100 — far larger than any 2D scene,\n * so `orderInLayer` always dominates world Y, and equal `orderInLayer` values fall back to Y.\n *\n * @internal\n */\nexport const Y_SORT_BIAS_STEP = 1_000_000;\n\n/**\n * Writes a layer's view: where the camera looks, how far in, and how it is turned.\n *\n * @remarks\n * `Sprite2DView.positionPx` is the layer-pixel point that lands at the viewport's **top-left**, not\n * its centre (`sprite2DWorldToScreenToRef` in `lib/sprite/sprite-2d-view.js` subtracts it before\n * scaling, and the vertex shader maps `v.x / screenWidth * 2 - 1`). {@link centreView} does the\n * centring arithmetic so callers can think in centres.\n *\n * @param view - The view to write.\n * @param xPx - The top-left corner, in layer pixels.\n * @param yPx - The top-left corner, in layer pixels.\n * @param zoom - The scale; must not be zero, which Lite rejects with a `RangeError`.\n * @param rotation - The view rotation, in radians.\n *\n * @internal\n */\nexport function writeView(view: Sprite2DView, xPx: number, yPx: number, zoom: number, rotation: number): void {\n view.positionPx[0] = xPx;\n view.positionPx[1] = yPx;\n view.zoom = zoom === 0 ? 1 : zoom;\n view.rotation = rotation;\n}\n\n/**\n * Centres a view on a layer-pixel point.\n *\n * @param view - The view to write.\n * @param centreXPx - The point to centre on, in layer pixels.\n * @param centreYPx - The point to centre on, in layer pixels.\n * @param widthPx - The viewport width, in pixels.\n * @param heightPx - The viewport height, in pixels.\n * @param zoom - The scale.\n * @param rotation - The view rotation, in radians.\n *\n * @internal\n */\n// oxlint-disable-next-line max-params -- called once per camera per frame; an options object would allocate.\nexport function centreView(\n view: Sprite2DView,\n centreXPx: number,\n centreYPx: number,\n widthPx: number,\n heightPx: number,\n zoom: number,\n rotation: number,\n): void {\n const safeZoom = zoom === 0 ? 1 : zoom;\n const inverse = 1 / safeZoom;\n const halfWidth = widthPx * 0.5 * inverse;\n const halfHeight = heightPx * 0.5 * inverse;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n view.positionPx[0] = centreXPx - halfWidth * cos - halfHeight * sin;\n view.positionPx[1] = centreYPx + halfWidth * sin - halfHeight * cos;\n view.zoom = safeZoom;\n view.rotation = rotation;\n}\n\n/**\n * Writes the layer-pixel bounds a view can currently see, for chunk culling.\n *\n * @param view - The view.\n * @param widthPx - The viewport width.\n * @param heightPx - The viewport height.\n * @param out - The bounds to write.\n * @returns `out`.\n *\n * @internal\n */\nexport function visibleBounds<TOut extends Bounds2D>(\n view: Sprite2DView,\n widthPx: number,\n heightPx: number,\n out: TOut,\n): TOut {\n return getSprite2DVisibleBoundsToRef(view, widthPx, heightPx, out);\n}\n\n/**\n * A mutable point in a layer's pixel space.\n *\n * @internal\n */\nexport interface LayerPoint {\n /** The layer-space x. */\n x: number;\n /** The layer-space y. */\n y: number;\n}\n\n/**\n * Unprojects a viewport pixel into the layer-pixel space a layer's sprites live in.\n *\n * @param view - The layer's view.\n * @param screenXPx - The viewport x, from the left edge.\n * @param screenYPx - The viewport y, from the top edge.\n * @param out - The point to write: its `x` and `y` take the layer-space coordinates.\n * @returns `out`.\n *\n * @internal\n */\nexport function screenToLayer(view: Sprite2DView, screenXPx: number, screenYPx: number, out: LayerPoint): LayerPoint {\n return sprite2DScreenToWorldToRef(view, screenXPx, screenYPx, out);\n}\n\n/**\n * Picks the topmost sprite under a **layer-pixel** point.\n *\n * @remarks\n * This is the trap in Lite's picking API, and it is not in the declaration: despite the parameter\n * names, `pickSprite2D` compares `xPx`/`yPx` directly against each sprite's stored `positionPx` and\n * **never applies the layer's view** (`lib/sprite/picking/pick-sprite-2d.js` lines 26-27). A\n * viewport pixel therefore has to be unprojected with {@link screenToLayer} first, per layer,\n * because a world layer and a screen-space layer carry different views.\n *\n * @param layers - The layers to test, in draw order.\n * @param xPx - The layer-space x.\n * @param yPx - The layer-space y.\n * @returns The hit, or `null`.\n *\n * @internal\n */\nexport function pickSprite(layers: readonly Sprite2DLayer[], xPx: number, yPx: number): SpritePickInfo | null {\n return pickSprite2D(layers, xPx, yPx);\n}\n\n/**\n * Compiles a WGSL fragment body into a layer shader (`index.d.ts` 3160).\n *\n * @remarks\n * The body is compiled on demand and the result is pure data, so one compiled shader can back many\n * layers. `Sprite2DLayerOptions.customShader` is only read at creation and\n * `Sprite2DLayer.customShader` is `readonly` — a layer's shader cannot be swapped later.\n *\n * @param fragment - The WGSL fragment body.\n * @returns The compiled shader.\n *\n * @internal\n */\nexport function compileLayerShader(fragment: string): Sprite2DCustomShader {\n return createSprite2DCustomShader({ fragment });\n}\n\n/**\n * Writes a custom shader's `fx.params` vec4 for one layer.\n *\n * @param layer - The layer.\n * @param x - The first component.\n * @param y - The second component.\n * @param z - The third component.\n * @param w - The fourth component.\n *\n * @internal\n */\nexport function setShaderParams(layer: Sprite2DLayer, x: number, y: number, z: number, w: number): void {\n setSprite2DShaderParams(layer, [x, y, z, w]);\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\n\n/**\n * The sorting-layer table (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * `@ignifx/core` owns the `sortingLayers` settings section — an ordered list of names, back to\n * front — but ships no resolver for it, the way `layers/layer-table.ts` resolves the `layers`\n * section. This is that resolver: it turns a name into the index the Lite layer's `order` is\n * derived from, and it refuses a name the project never declared instead of silently drawing on\n * the wrong layer.\n */\n\n/**\n * The sorting layer a component that names none draws on.\n *\n * @public\n */\nexport const DEFAULT_SORTING_LAYER = \"Default\";\n\n/**\n * How far apart two sorting layers' Lite `order` values sit.\n *\n * @remarks\n * A gap of 1000 leaves room for the per-(atlas, blend, space) sub-layers a single sorting layer\n * expands into: one sorting layer holding sprites from twelve atlases in three blend modes still\n * fits inside its slice without reaching the next layer's.\n *\n * @public\n */\nexport const SORTING_LAYER_ORDER_STEP = 1000;\n\n/**\n * Resolves sorting-layer names to draw orders.\n *\n * @example\n * ```ts\n * const layers = new SortingLayerTable([\"Background\", \"Default\", \"Foreground\"]);\n * layers.indexOf(\"Foreground\"); // 2\n * ```\n *\n * @public\n */\nexport class SortingLayerTable {\n readonly #names: readonly string[];\n\n readonly #indices: ReadonlyMap<string, number>;\n\n /**\n * Builds the table from the project's `sortingLayers` section.\n *\n * @param names - The names, back to front. An empty list falls back to `[\"Default\"]`.\n */\n constructor(names: readonly string[]) {\n const resolved = names.length === 0 ? [DEFAULT_SORTING_LAYER] : names;\n const indices = new Map<string, number>();\n for (let index = 0; index < resolved.length; index += 1) {\n const name = resolved[index];\n if (name !== undefined && !indices.has(name)) {\n indices.set(name, index);\n }\n }\n if (!indices.has(DEFAULT_SORTING_LAYER)) {\n // A project may rename every layer; `Default` still has to resolve, because it is what an\n // unconfigured `SpriteRenderer` carries.\n indices.set(DEFAULT_SORTING_LAYER, 0);\n }\n this.#names = resolved;\n this.#indices = indices;\n }\n\n /**\n * The layer names, back to front.\n *\n * @returns The names.\n */\n get names(): readonly string[] {\n return this.#names;\n }\n\n /**\n * Resolves a name to its index.\n *\n * @param name - The sorting layer name.\n * @returns The index, or `-1` when the project declares no such layer.\n */\n indexOf(name: string): number {\n return this.#indices.get(name) ?? -1;\n }\n\n /**\n * Resolves a name to its index and refuses to guess.\n *\n * @param name - The sorting layer name.\n * @returns The index.\n * @throws IgnifxError with code `IGX-1107` when the project declares no such layer.\n */\n require(name: string): number {\n const index = this.#indices.get(name);\n if (index === undefined) {\n throw twoDError(TwoDErrorCode.unknownSortingLayer, `${name} is not a declared sorting layer.`, {\n context: { sortingLayer: name },\n hint: `Add it to the sortingLayers settings section. Declared: ${this.#names.join(\", \")}.`,\n });\n }\n return index;\n }\n\n /**\n * The Lite `Sprite2DLayer.order` a sorting layer's sub-layers start at.\n *\n * @param name - The sorting layer name.\n * @returns The base order.\n * @throws IgnifxError with code `IGX-1107` when the project declares no such layer.\n */\n orderOf(name: string): number {\n return this.require(name) * SORTING_LAYER_ORDER_STEP;\n }\n}\n","import {\n asset,\n bool,\n color,\n Component,\n createDefaults,\n defineSchema,\n enumOf,\n i32,\n optional,\n str,\n vec2,\n} from \"@ignifx/core\";\nimport { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport { SPRITE_BLEND_MODES } from \"../lite/sprite-layer.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport type { SpriteBlendName } from \"../lite/sprite-layer.js\";\nimport type { LiteSprite2DHandle } from \"../lite/types.js\";\nimport type { AssetHandle, ColorLike, ComponentHooks, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `SpriteRenderer` (`docs/architecture/11-2d-toolkit.md` §2.2): one sprite drawn from one frame of\n * one atlas.\n *\n * The component holds a single Lite sprite handle inside the layer that matches its\n * (sorting layer, atlas, blend mode, screen-space) key. It creates nothing itself: the 2D sync\n * system owns every layer, so the component only records which layer it belongs in and lets the\n * system reconcile that against the layer it is currently in.\n */\n\n/**\n * The layer key a sprite belongs to.\n *\n * @remarks\n * Two sprites share a Lite layer exactly when all four parts match. The atlas is part of the key\n * because a `Sprite2DLayer` is bound to one atlas for its whole life (`index.d.ts` 11885,\n * `readonly atlas`), and the blend mode is part of it for the same reason (`readonly blendMode`).\n *\n * @public\n */\nexport interface SpriteLayerKey {\n /** The sorting layer's name. */\n readonly sortingLayer: string;\n /** The atlas every sprite in the layer draws from. */\n readonly atlas: SpriteAtlasAsset;\n /** The blend mode. */\n readonly blend: SpriteBlendName;\n /** Whether the layer keeps the identity view instead of following the `Camera2D`. */\n readonly screenSpace: boolean;\n}\n\n/**\n * A sprite.\n *\n * @remarks\n * The `sprite` field is an atlas handle; the frame inside it comes from the address's `#frame:`\n * fragment when there is one, and otherwise from {@link SpriteRenderer.frame}, which game code and\n * `SpriteAnimator` both write. A sprite whose atlas has not finished loading draws nothing and\n * costs nothing.\n *\n * @example\n * ```ts\n * const hero = app.world.createEntity({ name: \"hero\" });\n * const sprite = hero.addComponent(SpriteRenderer);\n * sprite.sprite = app.assets.load<SpriteAtlasAsset>(\"2d/hero.atlas.json\").retain();\n * sprite.sortingLayer = \"Default\";\n * ```\n *\n * @public\n */\nexport class SpriteRenderer extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/SpriteRenderer\";\n\n /** Several sprites may share an entity — a character and its shadow, for instance. */\n static allowMultiple = true;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = spriteRendererSchema();\n\n /** The atlas this sprite draws a frame of. */\n declare sprite: AssetHandle<SpriteAtlasAsset> | null;\n\n /** The tint multiplied into every texel. */\n declare color: ColorLike;\n\n /** Whether the sprite is mirrored horizontally. */\n declare flipX: boolean;\n\n /** Whether the sprite is mirrored vertically. */\n declare flipY: boolean;\n\n /** Which sorting layer the sprite draws on. */\n declare sortingLayer: string;\n\n /** The sub-order within the sorting layer; higher draws in front. */\n declare orderInLayer: number;\n\n /** How the sprite's colour combines with what is behind it. */\n declare blend: SpriteBlendName;\n\n /** The pivot in `[0, 1]` of the frame, overriding the frame's own; `null` uses the frame's. */\n declare pivotOverride: Vec2Like | null;\n\n /** Whether the sprite keeps the identity view instead of following the `Camera2D`. */\n declare screenSpace: boolean;\n\n /** Whether `app.twoD.pickAt` considers this sprite. */\n declare pickable: boolean;\n\n /** The atlas frame index drawn; `SpriteAnimator` writes this. */\n #frame = 0;\n\n /** The Lite handle, or `null` while the sprite is not in a layer. */\n #handle: LiteSprite2DHandle | null = null;\n\n /** The key of the layer the handle currently lives in, or `null`. */\n #layerKey: string | null = null;\n\n /** The `worldMatrixVersion` the last sync wrote at, so a still entity costs one comparison. */\n #syncedMatrixVersion = -1;\n\n /** Whether a field changed since the last sync. */\n #isDirty = true;\n\n /** Whether a static entity has been synced at least once. */\n #hasSyncedStatic = false;\n\n /** The visibility the last sync wrote, so toggling `enabled` reaches Lite. */\n #appliedVisible = false;\n\n /** The world AABB the last sync computed, as `minX, minY, maxX, maxY` in metres. */\n readonly #bounds = new Float64Array(4);\n\n /**\n * Builds a sprite with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(SpriteRenderer.schema));\n }\n\n /**\n * Resets the sync shadow state, so a recycled component does not inherit the previous one's.\n */\n onAttach(): void {\n this.#syncedMatrixVersion = -1;\n this.#hasSyncedStatic = false;\n this.#appliedVisible = false;\n this.#isDirty = true;\n }\n\n /**\n * Marks the sprite for removal from its layer. The sync system does the removal, because it owns\n * the layer.\n */\n onDetach(): void {\n this.#isDirty = true;\n }\n\n /**\n * The atlas frame drawn.\n *\n * @returns The frame index.\n */\n get frame(): number {\n return this.#frame;\n }\n\n /**\n * Sets the atlas frame drawn, marking the sprite for the next sync when it changes.\n *\n * @param value - The frame index.\n */\n set frame(value: number) {\n if (value !== this.#frame) {\n this.#frame = value;\n this.#isDirty = true;\n }\n }\n\n /**\n * The Babylon Lite objects the component uses. Unstable escape hatch\n * (`CONSTITUTION.md` §3.4).\n *\n * @returns The sprite handle, or `null` when the sprite is not in a layer.\n */\n get lite(): { readonly sprite: LiteSprite2DHandle | null } {\n return { sprite: this.#handle };\n }\n\n /**\n * The sprite's world-space axis-aligned bounding box, for coarse queries\n * (`docs/architecture/11-2d-toolkit.md` §5).\n *\n * @remarks\n * The box is the one the last sync computed, so it is a frame behind a sprite that has just\n * moved, and it is the origin-sized empty box until the sprite has been synced once. It ignores\n * rotation: a rotated sprite reports the box of its unrotated quad, which is the cheap\n * conservative answer only for rotations that are multiples of a quarter turn.\n *\n * @returns A freshly allocated box in world metres.\n */\n get bounds(): { readonly min: Vec2Like; readonly max: Vec2Like } {\n return {\n min: { x: this.#bounds[0] ?? 0, y: this.#bounds[1] ?? 0 },\n max: { x: this.#bounds[2] ?? 0, y: this.#bounds[3] ?? 0 },\n };\n }\n\n /**\n * The loaded atlas, or `null` while it is still loading or failed.\n *\n * @returns The atlas.\n */\n get atlas(): SpriteAtlasAsset | null {\n const handle = this.sprite;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * Whether anything about this sprite needs writing to Lite this frame.\n *\n * @param isStatic - Whether the owning entity is marked static.\n * @param matrixVersion - The entity transform's `worldMatrixVersion`.\n * @returns `true` when the sync system must write the sprite.\n *\n * @internal\n */\n needsSync(isStatic: boolean, matrixVersion: number): boolean {\n if (this.#isDirty) {\n return true;\n }\n // Enabling or disabling the component, or anything above it in the hierarchy, changes nothing\n // the transform version or the dirty flag can see — but it does change what Lite must draw.\n if (this.isEnabledInHierarchy !== this.#appliedVisible) {\n return true;\n }\n if (isStatic) {\n return !this.#hasSyncedStatic;\n }\n return matrixVersion !== this.#syncedMatrixVersion;\n }\n\n /**\n * Records that the sync system has written this sprite.\n *\n * @param isStatic - Whether the owning entity is marked static.\n * @param matrixVersion - The transform version written at.\n * @param minX - The world AABB, in metres.\n * @param minY - The world AABB, in metres.\n * @param maxX - The world AABB, in metres.\n * @param maxY - The world AABB, in metres.\n *\n * @internal\n */\n // oxlint-disable-next-line max-params -- once per moved sprite per frame; an options object would allocate.\n markSynced(isStatic: boolean, matrixVersion: number, minX: number, minY: number, maxX: number, maxY: number): void {\n this.#isDirty = false;\n this.#appliedVisible = this.isEnabledInHierarchy;\n this.#hasSyncedStatic = isStatic;\n this.#syncedMatrixVersion = matrixVersion;\n this.#bounds[0] = minX;\n this.#bounds[1] = minY;\n this.#bounds[2] = maxX;\n this.#bounds[3] = maxY;\n }\n\n /**\n * Forces the next sync to rewrite this sprite.\n *\n * @internal\n */\n invalidate(): void {\n this.#isDirty = true;\n this.#hasSyncedStatic = false;\n }\n\n /**\n * The Lite handle and the key of the layer holding it.\n *\n * @returns The placement, or `null` when the sprite is not in a layer.\n *\n * @internal\n */\n placement(): { readonly handle: LiteSprite2DHandle; readonly key: string } | null {\n const handle = this.#handle;\n const key = this.#layerKey;\n return handle === null || key === null ? null : { handle, key };\n }\n\n /**\n * Records the layer the sync system put this sprite in.\n *\n * @param handle - The Lite handle, or `null` when the sprite was removed.\n * @param key - The layer key, or `null`.\n *\n * @internal\n */\n setPlacement(handle: LiteSprite2DHandle | null, key: string | null): void {\n this.#handle = handle;\n this.#layerKey = key;\n }\n}\n\n/**\n * The `SpriteRenderer` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction spriteRendererSchema(): Schema {\n return defineSchema({\n sprite: asset(SpriteAtlasAsset, { tooltip: \"The atlas this sprite draws a frame of.\" }),\n color: color(\"#ffffffff\", { tooltip: \"Tint multiplied into every texel.\" }),\n flipX: bool(false, { tooltip: \"Mirror horizontally.\" }),\n flipY: bool(false, { tooltip: \"Mirror vertically.\" }),\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Which sorting layer the sprite draws on.\" }),\n orderInLayer: i32(0, { tooltip: \"Sub-order within the sorting layer; higher draws in front.\" }),\n blend: enumOf(SPRITE_BLEND_MODES, \"alpha\", { tooltip: \"How the colour combines with the background.\" }),\n pivotOverride: optional(vec2(), { tooltip: \"Overrides the frame's own pivot, in [0,1] of the frame.\" }),\n screenSpace: bool(false, { tooltip: \"Keep the identity view instead of following the Camera2D.\" }),\n pickable: bool(true, { tooltip: \"Whether app.twoD.pickAt considers this sprite.\" }),\n });\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\n\n/**\n * The `ignifx.spriteanimation` document — the `.spriteanim.json` file that names an atlas and the\n * clips cut out of its frames (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `11-2d-toolkit.md` §2.4).\n *\n * A clip lists frame names explicitly, or names the first and last frame of a contiguous run in the\n * atlas. ignifx drives these on its own clock in `PostUpdate`, not on Lite's\n * `SpriteAnimationManager`, so `timeScale`, pause, and frame events behave exactly as they do for\n * 3D animation (ADR-0003).\n */\n\n/**\n * The `format` discriminator every `.spriteanim.json` document carries.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_FORMAT = \"ignifx.spriteanimation\";\n\n/**\n * The document version this build reads and writes.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_FORMAT_VERSION = 1;\n\n/**\n * The asset type name the loader registers.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_ASSET_TYPE = \"spriteanimation\";\n\n/**\n * The address suffixes that select the sprite-animation loader.\n *\n * @public\n */\nexport const SPRITE_ANIMATION_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".spriteanim.json\"]);\n\n/**\n * A frame event: a name emitted on `SpriteAnimator.onEvent` when the clip reaches a frame.\n *\n * @public\n */\nexport interface SpriteAnimationEvent {\n /** The zero-based index **within the clip**, not within the atlas. */\n readonly frame: number;\n /** The name emitted on `SpriteAnimator.onEvent`. */\n readonly name: string;\n}\n\n/**\n * One clip: an ordered run of atlas frames with a rate and a loop flag.\n *\n * @remarks\n * A clip names its frames one of two ways, and they mean different things.\n *\n * - `frames` is an explicit **list of frame names**, played in the order written. Anything the\n * atlas does not carry is dropped, and the frames need not be adjacent in the atlas.\n * - `from`/`to` is an **index range over the atlas**, not a pair of endpoints joined by name. Both\n * names are resolved to their atlas indices and *every index between them is played*, in atlas\n * order, endpoints included. So a range whose endpoints are not adjacent in the sheet plays\n * whatever the packer happened to put between them — a `from: \"run_0\"`, `to: \"run_5\"` over an\n * atlas ordered `run_0, idle_0, run_1, …` plays `idle_0` too. Use `frames` whenever the run is\n * not contiguous in the atlas.\n * - `to` before `from` is legal and plays the range backwards.\n *\n * @public\n */\nexport interface SpriteClipDefinition {\n /** The clip's name, unique within the document; what `SpriteAnimator.play` takes. */\n readonly name: string;\n /**\n * The atlas frame names, in play order; they need not be adjacent in the atlas. Absent or empty\n * when `from`/`to` name a range instead.\n */\n readonly frames?: readonly string[];\n /**\n * The atlas frame whose **index** starts the range, when `frames` is absent. The clip plays every\n * atlas index from here to `to`, so the two must bracket a contiguous run in the sheet.\n */\n readonly from?: string;\n /**\n * The atlas frame whose **index** ends the range, inclusive. An index below `from`'s plays the\n * range backwards.\n */\n readonly to?: string;\n /** Frames per second. Defaults to `12`. */\n readonly fps?: number;\n /** Whether the clip restarts at its end. Defaults to `true`. */\n readonly loop?: boolean;\n /** Events fired as the clip passes a frame. */\n readonly events?: readonly SpriteAnimationEvent[];\n}\n\n/**\n * The parsed `.spriteanim.json` document.\n *\n * @public\n */\nexport interface SpriteAnimationDefinition {\n /** Always `\"ignifx.spriteanimation\"`. */\n readonly format: typeof SPRITE_ANIMATION_FORMAT;\n /** Always `1` in this build. */\n readonly formatVersion: number;\n /** The address of the `.atlas.json` the clips index into; empty uses the renderer's own atlas. */\n readonly atlas: string;\n /** The clips, in declaration order; the first is the default when the component names none. */\n readonly clips: readonly SpriteClipDefinition[];\n}\n\n/**\n * What {@link defineSpriteAnimation} accepts.\n *\n * @public\n */\nexport interface SpriteAnimationInput {\n /** Always `\"ignifx.spriteanimation\"` when present. */\n readonly format?: string;\n /** The document version. */\n readonly formatVersion?: number;\n /** The address of the `.atlas.json` the clips index into. */\n readonly atlas?: string;\n /** The clips. */\n readonly clips: readonly SpriteClipDefinition[];\n}\n\n/**\n * The frames-per-second a clip that declares none plays at.\n *\n * @public\n */\nexport const DEFAULT_CLIP_FPS = 12;\n\n/**\n * Fills in the defaults of an animation document and checks the invariants the animator relies on.\n *\n * @param input - The document, as authored or as an importer emitted it.\n * @param address - What to name in an error; defaults to `\"<inline>\"`.\n * @returns The complete document.\n * @throws IgnifxError with code `IGX-1104` when the format tag, the version, or a clip is wrong.\n *\n * @public\n */\nexport function defineSpriteAnimation(input: SpriteAnimationInput, address = \"<inline>\"): SpriteAnimationDefinition {\n const fail = (reason: string): never => {\n throw twoDError(\n TwoDErrorCode.invalidAnimationFile,\n `${address} is not a readable ignifx.spriteanimation document: ${reason}.`,\n { context: { file: address }, hint: \"Check the format, version, and clip fields.\" },\n );\n };\n if (input.format !== undefined && input.format !== SPRITE_ANIMATION_FORMAT) {\n fail(`its format is ${input.format}, not ${SPRITE_ANIMATION_FORMAT}`);\n }\n if (input.formatVersion !== undefined && input.formatVersion !== SPRITE_ANIMATION_FORMAT_VERSION) {\n fail(\n `its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(SPRITE_ANIMATION_FORMAT_VERSION)}`,\n );\n }\n if (!Array.isArray(input.clips) || input.clips.length === 0) {\n fail(\"it declares no clips\");\n }\n const seen = new Set<string>();\n for (let index = 0; index < input.clips.length; index += 1) {\n const clip = input.clips[index];\n if (clip === undefined || typeof clip.name !== \"string\" || clip.name === \"\") {\n fail(`clip ${String(index)} has no name`);\n continue;\n }\n if (seen.has(clip.name)) {\n fail(`two clips are named ${clip.name}`);\n }\n seen.add(clip.name);\n const hasList = clip.frames !== undefined && clip.frames.length > 0;\n const hasRange = typeof clip.from === \"string\" && typeof clip.to === \"string\";\n if (!hasList && !hasRange) {\n fail(`clip ${clip.name} names neither a frame list nor a from/to range`);\n }\n if (clip.fps !== undefined && !(clip.fps > 0)) {\n fail(`clip ${clip.name} has a non-positive fps`);\n }\n }\n return {\n format: SPRITE_ANIMATION_FORMAT,\n formatVersion: SPRITE_ANIMATION_FORMAT_VERSION,\n atlas: input.atlas ?? \"\",\n clips: input.clips,\n };\n}\n\n/**\n * Resolves a clip's frame names into atlas frame indices.\n *\n * @remarks\n * `frames` resolves name by name and skips what the atlas does not carry. `from`/`to` resolves both\n * endpoints to atlas **indices** and walks every index between them — ascending or descending — so\n * a range over non-adjacent frames plays everything the packer put in between\n * ({@link SpriteClipDefinition}).\n *\n * @param clip - The clip to resolve.\n * @param indexOf - Maps an atlas frame name to its index, or `-1` when the atlas has no such frame.\n * @returns The indices in play order; empty when the clip names nothing the atlas has.\n *\n * @public\n */\nexport function resolveClipFrames(clip: SpriteClipDefinition, indexOf: (name: string) => number): readonly number[] {\n const list = clip.frames;\n if (list !== undefined && list.length > 0) {\n const out: number[] = [];\n for (let index = 0; index < list.length; index += 1) {\n const name = list[index];\n const resolved = name === undefined ? -1 : indexOf(name);\n if (resolved >= 0) {\n out.push(resolved);\n }\n }\n return out;\n }\n const first = clip.from === undefined ? -1 : indexOf(clip.from);\n const last = clip.to === undefined ? -1 : indexOf(clip.to);\n if (first < 0 || last < 0) {\n return [];\n }\n const out: number[] = [];\n const step = last >= first ? 1 : -1;\n for (let frame = first; step > 0 ? frame <= last : frame >= last; frame += step) {\n out.push(frame);\n }\n return out;\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { resolveClipFrames, SPRITE_ANIMATION_ASSET_TYPE, DEFAULT_CLIP_FPS } from \"./definition.js\";\nimport type { SpriteAnimationDefinition, SpriteAnimationEvent, SpriteClipDefinition } from \"./definition.js\";\nimport type { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\n\n/**\n * The value a `.spriteanim.json` address loads to: the parsed document plus, once the atlas it\n * names has loaded, every clip resolved to atlas frame indices\n * (`docs/architecture/11-2d-toolkit.md` §2.4).\n */\n\n/**\n * One clip, resolved against an atlas.\n *\n * @public\n */\nexport interface SpriteClip {\n /** The clip's name. */\n readonly name: string;\n /** The atlas frame indices, in play order. */\n readonly frames: readonly number[];\n /** Frames per second. */\n readonly fps: number;\n /** Whether the clip restarts at its end. */\n readonly loop: boolean;\n /** Events fired as the clip passes a frame. */\n readonly events: readonly SpriteAnimationEvent[];\n /** How long one pass through the clip takes, in seconds. */\n readonly durationSeconds: number;\n}\n\n/**\n * A loaded sprite-animation document.\n *\n * @remarks\n * Resolution needs an atlas, and a document may be loaded before, after, or without one. The asset\n * therefore keeps the parsed clips and resolves them lazily the first time an atlas is offered;\n * `SpriteAnimator` offers its renderer's atlas. Under a headless app everything here works\n * unchanged, which is what makes animation timing testable with `app.step`.\n *\n * @example\n * ```ts\n * const clips = await app.assets.load<SpriteAnimationAsset>(\"2d/hero.spriteanim.json\").promise;\n * clips.clipNames(); // [\"idle\", \"run\"]\n * ```\n *\n * @public\n */\nexport class SpriteAnimationAsset {\n /** The type name the asset service registers animation documents under. */\n static assetType: string = SPRITE_ANIMATION_ASSET_TYPE;\n\n /** The address the document was loaded from. */\n readonly address: string;\n\n /** The parsed document. */\n readonly definition: SpriteAnimationDefinition;\n\n /** The atlas address the document names, already resolved against its own address. */\n readonly atlasAddress: string;\n\n #resolved: ReadonlyMap<string, SpriteClip> | null = null;\n\n #resolvedAgainst: SpriteAtlasAsset | null = null;\n\n /**\n * Wraps a parsed document. The `spriteanimation` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The parsed document.\n * @param atlasAddress - The atlas address, resolved against `address`.\n *\n * @internal\n */\n constructor(address: string, definition: SpriteAnimationDefinition, atlasAddress: string) {\n this.address = address;\n this.definition = definition;\n this.atlasAddress = atlasAddress;\n }\n\n /**\n * Every clip name, in declaration order.\n *\n * @returns A freshly allocated array.\n */\n clipNames(): readonly string[] {\n const names: string[] = [];\n for (let index = 0; index < this.definition.clips.length; index += 1) {\n const clip = this.definition.clips[index];\n if (clip !== undefined) {\n names.push(clip.name);\n }\n }\n return names;\n }\n\n /**\n * The name of the clip a component that names none plays.\n *\n * @returns The first clip's name, or `\"\"` when the document is empty.\n */\n get defaultClipName(): string {\n return this.definition.clips[0]?.name ?? \"\";\n }\n\n /**\n * Resolves every clip's frame names against an atlas.\n *\n * @remarks\n * The result is cached against the atlas it was resolved with, so playing ten characters off one\n * atlas resolves once. Offering a different atlas re-resolves.\n *\n * @param atlas - The atlas the frame names index into.\n * @returns The clips, keyed by name.\n */\n resolve(atlas: SpriteAtlasAsset): ReadonlyMap<string, SpriteClip> {\n const cached = this.#resolved;\n if (cached !== null && this.#resolvedAgainst === atlas) {\n return cached;\n }\n const clips = new Map<string, SpriteClip>();\n const indexOf = (name: string): number => atlas.frameIndex(name);\n for (let index = 0; index < this.definition.clips.length; index += 1) {\n const declared = this.definition.clips[index];\n if (declared === undefined) {\n continue;\n }\n clips.set(declared.name, toClip(declared, resolveClipFrames(declared, indexOf)));\n }\n this.#resolved = clips;\n this.#resolvedAgainst = atlas;\n return clips;\n }\n\n /**\n * Looks a clip up, resolving against an atlas first.\n *\n * @param name - The clip name.\n * @param atlas - The atlas the frame names index into.\n * @returns The clip.\n * @throws IgnifxError with code `IGX-1108` when the document declares no such clip.\n */\n requireClip(name: string, atlas: SpriteAtlasAsset): SpriteClip {\n const clip = this.resolve(atlas).get(name);\n if (clip === undefined) {\n throw twoDError(TwoDErrorCode.unknownClip, `${this.address} declares no clip named ${name}.`, {\n context: { asset: this.address, clip: name },\n hint: `Known clips: ${this.clipNames().join(\", \")}.`,\n });\n }\n return clip;\n }\n}\n\n/**\n * Builds a resolved clip from a declaration and its frame indices.\n *\n * @param declared - The clip as the document wrote it.\n * @param frames - Its atlas frame indices.\n * @returns The clip.\n */\nfunction toClip(declared: SpriteClipDefinition, frames: readonly number[]): SpriteClip {\n const fps = declared.fps !== undefined && declared.fps > 0 ? declared.fps : DEFAULT_CLIP_FPS;\n return {\n name: declared.name,\n frames,\n fps,\n loop: declared.loop ?? true,\n events: declared.events ?? EMPTY_EVENTS,\n durationSeconds: frames.length / fps,\n };\n}\n\n/** The event list a clip that declares none carries. */\nconst EMPTY_EVENTS: readonly SpriteAnimationEvent[] = Object.freeze([]);\n","import { asset, bool, Component, createDefaults, defineSchema, f32, Signal, str } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\nimport { SpriteAnimationAsset } from \"./sprite-animation-asset.js\";\nimport type { SpriteClip } from \"./sprite-animation-asset.js\";\nimport type { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport type { AssetHandle, ComponentHooks, Schema } from \"@ignifx/core\";\n\n/**\n * `SpriteAnimator` (`docs/architecture/11-2d-toolkit.md` §2.4): plays a clip of atlas frames on the\n * `SpriteRenderer` sharing its entity.\n *\n * The clock is **ignifx's**, advanced in `PostUpdate` (ADR-0003), not Lite's\n * `SpriteAnimationManager`. That is what makes `app.time.timeScale`, `app.pause()`, and frame\n * events behave for a 2D character exactly as they do for a 3D one — and what makes the whole\n * thing testable with `app.step` under a headless app, where no sprite is drawn at all.\n */\n\n/**\n * What {@link SpriteAnimator.play} accepts.\n *\n * @public\n */\nexport interface PlayClipOptions {\n /** Whether to rewind a clip that is already playing. Defaults to `false`. */\n readonly restart?: boolean;\n}\n\n/**\n * A sprite animator.\n *\n * @example\n * ```ts\n * const animator = hero.addComponent(SpriteAnimator);\n * animator.animations = app.assets.load<SpriteAnimationAsset>(\"2d/hero.spriteanim.json\").retain();\n * animator.onEvent.connect((name) => { if (name === \"footstep\") playStep(); }, { owner: animator });\n * animator.play(\"run\");\n * ```\n *\n * @public\n */\nexport class SpriteAnimator extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/SpriteAnimator\";\n\n /** One animator per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = spriteAnimatorSchema();\n\n /** The document holding the clips. */\n declare animations: AssetHandle<SpriteAnimationAsset> | null;\n\n /** Which clip to start on; empty plays the document's first. */\n declare defaultClip: string;\n\n /** Whether the default clip starts as soon as the document has loaded. */\n declare playOnAwake: boolean;\n\n /** A multiplier on the clip's own frame rate. */\n declare speed: number;\n\n /** The clip currently playing, or `null`. */\n #clip: SpriteClip | null = null;\n\n /** How far into the clip playback is, in seconds. */\n #elapsed = 0;\n\n /** The clip frame index the last advance settled on. */\n #cursor = 0;\n\n /** Whether playback is running. */\n #isPlaying = false;\n\n /** Whether the default clip has been started already. */\n #hasAutoPlayed = false;\n\n /** The renderer this animator writes frames to; found lazily. */\n #renderer: SpriteRenderer | null = null;\n\n readonly #onClipEnded: Signal<string> = new Signal<string>();\n\n readonly #onEvent: Signal<string> = new Signal<string>();\n\n /**\n * Builds an animator with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(SpriteAnimator.schema));\n }\n\n /**\n * Clears playback state, so a recycled component does not inherit the previous one's.\n */\n onAttach(): void {\n this.#clip = null;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#isPlaying = false;\n this.#hasAutoPlayed = false;\n this.#renderer = null;\n }\n\n /**\n * Releases the signals' handlers.\n */\n onDetach(): void {\n this.#isPlaying = false;\n }\n\n /**\n * Emitted with a clip's name when a non-looping clip reaches its last frame.\n *\n * @returns The signal.\n */\n get onClipEnded(): Signal<string> {\n return this.#onClipEnded;\n }\n\n /**\n * Emitted with an event's name when playback passes the frame that declares it.\n *\n * @remarks\n * A looping clip fires each event once per pass. A clip advanced by more than one frame in a\n * single step — a long frame, or a high `speed` — fires every event it skipped over, in order,\n * so a footstep is never silently dropped.\n *\n * @returns The signal.\n */\n get onEvent(): Signal<string> {\n return this.#onEvent;\n }\n\n /**\n * Whether a clip is currently advancing.\n *\n * @returns `true` while playing.\n */\n get isPlaying(): boolean {\n return this.#isPlaying;\n }\n\n /**\n * The clip currently playing, or `null`.\n *\n * @returns The clip.\n */\n get clip(): SpriteClip | null {\n return this.#clip;\n }\n\n /**\n * The atlas frame index the animator last wrote.\n *\n * @returns The frame index, or `-1` when no clip is playing.\n */\n get frame(): number {\n return this.#clip?.frames[this.#cursor] ?? -1;\n }\n\n /**\n * How far into the clip playback is, in seconds.\n *\n * @returns The elapsed time.\n */\n get time(): number {\n return this.#elapsed;\n }\n\n /**\n * The loaded animation document, or `null` while it is still loading.\n *\n * @returns The document.\n */\n get asset(): SpriteAnimationAsset | null {\n const handle = this.animations;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * Starts a clip.\n *\n * @param name - The clip's name.\n * @param options - Whether to rewind a clip that is already playing.\n * @throws IgnifxError with code `IGX-1108` when the document declares no such clip.\n *\n * @example\n * ```ts\n * animator.play(\"run\", { restart: true });\n * ```\n */\n play(name: string, options?: PlayClipOptions): void {\n const clips = this.asset;\n const atlas = this.#atlas();\n if (clips === null || atlas === null) {\n // Nothing loaded yet; remember the intent so `advance` starts it on arrival.\n this.defaultClip = name;\n this.playOnAwake = true;\n this.#hasAutoPlayed = false;\n return;\n }\n const clip = clips.requireClip(name, atlas);\n if (this.#clip === clip && this.#isPlaying && options?.restart !== true) {\n return;\n }\n this.#clip = clip;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#isPlaying = clip.frames.length > 0;\n this.#writeFrame();\n }\n\n /**\n * Stops playback and rewinds to the clip's first frame.\n */\n stop(): void {\n this.#isPlaying = false;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#writeFrame();\n }\n\n /**\n * Suspends playback where it is; {@link SpriteAnimator.resume} continues from there.\n */\n pause(): void {\n this.#isPlaying = false;\n }\n\n /**\n * Continues a paused clip.\n */\n resume(): void {\n if (this.#clip !== null && this.#clip.frames.length > 0) {\n this.#isPlaying = true;\n }\n }\n\n /**\n * Advances playback by one frame's worth of scaled time. The animation system calls this in\n * `PostUpdate`.\n *\n * @remarks\n * `deltaSeconds` is `ctx.dt` in the `PostUpdate` phase, which is `time.deltaTime` — already\n * multiplied by `time.timeScale`; the 2D animation system skips the call while the app is paused\n * (`docs/architecture/01-lifecycle-and-time.md` §2). The animator does not consult the clock\n * itself, which is what makes it deterministic under `app.step`.\n *\n * @param deltaSeconds - The scaled frame delta.\n *\n * @internal\n */\n advance(deltaSeconds: number): void {\n this.#autoPlay();\n const clip = this.#clip;\n if (clip === null || !this.#isPlaying || clip.frames.length === 0) {\n return;\n }\n const rate = clip.fps * this.speed;\n if (rate <= 0) {\n return;\n }\n const count = clip.frames.length;\n const previous = this.#cursor;\n this.#elapsed += deltaSeconds;\n const raw = Math.floor(this.#elapsed * rate);\n let next = raw;\n let ended = false;\n if (raw >= count) {\n if (clip.loop) {\n next = raw % count;\n } else {\n next = count - 1;\n ended = true;\n }\n }\n if (next !== previous) {\n this.#emitEventsBetween(clip, previous, raw, count);\n this.#cursor = next;\n this.#writeFrame();\n }\n if (ended) {\n this.#isPlaying = false;\n this.#onClipEnded.emit(clip.name);\n }\n }\n\n /**\n * Starts the default clip once the document and the atlas have both arrived.\n */\n #autoPlay(): void {\n if (this.#hasAutoPlayed || !this.playOnAwake) {\n return;\n }\n const clips = this.asset;\n const atlas = this.#atlas();\n if (clips === null || atlas === null) {\n return;\n }\n const name = this.defaultClip === \"\" ? clips.defaultClipName : this.defaultClip;\n if (name === \"\") {\n this.#hasAutoPlayed = true;\n return;\n }\n const clip = clips.resolve(atlas).get(name);\n if (clip === undefined) {\n this.#hasAutoPlayed = true;\n throw twoDError(TwoDErrorCode.unknownClip, `${clips.address} declares no clip named ${name}.`, {\n context: { asset: clips.address, clip: name },\n hint: `Known clips: ${clips.clipNames().join(\", \")}.`,\n });\n }\n this.#hasAutoPlayed = true;\n this.#clip = clip;\n this.#elapsed = 0;\n this.#cursor = 0;\n this.#isPlaying = clip.frames.length > 0;\n this.#writeFrame();\n }\n\n /**\n * Fires every frame event between two clip positions, in order.\n *\n * @param clip - The playing clip.\n * @param from - The clip frame index playback was on.\n * @param toRaw - The unwrapped frame index playback reached.\n * @param count - How many frames the clip has.\n */\n #emitEventsBetween(clip: SpriteClip, from: number, toRaw: number, count: number): void {\n if (clip.events.length === 0) {\n return;\n }\n // A looping clip can pass every frame at most once per step's worth of wrapping; a\n // non-looping one stops at its last frame, and walking past it would fire that frame's events\n // again for every extra step the clamp swallowed.\n const reach = clip.loop ? count : count - 1 - from;\n const steps = Math.min(toRaw - from, reach);\n for (let step = 1; step <= steps; step += 1) {\n const frame = clip.loop ? (from + step) % count : from + step;\n for (let index = 0; index < clip.events.length; index += 1) {\n const event = clip.events[index];\n if (event !== undefined && event.frame === frame) {\n this.#onEvent.emit(event.name);\n }\n }\n }\n }\n\n /**\n * Writes the current clip frame onto the renderer.\n */\n #writeFrame(): void {\n const renderer = this.#findRenderer();\n const frame = this.#clip?.frames[this.#cursor];\n if (renderer !== null && frame !== undefined) {\n renderer.frame = frame;\n }\n }\n\n /**\n * The atlas the clips index into: the sibling renderer's.\n *\n * @returns The atlas, or `null`.\n */\n #atlas(): SpriteAtlasAsset | null {\n return this.#findRenderer()?.atlas ?? null;\n }\n\n /**\n * The `SpriteRenderer` on this entity, cached once found.\n *\n * @returns The renderer, or `null` when the entity has none.\n */\n #findRenderer(): SpriteRenderer | null {\n const cached = this.#renderer;\n if (cached !== null && !cached.isDestroyed) {\n return cached;\n }\n const found = this.entity.getComponent(SpriteRenderer);\n this.#renderer = found;\n return found;\n }\n}\n\n/**\n * The `SpriteAnimator` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction spriteAnimatorSchema(): Schema {\n return defineSchema({\n animations: asset(SpriteAnimationAsset, { tooltip: \"The .spriteanim.json document holding the clips.\" }),\n defaultClip: str(\"\", { tooltip: \"Which clip to start on; empty plays the document's first.\" }),\n playOnAwake: bool(true, { tooltip: \"Start the default clip as soon as the document has loaded.\" }),\n speed: f32(1, { min: 0, tooltip: \"A multiplier on each clip's own frame rate.\" }),\n });\n}\n","import { SpriteAnimator } from \"./sprite-animator.js\";\nimport type { AnimatedTilemapSink } from \"../tilemap/animated-tiles.js\";\nimport type { System, SystemContext } from \"@ignifx/core\";\n\n/**\n * The 2D animation system (`docs/architecture/01-lifecycle-and-time.md` §3, ADR-0003).\n *\n * It runs in `PostUpdate` — after `update`, before `PreRender` — which is where every animation in\n * ignifx advances, so a `lateUpdate` sees the posed frame and the render sync writes it in the same\n * frame it was computed. It advances every `SpriteAnimator` and every animated tile on the same\n * `ctx.dt`, which is `time.deltaTime`, already scaled by `time.timeScale`. Systems keep running\n * while the app is paused and `dt` is **not** zeroed then (only scripts are filtered by\n * `updateWhenPaused`), so the system checks `time.paused` itself: sprite animation does not advance\n * while paused (`01-lifecycle-and-time.md` §7). Phase 6 shipped without this check and the sprites\n * kept animating under a pause menu.\n */\n\n/**\n * The `PostUpdate` order the 2D animation system runs at.\n *\n * @remarks\n * `PostUpdate` is empty today — no core or extension system registers there — so `0` is the middle\n * of an open phase. Anything a game adds later can sit either side of it by choosing a sign.\n *\n * @public\n */\nexport const TWO_D_ANIMATION_ORDER = 0;\n\n/**\n * Advances sprite animation on ignifx's clock.\n *\n * @public\n */\nexport class TwoDAnimationSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name = \"ignifx/2d-animation\";\n\n readonly #tilemaps: AnimatedTilemapSink;\n\n /**\n * Builds the system.\n *\n * @param tilemaps - Advances animated tiles on the same clock.\n */\n constructor(tilemaps: AnimatedTilemapSink) {\n this.#tilemaps = tilemaps;\n }\n\n /**\n * Advances every animator and every animated tile.\n *\n * @param ctx - The world, clock, phase, and delta.\n */\n update(ctx: SystemContext): void {\n if (ctx.time.paused) {\n return;\n }\n const animators = ctx.world.components(SpriteAnimator);\n for (let index = 0; index < animators.length; index += 1) {\n const animator = animators[index];\n if (animator !== undefined && animator.isEnabledInHierarchy) {\n animator.advance(ctx.dt);\n }\n }\n this.#tilemaps.advanceAnimatedTiles(ctx.world, ctx.dt);\n }\n}\n","import { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { defineSpriteAtlas } from \"./definition.js\";\nimport type { SpriteAtlasDefinition, SpriteFrameDefinition } from \"./definition.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The atlas importers: pure functions that turn a third-party packer document — or a plain grid\n * description — into an `ignifx.spriteatlas` document\n * (`docs/architecture/11-2d-toolkit.md` §2.3).\n *\n * Nothing here does I/O. The CLI (`ignifx import atlas`) reads the file, hands the parsed JSON to\n * one of these functions, and writes the returned document out; a game can equally call them at\n * build time from a script. Every frame rectangle stays in **image pixels with a top-left origin**,\n * which is what both TexturePacker and Aseprite emit and what the loader expects.\n *\n * Untrusted input is typed `unknown` and narrowed with the local guards below rather than asserted\n * (coding standards §5.2), so a malformed document fails with `IGX-1109` instead of producing an\n * atlas that only breaks later, at load.\n */\n\n/** The pivot a frame gets when neither the packer nor the caller names one. */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/** The prefix {@link gridAtlas} names frames with when the caller supplies none. */\nconst DEFAULT_GRID_NAME_PREFIX = \"tile\";\n\n/** The name a frame falls back to when normalisation leaves nothing usable. */\nconst FALLBACK_FRAME_NAME = \"frame\";\n\n/** A rectangle as every packer writes it: left, top, width, height, in image pixels. */\ninterface Rect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n}\n\n/** One raw frame entry paired with the key it was found under (hash key or `filename`). */\ninterface RawFrameEntry {\n readonly key: string;\n readonly entry: Record<string, unknown>;\n}\n\n/** A slice pivot lifted out of `meta.slices`, still in sprite-canvas pixels. */\ninterface SlicePivot {\n readonly frame: number;\n readonly bounds: Rect;\n readonly pivot: Vec2Like;\n}\n\n/**\n * Raises the one diagnostic these importers own.\n *\n * @param importer - The importer function's name, echoed into the message and the context.\n * @param reason - What about the document could not be read.\n * @param hint - The remedy sentence, when there is a specific one.\n * @throws IgnifxError with code `IGX-1109`, always.\n */\nfunction failImport(importer: string, reason: string, hint?: string): never {\n throw twoDError(TwoDErrorCode.unsupportedImport, `${importer} cannot read this document: ${reason}.`, {\n context: { importer },\n hint: hint ?? \"Re-export the atlas from the packer, or check that the document is the one the importer expects.\",\n });\n}\n\n/**\n * Narrows an unknown value to a plain property bag.\n *\n * @param value - The value to test.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to an array without widening it to `any[]`.\n *\n * @param value - The value to test.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to a real number.\n *\n * @param value - The value to test.\n * @returns Whether it is a finite number.\n */\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Reads a `{ x, y, w, h }` rectangle out of a property bag.\n *\n * @param entry - The bag to read from.\n * @param key - The field holding the rectangle.\n * @returns The rectangle, or `null` when the field is absent or incomplete.\n */\nfunction readRect(entry: Record<string, unknown>, key: string): Rect | null {\n const raw = entry[key];\n if (!isObject(raw)) {\n return null;\n }\n const x = raw[\"x\"];\n const y = raw[\"y\"];\n const w = raw[\"w\"];\n const h = raw[\"h\"];\n if (!isFiniteNumber(x) || !isFiniteNumber(y) || !isFiniteNumber(w) || !isFiniteNumber(h)) {\n return null;\n }\n return { x, y, w, h };\n}\n\n/**\n * Reads a `{ w, h }` size out of a property bag, as a vector.\n *\n * @param entry - The bag to read from.\n * @param key - The field holding the size.\n * @returns The size as `{ x: w, y: h }`, or `null` when the field is absent or incomplete.\n */\nfunction readSize(entry: Record<string, unknown>, key: string): Vec2Like | null {\n const raw = entry[key];\n if (!isObject(raw)) {\n return null;\n }\n const w = raw[\"w\"];\n const h = raw[\"h\"];\n if (!isFiniteNumber(w) || !isFiniteNumber(h)) {\n return null;\n }\n return { x: w, y: h };\n}\n\n/**\n * Reads an `{ x, y }` vector out of a property bag.\n *\n * @param entry - The bag to read from.\n * @param key - The field holding the vector.\n * @returns The vector, or `null` when the field is absent or incomplete.\n */\nfunction readVec2(entry: Record<string, unknown>, key: string): Vec2Like | null {\n const raw = entry[key];\n if (!isObject(raw)) {\n return null;\n }\n const x = raw[\"x\"];\n const y = raw[\"y\"];\n if (!isFiniteNumber(x) || !isFiniteNumber(y)) {\n return null;\n }\n return { x, y };\n}\n\n/**\n * Clamps a normalised coordinate into `[0, 1]`.\n *\n * @param value - The coordinate.\n * @returns The coordinate, clamped.\n */\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) {\n return 0.5;\n }\n return Math.min(Math.max(value, 0), 1);\n}\n\n/**\n * Drops a trailing file extension.\n *\n * Only a dot followed by a letter and up to seven more alphanumerics counts, so `hero_0.png` and\n * `hero 0.aseprite` lose their suffix while `walk.2` — a name, not a file — keeps it.\n *\n * @param raw - The raw frame key.\n * @returns The key without its extension.\n */\nfunction stripFileExtension(raw: string): string {\n return raw.replace(/\\.[A-Za-z][A-Za-z0-9]{0,7}$/u, \"\");\n}\n\n/**\n * Flattens a TexturePacker-shaped `frames` collection — hash or array — into ordered entries.\n *\n * @param frames - The document's `frames` field.\n * @param importer - The importer name to blame in an error.\n * @returns The entries, in document order.\n * @throws IgnifxError with code `IGX-1109` when `frames` is neither an object nor an array, or\n * holds something that is not an object.\n */\nfunction collectFrameEntries(frames: unknown, importer: string): readonly RawFrameEntry[] {\n const out: RawFrameEntry[] = [];\n if (isUnknownArray(frames)) {\n for (let index = 0; index < frames.length; index += 1) {\n const entry = frames[index];\n if (!isObject(entry)) {\n failImport(importer, `frame ${String(index)} is not an object`);\n }\n const filename = entry[\"filename\"];\n const key =\n typeof filename === \"string\" && filename !== \"\" ? filename : `${FALLBACK_FRAME_NAME}_${String(index)}`;\n out.push({ key, entry });\n }\n return out;\n }\n if (isObject(frames)) {\n const keys = Object.keys(frames);\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n if (key === undefined) {\n continue;\n }\n const entry = frames[key];\n if (!isObject(entry)) {\n failImport(importer, `frame ${key} is not an object`);\n }\n out.push({ key, entry });\n }\n return out;\n }\n return failImport(importer, \"its frames field is neither an object (hash layout) nor an array (array layout)\");\n}\n\n/**\n * Lifts every `meta.slices[].keys[]` entry that declares a pivot out of an Aseprite document.\n *\n * @param meta - The document's `meta` object, or `null` when it has none.\n * @returns The slice pivots, in document order.\n */\nfunction collectSlicePivots(meta: Record<string, unknown> | null): readonly SlicePivot[] {\n const out: SlicePivot[] = [];\n if (meta === null) {\n return out;\n }\n const slices = meta[\"slices\"];\n if (!isUnknownArray(slices)) {\n return out;\n }\n for (let sliceIndex = 0; sliceIndex < slices.length; sliceIndex += 1) {\n const slice = slices[sliceIndex];\n if (!isObject(slice)) {\n continue;\n }\n const keys = slice[\"keys\"];\n if (!isUnknownArray(keys)) {\n continue;\n }\n for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {\n const key = keys[keyIndex];\n if (!isObject(key)) {\n continue;\n }\n const pivot = readVec2(key, \"pivot\");\n const bounds = readRect(key, \"bounds\");\n if (pivot === null || bounds === null) {\n continue;\n }\n const frame = key[\"frame\"];\n out.push({ frame: isFiniteNumber(frame) ? frame : 0, bounds, pivot });\n }\n }\n return out;\n}\n\n/**\n * Picks the slice pivot that applies to one frame and normalises it into `[0, 1]`.\n *\n * @param pivots - Every slice pivot in the document.\n * @param frameIndex - The frame's index in the document's own frame order.\n * @param sourceWidth - The untrimmed frame width the pivot is measured against.\n * @param sourceHeight - The untrimmed frame height the pivot is measured against.\n * @returns The normalised pivot, or `null` when no slice covers the frame.\n */\nfunction slicePivotFor(\n pivots: readonly SlicePivot[],\n frameIndex: number,\n sourceWidth: number,\n sourceHeight: number,\n): Vec2Like | null {\n if (!(sourceWidth > 0) || !(sourceHeight > 0)) {\n return null;\n }\n let best: SlicePivot | null = null;\n for (let index = 0; index < pivots.length; index += 1) {\n const candidate = pivots[index];\n if (candidate === undefined || candidate.frame > frameIndex) {\n continue;\n }\n if (best === null || candidate.frame > best.frame) {\n best = candidate;\n }\n }\n if (best === null) {\n return null;\n }\n return {\n x: clamp01((best.bounds.x + best.pivot.x) / sourceWidth),\n y: clamp01((best.bounds.y + best.pivot.y) / sourceHeight),\n };\n}\n\n/**\n * Normalises an Aseprite frame key into an identifier a clip and a `#frame:` fragment can name.\n *\n * The rule, applied in this order:\n *\n * 1. Drop a trailing file extension — a dot, a letter, then up to seven more alphanumerics — so\n * `hero 0.aseprite` and `hero_0.png` both lose their suffix but `walk.2` does not.\n * 2. Replace every run of non-alphanumeric characters with a single `_`.\n * 3. Trim leading and trailing `_`.\n *\n * Case is preserved: `Hero (Idle) 0.aseprite` becomes `Hero_Idle_0`, not `hero_idle_0`. A key that\n * normalises to nothing at all (`\"###.png\"`) becomes `frame`.\n *\n * {@link importAsepriteAtlas} and `importAsepriteAnimations` both run keys through this function,\n * which is what makes an imported clip's frame names line up with the imported atlas's.\n *\n * @param raw - The frame key as Aseprite wrote it — a hash key, or an array entry's `filename`.\n * @returns The normalised frame name.\n *\n * @example\n * ```ts\n * asepriteFrameName(\"hero (idle) 0.aseprite\"); // \"hero_idle_0\"\n * asepriteFrameName(\"hero_0.png\"); // \"hero_0\"\n * ```\n *\n * @public\n */\nexport function asepriteFrameName(raw: string): string {\n const normalised = stripFileExtension(raw)\n .replaceAll(/[^0-9A-Za-z]+/gu, \"_\")\n .replace(/^_+/u, \"\")\n .replace(/_+$/u, \"\");\n return normalised === \"\" ? FALLBACK_FRAME_NAME : normalised;\n}\n\n/**\n * What {@link gridAtlas} needs to cut an evenly spaced sheet into frames.\n *\n * @public\n */\nexport interface GridAtlasImportOptions {\n /** The address of the image the frames are cut from. */\n readonly image: string;\n /** The image's full width, in pixels. */\n readonly imageWidth: number;\n /** The image's full height, in pixels. */\n readonly imageHeight: number;\n /** One cell's width, in pixels. Must be positive. */\n readonly cellWidth: number;\n /** One cell's height, in pixels. Must be positive. */\n readonly cellHeight: number;\n /** How many columns to emit. Defaults to as many as the image holds; clamped to that. */\n readonly columns?: number;\n /** How many rows to emit. Defaults to as many as the image holds; clamped to that. */\n readonly rows?: number;\n /** The border left around the whole grid, in pixels. Defaults to `0`. */\n readonly margin?: number;\n /** The gap between adjacent cells, in pixels. Defaults to `0`. */\n readonly spacing?: number;\n /** The pivot every frame gets, in `[0, 1]`. Defaults to the centre. */\n readonly pivot?: Vec2Like;\n /** The `<prefix>_<index>` frame names use. Defaults to `\"tile\"`. */\n readonly namePrefix?: string;\n /** The min/mag filter. Defaults to `\"linear\"`; pixel art wants `\"nearest\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n}\n\n/**\n * Cuts an evenly spaced sprite sheet into an `ignifx.spriteatlas` document.\n *\n * Frames come out in reading order — left to right, then top to bottom — named\n * `<namePrefix>_<index>` with `index` counting from `0` across the whole sheet, so a 4×2\n * grid ends at `tile_7`. `columns` and `rows` default to as many whole cells as the image holds\n * (`floor((imageWidth - 2·margin + spacing) / (cellWidth + spacing))`, and likewise for rows) and\n * are clamped to that capacity when given, so an over-large explicit count never produces a frame\n * that falls off the image.\n *\n * @remarks\n * `namePrefix` is how a grid atlas lines up with the rest of the toolkit: `@ignifx/2d`'s Tiled\n * importer names a tileset's frames `<tilesetName>_<index>`, so passing the tileset's name\n * as `namePrefix` makes a hand-cut grid atlas addressable by exactly the names a tilemap emits.\n *\n * @param options - The sheet's geometry and the frame naming.\n * @returns The complete atlas document.\n * @throws IgnifxError with code `IGX-1109` when a cell dimension is not positive, or when the\n * geometry yields no frames at all.\n *\n * @example\n * ```ts\n * const atlas = gridAtlas({\n * image: \"2d/terrain.png\",\n * imageWidth: 64,\n * imageHeight: 64,\n * cellWidth: 32,\n * cellHeight: 32,\n * namePrefix: \"terrain\",\n * sampling: \"nearest\",\n * });\n * atlas.frames.map((frame) => frame.name); // [\"terrain_0\", \"terrain_1\", \"terrain_2\", \"terrain_3\"]\n * ```\n *\n * @public\n */\nexport function gridAtlas(options: GridAtlasImportOptions): SpriteAtlasDefinition {\n const importer = \"gridAtlas\";\n const { cellWidth, cellHeight, imageWidth, imageHeight } = options;\n if (!(cellWidth > 0) || !(cellHeight > 0)) {\n failImport(\n importer,\n `the cell size ${String(cellWidth)}x${String(cellHeight)} is not positive`,\n \"Pass the cell size in pixels; both cellWidth and cellHeight must be greater than zero.\",\n );\n }\n const margin = options.margin ?? 0;\n const spacing = options.spacing ?? 0;\n const capacityColumns = gridCapacity(imageWidth, cellWidth, margin, spacing);\n const capacityRows = gridCapacity(imageHeight, cellHeight, margin, spacing);\n const columns =\n options.columns === undefined ? capacityColumns : Math.min(clampCount(options.columns), capacityColumns);\n const rows = options.rows === undefined ? capacityRows : Math.min(clampCount(options.rows), capacityRows);\n if (columns === 0 || rows === 0) {\n failImport(\n importer,\n `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`,\n \"Check the image size, the cell size, the margin, and the spacing against the sheet.\",\n );\n }\n const prefix = options.namePrefix ?? DEFAULT_GRID_NAME_PREFIX;\n const pivot = options.pivot ?? CENTRE_PIVOT;\n const frames: SpriteFrameDefinition[] = [];\n for (let row = 0; row < rows; row += 1) {\n for (let column = 0; column < columns; column += 1) {\n frames.push({\n name: `${prefix}_${String(row * columns + column)}`,\n x: margin + column * (cellWidth + spacing),\n y: margin + row * (cellHeight + spacing),\n w: cellWidth,\n h: cellHeight,\n pivot: { x: pivot.x, y: pivot.y },\n });\n }\n }\n return defineSpriteAtlas(\n {\n image: options.image,\n ...(options.sampling === undefined ? {} : { sampling: options.sampling }),\n ...(options.premultipliedAlpha === undefined ? {} : { premultipliedAlpha: options.premultipliedAlpha }),\n frames,\n },\n options.image,\n );\n}\n\n/**\n * How many whole cells fit along one axis.\n *\n * @param extent - The image's size along the axis, in pixels.\n * @param cell - One cell's size along the axis, in pixels.\n * @param margin - The border left at both ends, in pixels.\n * @param spacing - The gap between adjacent cells, in pixels.\n * @returns The cell count, never negative.\n */\nfunction gridCapacity(extent: number, cell: number, margin: number, spacing: number): number {\n const usable = extent - 2 * margin + spacing;\n const count = Math.floor(usable / (cell + spacing));\n return Number.isFinite(count) && count > 0 ? count : 0;\n}\n\n/**\n * Coerces a caller-supplied count into a non-negative whole number.\n *\n * @param value - The requested count.\n * @returns The count, truncated and floored at zero.\n */\nfunction clampCount(value: number): number {\n return Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\n/**\n * What {@link importTexturePackerAtlas} accepts alongside the document.\n *\n * @public\n */\nexport interface TexturePackerImportOptions {\n /** The image address to write into the atlas. Defaults to the document's `meta.image`. */\n readonly image?: string;\n /** Whether to keep the `.png` on frame names. Defaults to `false`, which strips it. */\n readonly keepExtensions?: boolean;\n /** The min/mag filter. Defaults to `\"linear\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n}\n\n/**\n * Converts a TexturePacker JSON export into an `ignifx.spriteatlas` document.\n *\n * Both of TexturePacker's JSON layouts are read and produce identical output for the same sheet:\n * the **hash** layout, whose `frames` is an object keyed by file name, and the **array** layout,\n * whose `frames` is an array of entries carrying a `filename`. Frame names lose their trailing file\n * extension (`hero_0.png` becomes `hero_0`) unless `keepExtensions` is set.\n *\n * A frame's `pivot` is used as-is when the document declares one: TexturePacker already writes\n * pivots normalised into `[0, 1]` against a top-left origin, which is exactly ignifx's convention.\n * Frames without one get the centre. A frame marked `trimmed` carries its `sourceSize` through so\n * the loader can lay the trimmed rectangle back inside its original bounds.\n *\n * @remarks\n * Rotated frames are rejected rather than silently drawn wrong — the sprite pipeline has no\n * per-frame rotation flag.\n *\n * `spriteSourceSize`'s **offset** (`x`/`y`) has no home in `SpriteFrameDefinition`, which records\n * only the untrimmed size, so a trimmed frame whose art is not centred in its source bounds may sit\n * slightly off. Pack with trimming disabled, or with `spriteSourceSize` centred, when that matters.\n *\n * @param json - The parsed TexturePacker document.\n * @param options - The image override, name handling, and sampling.\n * @returns The complete atlas document.\n * @throws IgnifxError with code `IGX-1109` when the document is not an object, when `frames` is\n * neither an object nor an array, when it is empty, when no image address can be found, when a\n * frame has no rectangle, or when a frame is rotated.\n *\n * @example\n * ```ts\n * const atlas = importTexturePackerAtlas(JSON.parse(text), { image: \"2d/hero.png\" });\n * atlas.frames[0]?.name; // \"hero_0\"\n * ```\n *\n * @public\n */\nexport function importTexturePackerAtlas(json: unknown, options?: TexturePackerImportOptions): SpriteAtlasDefinition {\n const importer = \"importTexturePackerAtlas\";\n if (!isObject(json)) {\n failImport(importer, \"the document is not a JSON object\");\n }\n const meta = isObject(json[\"meta\"]) ? json[\"meta\"] : null;\n const entries = collectFrameEntries(json[\"frames\"], importer);\n if (entries.length === 0) {\n failImport(importer, \"it declares no frames\");\n }\n const image = resolveImage(options?.image, meta, importer);\n const keepExtensions = options?.keepExtensions ?? false;\n const frames: SpriteFrameDefinition[] = [];\n for (let index = 0; index < entries.length; index += 1) {\n const item = entries[index];\n if (item === undefined) {\n continue;\n }\n if (item.entry[\"rotated\"] === true) {\n failImport(\n importer,\n `frame ${item.key} is rotated`,\n \"TexturePacker rotated frames are not supported; disable rotation when packing.\",\n );\n }\n const rect = readRect(item.entry, \"frame\");\n if (rect === null) {\n failImport(importer, `frame ${item.key} has no {x, y, w, h} frame rectangle`);\n }\n const pivot = readVec2(item.entry, \"pivot\") ?? CENTRE_PIVOT;\n const sourceSize = item.entry[\"trimmed\"] === true ? readSize(item.entry, \"sourceSize\") : null;\n frames.push({\n name: keepExtensions ? item.key : stripFileExtension(item.key),\n x: rect.x,\n y: rect.y,\n w: rect.w,\n h: rect.h,\n pivot: { x: pivot.x, y: pivot.y },\n ...(sourceSize === null ? {} : { sourceSize }),\n });\n }\n return defineSpriteAtlas(\n {\n image,\n ...(options?.sampling === undefined ? {} : { sampling: options.sampling }),\n ...(options?.premultipliedAlpha === undefined ? {} : { premultipliedAlpha: options.premultipliedAlpha }),\n frames,\n },\n image,\n );\n}\n\n/**\n * Picks the image address an imported atlas points at.\n *\n * @param override - The caller's `options.image`, when given.\n * @param meta - The document's `meta` object, or `null`.\n * @param importer - The importer name to blame in an error.\n * @returns The image address.\n * @throws IgnifxError with code `IGX-1109` when neither source names an image.\n */\nfunction resolveImage(override: string | undefined, meta: Record<string, unknown> | null, importer: string): string {\n if (override !== undefined && override !== \"\") {\n return override;\n }\n const fromMeta = meta === null ? undefined : meta[\"image\"];\n if (typeof fromMeta === \"string\" && fromMeta !== \"\") {\n return fromMeta;\n }\n return failImport(\n importer,\n \"neither options.image nor meta.image names an image\",\n \"Pass options.image, or re-export the sheet with the image name included in its metadata.\",\n );\n}\n\n/**\n * What {@link importAsepriteAtlas} accepts alongside the document.\n *\n * @public\n */\nexport interface AsepriteImportOptions {\n /** The image address to write into the atlas. Defaults to the document's `meta.image`. */\n readonly image?: string;\n /** The min/mag filter. Defaults to `\"linear\"`; pixel art wants `\"nearest\"`. */\n readonly sampling?: \"linear\" | \"nearest\";\n /** Whether the image's RGB is already multiplied by its alpha. Defaults to `false`. */\n readonly premultipliedAlpha?: boolean;\n}\n\n/**\n * Converts an Aseprite JSON sheet export into an `ignifx.spriteatlas` document.\n *\n * Aseprite writes a TexturePacker-shaped document — `frames` as either a hash or an array,\n * `meta.image`, `meta.size` — plus its own `meta.frameTags`, `meta.slices` and `meta.layers`. The\n * frame keys it produces are file-ish (`hero 0.aseprite`, `hero (idle) 0.aseprite`), so every one\n * is put through {@link asepriteFrameName}; `importAsepriteAnimations` uses the same normaliser,\n * which is what makes the imported clips and the imported atlas agree on names.\n *\n * A trimmed frame keeps its `sourceSize` so the loader can place the trimmed rectangle back inside\n * its original bounds.\n *\n * @remarks\n * Pivots are **best-effort**. Aseprite has no per-frame pivot; it has slices, which carry an\n * optional pivot in sprite-canvas pixels relative to the slice's own bounds and apply from their\n * key's `frame` index onwards. This importer takes the slice key with the greatest `frame` index at\n * or below the frame being converted (ties going to the earlier slice in document order) and\n * normalises `bounds + pivot` against the frame's untrimmed size, clamped into `[0, 1]`. That is\n * right for the common case — one slice covering the character, authored on an untrimmed sheet —\n * and approximate for anything else. Frames no slice covers get the centre.\n *\n * @param json - The parsed Aseprite document.\n * @param options - The image override and sampling.\n * @returns The complete atlas document.\n * @throws IgnifxError with code `IGX-1109` when the document is not an object, when `frames` is\n * neither an object nor an array, when it is empty, when no image address can be found, or when a\n * frame has no rectangle.\n *\n * @example\n * ```ts\n * const atlas = importAsepriteAtlas(JSON.parse(text), { sampling: \"nearest\" });\n * atlas.frames[0]?.name; // \"hero_idle_0\", from the key \"hero (idle) 0.aseprite\"\n * ```\n *\n * @public\n */\nexport function importAsepriteAtlas(json: unknown, options?: AsepriteImportOptions): SpriteAtlasDefinition {\n const importer = \"importAsepriteAtlas\";\n if (!isObject(json)) {\n failImport(importer, \"the document is not a JSON object\");\n }\n const meta = isObject(json[\"meta\"]) ? json[\"meta\"] : null;\n const entries = collectFrameEntries(json[\"frames\"], importer);\n if (entries.length === 0) {\n failImport(importer, \"it declares no frames\");\n }\n const image = resolveImage(options?.image, meta, importer);\n const slicePivots = collectSlicePivots(meta);\n const frames: SpriteFrameDefinition[] = [];\n for (let index = 0; index < entries.length; index += 1) {\n const item = entries[index];\n if (item === undefined) {\n continue;\n }\n const rect = readRect(item.entry, \"frame\");\n if (rect === null) {\n failImport(importer, `frame ${item.key} has no {x, y, w, h} frame rectangle`);\n }\n const declaredSource = readSize(item.entry, \"sourceSize\");\n const trimmed = item.entry[\"trimmed\"] === true;\n const sourceWidth = declaredSource === null ? rect.w : declaredSource.x;\n const sourceHeight = declaredSource === null ? rect.h : declaredSource.y;\n const pivot = slicePivotFor(slicePivots, index, sourceWidth, sourceHeight) ?? CENTRE_PIVOT;\n frames.push({\n name: asepriteFrameName(item.key),\n x: rect.x,\n y: rect.y,\n w: rect.w,\n h: rect.h,\n pivot: { x: pivot.x, y: pivot.y },\n ...(trimmed && declaredSource !== null ? { sourceSize: declaredSource } : {}),\n });\n }\n return defineSpriteAtlas(\n {\n image,\n ...(options?.sampling === undefined ? {} : { sampling: options.sampling }),\n ...(options?.premultipliedAlpha === undefined ? {} : { premultipliedAlpha: options.premultipliedAlpha }),\n frames,\n },\n image,\n );\n}\n","import { asepriteFrameName } from \"../atlas/importers.js\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { defineSpriteAnimation } from \"./definition.js\";\nimport type { SpriteAnimationDefinition, SpriteClipDefinition } from \"./definition.js\";\n\n/**\n * The animation importer: a pure function that turns an Aseprite sheet export's tags into an\n * `ignifx.spriteanimation` document (`docs/architecture/11-2d-toolkit.md` §2.4).\n *\n * It reads the same document `importAsepriteAtlas` reads and names frames with the same\n * normaliser, so an atlas and an animation set imported from one export always agree on frame\n * names. Nothing here does I/O; the CLI reads the file and writes the result.\n */\n\n/** The frames-per-second a tag falls back to when Aseprite recorded no usable durations. */\nconst FALLBACK_FPS = 12;\n\n/** How many decimal places a derived frames-per-second keeps. */\nconst FPS_DECIMALS = 3;\n\n/** The `repeat` value Aseprite writes for a tag that plays exactly once. */\nconst PLAY_ONCE_REPEAT = \"1\";\n\n/** One frame of the document, reduced to what a clip needs. */\ninterface FrameRecord {\n readonly key: string;\n readonly duration: number;\n}\n\n/**\n * Raises the one diagnostic this importer owns.\n *\n * @param reason - What about the document could not be read.\n * @param hint - The remedy sentence, when there is a specific one.\n * @throws IgnifxError with code `IGX-1109`, always.\n */\nfunction failImport(reason: string, hint?: string): never {\n throw twoDError(TwoDErrorCode.unsupportedImport, `importAsepriteAnimations cannot read this document: ${reason}.`, {\n context: { importer: \"importAsepriteAnimations\" },\n hint: hint ?? \"Re-export the sheet from Aseprite with `JSON Data` and `Meta: Tags` enabled.\",\n });\n}\n\n/**\n * Narrows an unknown value to a plain property bag.\n *\n * @param value - The value to test.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to an array without widening it to `any[]`.\n *\n * @param value - The value to test.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Narrows an unknown value to a real number.\n *\n * @param value - The value to test.\n * @returns Whether it is a finite number.\n */\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Reads the per-frame duration, in milliseconds, out of one frame entry.\n *\n * @param entry - The frame entry.\n * @returns The duration, or `0` when the entry declares none.\n */\nfunction readDuration(entry: Record<string, unknown>): number {\n const duration = entry[\"duration\"];\n return isFiniteNumber(duration) && duration > 0 ? duration : 0;\n}\n\n/**\n * Flattens the document's `frames` collection — hash or array — into ordered records.\n *\n * @param frames - The document's `frames` field.\n * @returns The records in document order; empty when `frames` is unreadable.\n */\nfunction collectFrames(frames: unknown): readonly FrameRecord[] {\n const out: FrameRecord[] = [];\n if (isUnknownArray(frames)) {\n for (let index = 0; index < frames.length; index += 1) {\n const entry = frames[index];\n if (!isObject(entry)) {\n continue;\n }\n const filename = entry[\"filename\"];\n out.push({\n key: typeof filename === \"string\" && filename !== \"\" ? filename : `frame_${String(index)}`,\n duration: readDuration(entry),\n });\n }\n return out;\n }\n if (isObject(frames)) {\n const keys = Object.keys(frames);\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n if (key === undefined) {\n continue;\n }\n const entry = frames[key];\n if (!isObject(entry)) {\n continue;\n }\n out.push({ key, duration: readDuration(entry) });\n }\n return out;\n }\n return out;\n}\n\n/**\n * Rounds a derived frames-per-second to {@link FPS_DECIMALS} places.\n *\n * @param value - The unrounded rate.\n * @returns The rounded rate.\n */\nfunction roundFps(value: number): number {\n const scale = 10 ** FPS_DECIMALS;\n return Math.round(value * scale) / scale;\n}\n\n/**\n * What {@link importAsepriteAnimations} accepts alongside the document.\n *\n * @public\n */\nexport interface AsepriteAnimationImportOptions {\n /** The `.atlas.json` address the clips index into. Defaults to `\"\"`, the renderer's own atlas. */\n readonly atlas?: string;\n /** The rate a tag gets when Aseprite recorded no usable frame durations. Defaults to `12`. */\n readonly defaultFps?: number;\n /**\n * Names the atlas frame at a document frame index. Defaults to the same normalisation\n * `importAsepriteAtlas` applies to the document's own frame keys, which is what makes the two\n * imports agree; override it when the atlas was produced some other way.\n */\n readonly frameNameOf?: (index: number) => string;\n}\n\n/**\n * Converts an Aseprite sheet export's tags into an `ignifx.spriteanimation` document.\n *\n * Every entry in `meta.frameTags` becomes one clip, named after the tag, listing the frame names\n * for indices `from` through `to` explicitly rather than as a range — a clip that lists names\n * survives an atlas being repacked in a different order.\n *\n * Playback direction is baked into that list, because ignifx clips play forwards:\n *\n * - `\"forward\"` (and anything unrecognised) lists `from … to` in order.\n * - `\"reverse\"` lists them backwards.\n * - `\"pingpong\"` lists them forwards and then appends the **interior** frames in reverse, so a\n * three-frame tag becomes `0, 1, 2, 1` — the ends are not repeated, which is what makes the clip\n * loop seamlessly.\n *\n * `loop` is `true` unless the tag's `repeat` is the string `\"1\"`, Aseprite's \"play once\".\n *\n * @remarks\n * Aseprite stores a duration **per frame**, in milliseconds, while an ignifx clip carries a single\n * `fps`. A tag is therefore approximated by the mean of its frames' durations: `fps` is\n * `1000 / averageDuration`, rounded to three decimal places. A tag whose frames all share a\n * duration converts exactly; one with uneven durations does not, and the individual frames will\n * hold for the average instead of their authored time. Split such a tag, or even the durations out\n * in Aseprite, when the timing matters. When no frame in the range declares a positive duration,\n * `options.defaultFps` — itself defaulting to `12` — is used instead.\n *\n * Aseprite has no frame-event concept, so no clip carries `events`.\n *\n * @param json - The parsed Aseprite document.\n * @param options - The atlas address, the fallback rate, and a frame-naming override.\n * @returns The complete animation document, already through `defineSpriteAnimation`.\n * @throws IgnifxError with code `IGX-1109` when the document is not an object, when\n * `meta.frameTags` is missing, is not an array, or is empty, when a tag has no name, or when\n * frames cannot be named because the document has no readable `frames` and no `frameNameOf` was\n * supplied.\n *\n * @example\n * ```ts\n * const animations = importAsepriteAnimations(JSON.parse(text), { atlas: \"2d/hero.atlas.json\" });\n * animations.clips[0]; // { name: \"idle\", frames: [\"hero_0\", \"hero_1\"], fps: 10, loop: true }\n * ```\n *\n * @public\n */\nexport function importAsepriteAnimations(\n json: unknown,\n options?: AsepriteAnimationImportOptions,\n): SpriteAnimationDefinition {\n if (!isObject(json)) {\n failImport(\"the document is not a JSON object\");\n }\n const meta = isObject(json[\"meta\"]) ? json[\"meta\"] : null;\n const tags = meta === null ? undefined : meta[\"frameTags\"];\n if (!isUnknownArray(tags) || tags.length === 0) {\n failImport(\n \"it declares no meta.frameTags, and tags are what become clips\",\n \"Re-export from Aseprite with `Meta: Tags` ticked, and tag the animations in the timeline first.\",\n );\n }\n const records = collectFrames(json[\"frames\"]);\n const nameOf = options?.frameNameOf;\n if (nameOf === undefined && records.length === 0) {\n failImport(\n \"it declares no readable frames, so tag indices cannot be turned into frame names\",\n \"Re-export with `Meta: Frames` included, or pass options.frameNameOf to name frames yourself.\",\n );\n }\n const defaultFps = options?.defaultFps ?? FALLBACK_FPS;\n const clips: SpriteClipDefinition[] = [];\n for (let index = 0; index < tags.length; index += 1) {\n const tag = tags[index];\n if (!isObject(tag)) {\n failImport(`tag ${String(index)} is not an object`);\n }\n const name = tag[\"name\"];\n if (typeof name !== \"string\" || name === \"\") {\n failImport(`tag ${String(index)} has no name`);\n }\n const rawFrom = tag[\"from\"];\n const rawTo = tag[\"to\"];\n const first = isFiniteNumber(rawFrom) && rawFrom > 0 ? Math.trunc(rawFrom) : 0;\n const last = isFiniteNumber(rawTo) && rawTo > first ? Math.trunc(rawTo) : first;\n const ordered = orderedFrameNames(first, last, tag[\"direction\"], records, nameOf);\n clips.push({\n name,\n frames: ordered,\n fps: tagFps(records, first, last, defaultFps),\n loop: tag[\"repeat\"] !== PLAY_ONCE_REPEAT,\n });\n }\n return defineSpriteAnimation({ ...(options?.atlas === undefined ? {} : { atlas: options.atlas }), clips });\n}\n\n/**\n * Builds one tag's frame-name list, with its direction already baked in.\n *\n * @param first - The tag's first frame index.\n * @param last - The tag's last frame index, inclusive.\n * @param direction - The tag's `direction` field, unnarrowed.\n * @param records - The document's frames, in order.\n * @param nameOf - The caller's frame namer, or `undefined` to use the document's own keys.\n * @returns The frame names in play order.\n */\nfunction orderedFrameNames(\n first: number,\n last: number,\n direction: unknown,\n records: readonly FrameRecord[],\n nameOf: ((index: number) => string) | undefined,\n): readonly string[] {\n const forward: string[] = [];\n for (let index = first; index <= last; index += 1) {\n forward.push(frameNameAt(index, records, nameOf));\n }\n if (direction === \"reverse\") {\n return forward.toReversed();\n }\n if (direction === \"pingpong\") {\n const out = forward.slice();\n for (let index = forward.length - 2; index >= 1; index -= 1) {\n const name = forward[index];\n if (name !== undefined) {\n out.push(name);\n }\n }\n return out;\n }\n return forward;\n}\n\n/**\n * Names the atlas frame at one document frame index.\n *\n * @param index - The frame index the tag refers to.\n * @param records - The document's frames, in order.\n * @param nameOf - The caller's frame namer, or `undefined` to use the document's own keys.\n * @returns The atlas frame name.\n */\nfunction frameNameAt(\n index: number,\n records: readonly FrameRecord[],\n nameOf: ((index: number) => string) | undefined,\n): string {\n if (nameOf !== undefined) {\n return nameOf(index);\n }\n const record = records[index];\n return asepriteFrameName(record === undefined ? `frame_${String(index)}` : record.key);\n}\n\n/**\n * Derives a tag's frames-per-second from the mean of its frames' durations.\n *\n * @param records - The document's frames, in order.\n * @param first - The tag's first frame index.\n * @param last - The tag's last frame index, inclusive.\n * @param defaultFps - The rate to fall back to when no duration is usable.\n * @returns The rate, rounded to three decimal places.\n */\nfunction tagFps(records: readonly FrameRecord[], first: number, last: number, defaultFps: number): number {\n let total = 0;\n let count = 0;\n for (let index = first; index <= last; index += 1) {\n const record = records[index];\n if (record === undefined || record.duration <= 0) {\n continue;\n }\n total += record.duration;\n count += 1;\n }\n if (count === 0 || total <= 0) {\n return defaultFps;\n }\n return roundFps(1000 / (total / count));\n}\n","/**\n * Resolving one document's reference to another (`docs/architecture/05-assets-and-loading.md` §2).\n *\n * Every reference `@ignifx/2d` reads out of a file — an atlas's `image`, an animation document's\n * `atlas`, a tilemap tileset's `atlas` — is interpreted **relative to the document that names it**,\n * which is what every atlas packer and map editor emits. The same arithmetic serves an address and\n * a URL, because both are `/`-separated paths.\n */\n\n/** The URL schemes that are never joined to a base. */\nconst ABSOLUTE_PREFIXES: readonly string[] = Object.freeze([\"http://\", \"https://\", \"blob:\", \"data:\", \"//\"]);\n\n/**\n * Resolves a document-relative reference against the document's own address or URL.\n *\n * @remarks\n * A reference that is absolute — one of the recognised URL schemes, or one starting with `/` — is\n * returned untouched, so a project that prefers project-root addresses can write them. `.` and `..`\n * segments are collapsed, and a base with no `/` at all is treated as a file in the root.\n *\n * @param base - The address or URL of the document holding the reference.\n * @param reference - What the document wrote.\n * @returns The resolved address or URL.\n *\n * @example\n * ```ts\n * resolveRelative(\"2d/hero.atlas.json\", \"hero.png\"); // \"2d/hero.png\"\n * resolveRelative(\"2d/hero.atlas.json\", \"../shared/pal.png\"); // \"shared/pal.png\"\n * resolveRelative(\"2d/hero.atlas.json\", \"/sprites/hero.png\"); // \"/sprites/hero.png\"\n * ```\n *\n * @public\n */\nexport function resolveRelative(base: string, reference: string): string {\n if (reference === \"\") {\n return \"\";\n }\n if (reference.startsWith(\"/\")) {\n return reference;\n }\n for (let index = 0; index < ABSOLUTE_PREFIXES.length; index += 1) {\n const prefix = ABSOLUTE_PREFIXES[index];\n if (prefix !== undefined && reference.startsWith(prefix)) {\n return reference;\n }\n }\n const cut = base.lastIndexOf(\"/\");\n const directory = cut < 0 ? \"\" : base.slice(0, cut);\n const joined = directory === \"\" ? reference : `${directory}/${reference}`;\n return normalisePath(joined);\n}\n\n/**\n * Collapses `.` and `..` segments in a `/`-separated path.\n *\n * @param path - The path to normalise.\n * @returns The normalised path; leading `..` segments that escape the root are dropped.\n *\n * @public\n */\nexport function normalisePath(path: string): string {\n const segments = path.split(\"/\");\n const out: string[] = [];\n for (let index = 0; index < segments.length; index += 1) {\n const segment = segments[index];\n if (segment === undefined || segment === \"\" || segment === \".\") {\n continue;\n }\n if (segment === \"..\") {\n out.pop();\n continue;\n }\n out.push(segment);\n }\n return out.join(\"/\");\n}\n\n/**\n * Whether a reference is a URL in its own right rather than an address: root-relative (`/…`),\n * protocol-relative (`//…`), or carrying a scheme (`http(s)://`, `blob:`, `data:`).\n *\n * @param reference - The reference as written in a document.\n * @returns `true` when the reference must be fetched verbatim rather than resolved through the manifest.\n */\nexport function isAbsoluteReference(reference: string): boolean {\n if (reference.startsWith(\"/\")) {\n return true;\n }\n for (let index = 0; index < ABSOLUTE_PREFIXES.length; index += 1) {\n const prefix = ABSOLUTE_PREFIXES[index];\n if (prefix !== undefined && reference.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n}\n","import { resolveRelative } from \"../assets/relative.js\";\nimport { defineSpriteAnimation, SPRITE_ANIMATION_ASSET_TYPE, SPRITE_ANIMATION_FILE_EXTENSIONS } from \"./definition.js\";\nimport { SpriteAnimationAsset } from \"./sprite-animation-asset.js\";\nimport type { SpriteAnimationInput } from \"./definition.js\";\nimport type { AssetLoader, LoaderContext } from \"@ignifx/core\";\n\n/**\n * The `spriteanimation` asset loader (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * The document is pure data — clip names, frame names, rates — so the loader needs no device and\n * behaves identically under a headless app. It does not load the atlas it names: a `SpriteAnimator`\n * already has one on its `SpriteRenderer`, and forcing a second copy would double the upload.\n * `SpriteAnimationAsset.atlasAddress` carries the reference for a game that wants to load it.\n */\n\n/**\n * Builds the loader for `.spriteanim.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createSpriteAnimationLoader());\n * ```\n *\n * @public\n */\nexport function createSpriteAnimationLoader(): AssetLoader<SpriteAnimationAsset> {\n return {\n type: SPRITE_ANIMATION_ASSET_TYPE,\n extensions: SPRITE_ANIMATION_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<SpriteAnimationAsset> {\n const raw = await ctx.fetchJson<SpriteAnimationInput>();\n const definition = defineSpriteAnimation(raw, ctx.address);\n const atlasAddress = definition.atlas === \"\" ? \"\" : resolveRelative(ctx.address, definition.atlas);\n return new SpriteAnimationAsset(ctx.address, definition, atlasAddress);\n },\n };\n}\n","import type { SpriteAtlas, SpriteFrame, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * The atlas half of the Babylon Lite sprite adapter: turning pixel rectangles into the normalised\n * UV records Lite's `SpriteAtlas` holds (`index.d.ts` 12041 and 12156).\n *\n * A `SpriteAtlas` is pure data — `{ texture, textureSizePx, frames, premultipliedAlpha }` — so\n * building one touches no device and this module stays Node-testable. Only the texture behind it\n * needs a GPU, and that lives in `./gpu/texture.ts`.\n *\n * Everything here is `@internal`.\n */\n\n/**\n * One frame rectangle in image pixels, top-left origin — the shape a `.atlas.json` document and\n * every importer speak.\n *\n * @internal\n */\nexport interface FrameRect {\n /** The frame's name, carried onto `SpriteFrame.name`. */\n readonly name: string;\n /** The left edge, in image pixels. */\n readonly x: number;\n /** The top edge, in image pixels. */\n readonly y: number;\n /** The width, in image pixels. */\n readonly w: number;\n /** The height, in image pixels. */\n readonly h: number;\n /** The pivot in `[0, 1]` of the frame, `[0, 0]` top-left. */\n readonly pivotX: number;\n /** The pivot in `[0, 1]` of the frame. */\n readonly pivotY: number;\n /** The drawn size in pixels, which differs from `w`/`h` only for a trimmed frame. */\n readonly sourceW: number;\n /** The drawn size in pixels. */\n readonly sourceH: number;\n}\n\n/**\n * Converts pixel rectangles into Lite `SpriteFrame` records.\n *\n * @remarks\n * Lite's sprite UVs are **top-down**: `uvMin` is the frame's top-left corner in `[0, 1]`, which is\n * why the atlas texture is uploaded with `invertY: false` (Lite's own `loadSpriteAtlas` does the\n * same — `lib/sprite/shared/sprite-atlas.js`, \"Sprite UVs are top-down (origin at image\n * top-left); do not flip\").\n *\n * @param frames - The rectangles, in the order they should be indexed.\n * @param textureWidth - The atlas image width, in pixels.\n * @param textureHeight - The atlas image height, in pixels.\n * @returns The Lite frame records.\n *\n * @internal\n */\nexport function toSpriteFrames(\n frames: readonly FrameRect[],\n textureWidth: number,\n textureHeight: number,\n): readonly SpriteFrame[] {\n const width = textureWidth > 0 ? textureWidth : 1;\n const height = textureHeight > 0 ? textureHeight : 1;\n const out: SpriteFrame[] = [];\n for (let index = 0; index < frames.length; index += 1) {\n const rect = frames[index];\n if (rect === undefined) {\n continue;\n }\n out.push({\n name: rect.name,\n uvMin: [rect.x / width, rect.y / height],\n uvMax: [(rect.x + rect.w) / width, (rect.y + rect.h) / height],\n sourceSizePx: [rect.sourceW, rect.sourceH],\n pivot: [rect.pivotX, rect.pivotY],\n });\n }\n return out;\n}\n\n/**\n * Assembles a `SpriteAtlas` from a texture and pixel rectangles.\n *\n * @param texture - The uploaded atlas image.\n * @param textureWidth - Its width, in pixels.\n * @param textureHeight - Its height, in pixels.\n * @param frames - The rectangles.\n * @param premultipliedAlpha - Whether the image's RGB is already multiplied by its alpha.\n * @returns The atlas.\n *\n * @internal\n */\nexport function buildAtlas(\n texture: Texture2D,\n textureWidth: number,\n textureHeight: number,\n frames: readonly FrameRect[],\n premultipliedAlpha: boolean,\n): SpriteAtlas {\n return {\n texture,\n textureSizePx: [textureWidth, textureHeight],\n frames: toSpriteFrames(frames, textureWidth, textureHeight),\n premultipliedAlpha,\n };\n}\n\n/**\n * Finds a frame by name.\n *\n * @param atlas - The atlas to search.\n * @param name - The frame name.\n * @returns The frame index, or `-1`.\n *\n * @internal\n */\nexport function frameIndexOf(atlas: SpriteAtlas, name: string): number {\n const frames = atlas.frames;\n for (let index = 0; index < frames.length; index += 1) {\n if (frames[index]?.name === name) {\n return index;\n }\n }\n return -1;\n}\n","import { loadTexture2D, releaseTexture } from \"@babylonjs/lite\";\nimport type { EngineContext, SpriteSampling, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * The device-only half of the atlas adapter: uploading an atlas image and releasing it again.\n * Every line here needs `engine._device`, so the module lives under `gpu/` and the root Vitest\n * coverage config excludes it; the `browser` project covers it instead\n * (`vitest.config.ts`, and the same rule core's `src/lite/gpu/**` follows).\n *\n * Everything here is `@internal`.\n */\n\n/**\n * Uploads an atlas image with the sampler settings a sprite atlas needs.\n *\n * @remarks\n * Four of the five options are not defaults and each one matters, and Lite's own `loadSpriteAtlas`\n * chooses exactly the same set (`lib/sprite/shared/sprite-atlas.js`):\n *\n * - `invertY: false` — Lite's `Texture2DOptions.invertY` defaults to **`true`** (`index.d.ts`\n * 12923) to match Babylon's convention, but sprite UVs are top-down with the origin at the image\n * top-left, so flipping would put every frame upside down.\n * - `mipMaps: false` — a sprite is drawn at roughly one texel per pixel; a mip chain only costs\n * memory and blurs a pixel-perfect camera.\n * - `addressModeU`/`addressModeV: \"clamp-to-edge\"` — the default `\"repeat\"` lets a frame at the\n * image edge sample its opposite edge.\n * - `minFilter`/`magFilter` — `\"nearest\"` is what pixel art needs; anything else blends adjacent\n * texels and defeats `Camera2D.pixelPerfect`.\n *\n * @param engine - The engine that owns the GPU texture.\n * @param url - Where to fetch the image from.\n * @param sampling - The min/mag filter.\n * @param premultiplyOnLoad - Whether to premultiply alpha at decode time.\n * @returns The uploaded texture; its reference count starts at an implicit one.\n *\n * @internal\n */\nexport function loadAtlasTexture(\n engine: EngineContext,\n url: string,\n sampling: SpriteSampling,\n premultiplyOnLoad: boolean,\n): Promise<Texture2D> {\n const filter = sampling === \"nearest\" ? \"nearest\" : \"linear\";\n return loadTexture2D(engine, url, {\n invertY: false,\n mipMaps: false,\n addressModeU: \"clamp-to-edge\",\n addressModeV: \"clamp-to-edge\",\n minFilter: filter,\n magFilter: filter,\n premultiplyAlpha: premultiplyOnLoad,\n });\n}\n\n/**\n * Releases an atlas texture through Lite's reference-counted resource pool.\n *\n * @remarks\n * This is deliberately **not** `disposeSpriteAtlas`. That function calls\n * `atlas.texture.texture.destroy()` unconditionally (`lib/sprite/shared/sprite-atlas.js` line 73)\n * and its own doc says idempotence is not guaranteed and that an atlas built over an\n * externally-owned texture should be freed by whoever owns the texture. ignifx's asset layer owns\n * it, so it releases the texture through the pool instead — the same call\n * `@ignifx/core`'s `TextureAsset` makes.\n *\n * @param texture - The texture to release.\n * @returns `true` when the reference count reached zero and the GPU texture was destroyed.\n *\n * @internal\n */\nexport function releaseAtlasTexture(texture: Texture2D): boolean {\n return releaseTexture(texture);\n}\n","import { isAbsoluteReference, resolveRelative } from \"../assets/relative.js\";\nimport { TwoDErrorCode } from \"../errors.js\";\nimport { buildAtlas } from \"../lite/atlas.js\";\nimport { loadAtlasTexture, releaseAtlasTexture } from \"../lite/gpu/texture.js\";\nimport {\n defineSpriteAtlas,\n parseSpriteFragment,\n readVec2,\n SPRITE_ATLAS_ASSET_TYPE,\n SPRITE_ATLAS_FILE_EXTENSIONS,\n} from \"./definition.js\";\nimport { SpriteAtlasAsset } from \"./sprite-atlas-asset.js\";\nimport type { SpriteAtlasDefinition, SpriteAtlasInput } from \"./definition.js\";\nimport type { SpriteAsset } from \"./sprite-atlas-asset.js\";\nimport type { FrameRect } from \"../lite/atlas.js\";\nimport type { AssetLoader, LoaderContext, Logger, Vec2Like } from \"@ignifx/core\";\n\n/**\n * The `spriteatlas` asset loader (`docs/architecture/05-assets-and-loading.md` §5,\n * `11-2d-toolkit.md` §2.3).\n *\n * The loader fetches the `.atlas.json` document, uploads the image it names, and builds Lite's\n * `SpriteAtlas` from the pixel rectangles. Under a headless app it stops after parsing: the frames\n * are all queryable, nothing is uploaded, and `asset.lite.atlas` is `null`\n * (`docs/architecture/07-rendering.md` §6).\n *\n * `parseFragment` is what makes `\"2d/hero.atlas.json#frame:idle_0\"` work: the base document is\n * loaded once and shared, and the fragment handle resolves to a {@link SpriteAsset} naming one\n * frame of it.\n */\n\n/**\n * The centre pivot a frame that declares none uses.\n */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * Converts the document's frame rectangles into the adapter's shape.\n *\n * @param definition - The parsed document.\n * @returns The rectangles, in index order.\n */\nfunction toRects(definition: SpriteAtlasDefinition): readonly FrameRect[] {\n const rects: FrameRect[] = [];\n for (let index = 0; index < definition.frames.length; index += 1) {\n const frame = definition.frames[index];\n if (frame === undefined) {\n continue;\n }\n rects.push({\n name: frame.name,\n x: frame.x,\n y: frame.y,\n w: frame.w,\n h: frame.h,\n pivotX: readVec2(frame.pivot, CENTRE_PIVOT).x,\n pivotY: readVec2(frame.pivot, CENTRE_PIVOT).y,\n sourceW: readVec2(frame.sourceSize, { x: frame.w, y: frame.h }).x,\n sourceH: readVec2(frame.sourceSize, { x: frame.w, y: frame.h }).y,\n });\n }\n return rects;\n}\n\n/**\n * Warns about frames that a pixel-perfect camera will bleed.\n *\n * @remarks\n * `docs/architecture/11-2d-toolkit.md` §4 asks importers to warn when a frame lacks a one-pixel\n * extruded border. The loader cannot see the image's pixels — it only has rectangles — so it checks\n * the thing it *can* see and that causes the bleed: a frame whose rectangle touches another frame's\n * rectangle, or the image edge, with no gap. Two frames packed flush against each other are exactly\n * the case where a `nearest` sample at a frame boundary can pick up the neighbour.\n *\n * This is a log, not a throw (`IGX-1102`): a game that never turns on `pixelPerfect` is unaffected,\n * and the remedy — repacking with padding — belongs to the art pipeline.\n *\n * @param definition - The parsed document.\n * @param address - The atlas address, for the message.\n * @param log - Where to report.\n *\n * @internal\n */\nexport function warnUnextrudedFrames(definition: SpriteAtlasDefinition, address: string, log: Logger): void {\n const frames = definition.frames;\n for (let index = 0; index < frames.length; index += 1) {\n const frame = frames[index];\n if (frame === undefined) {\n continue;\n }\n let touches = false;\n for (let other = 0; other < frames.length && !touches; other += 1) {\n const neighbour = frames[other];\n if (neighbour === undefined || other === index) {\n continue;\n }\n const gapX = Math.max(frame.x - (neighbour.x + neighbour.w), neighbour.x - (frame.x + frame.w));\n const gapY = Math.max(frame.y - (neighbour.y + neighbour.h), neighbour.y - (frame.y + frame.h));\n touches = gapX === 0 || gapY === 0;\n }\n if (touches) {\n log.warnOnce(\n `${address}#${frame.name}`,\n `${TwoDErrorCode.atlasFrameNotExtruded}: atlas frame ${frame.name} has no 1-px extruded border.`,\n {\n atlas: address,\n frame: frame.name,\n hint: \"Repack with at least 1 px of padding, or a pixel-perfect camera can sample the neighbouring frame.\",\n },\n );\n }\n }\n}\n\n/** The one thing the image resolution needs from `app.assets`. */\nexport interface AtlasImageUrlResolver {\n /** Resolves an address to the URL the asset service would fetch. */\n resolveUrl(address: string): string;\n}\n\n/**\n * Resolves an atlas document's `image` reference to the URL to fetch.\n *\n * @remarks\n * A relative reference is an **address** relative to the atlas document's own address and goes\n * through the asset manifest (`assets.resolveUrl`), so a production build that content-hashes the\n * asset root still finds the image. A root-relative (`/sheet.png`) or absolute (`https://…`,\n * `blob:`, `data:`) reference is a URL and is fetched verbatim — the shape a file in Vite's `public/`\n * directory has. Resolving against the document's *URL* instead broke hashed builds (Phase 6).\n *\n * @param assets - The app's asset service, or anything with its `resolveUrl`.\n * @param atlasAddress - The address of the atlas document.\n * @param image - The `image` reference as written in the document.\n * @returns The URL to load the sheet from.\n *\n * @internal\n */\nexport function resolveAtlasImageUrl(assets: AtlasImageUrlResolver, atlasAddress: string, image: string): string {\n const reference = resolveRelative(atlasAddress, image);\n return isAbsoluteReference(reference) ? reference : assets.resolveUrl(reference);\n}\n\n/**\n * Builds the loader for `.atlas.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createSpriteAtlasLoader());\n * ```\n *\n * @public\n */\nexport function createSpriteAtlasLoader(): AssetLoader<SpriteAtlasAsset> {\n return {\n type: SPRITE_ATLAS_ASSET_TYPE,\n extensions: SPRITE_ATLAS_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<SpriteAtlasAsset> {\n const raw = await ctx.fetchJson<SpriteAtlasInput>();\n const definition = defineSpriteAtlas(raw, ctx.address);\n warnUnextrudedFrames(definition, ctx.address, ctx.app.log);\n if (ctx.app.isHeadless) {\n // §6: a loader must tolerate the null engine and return CPU-only data.\n return new SpriteAtlasAsset(ctx.address, definition, null, null);\n }\n ctx.reportProgress(0);\n const url = resolveAtlasImageUrl(ctx.app.assets, ctx.address, definition.image);\n const texture = await loadAtlasTexture(ctx.lite.engine, url, definition.sampling, definition.premultipliedAlpha);\n ctx.reportProgress(1);\n const atlas = buildAtlas(\n texture,\n texture.width,\n texture.height,\n toRects(definition),\n definition.premultipliedAlpha,\n );\n return new SpriteAtlasAsset(ctx.address, definition, atlas, (): void => {\n releaseAtlasTexture(texture);\n });\n },\n unload(value: SpriteAtlasAsset): void {\n value.releaseGpu();\n },\n parseFragment(fragment: string, value: SpriteAtlasAsset): unknown {\n const name = parseSpriteFragment(fragment);\n if (name === null) {\n const first = value.frame(0);\n return first === null ? null : ({ atlas: value, frame: 0, name: first.name } satisfies SpriteAsset);\n }\n const index = value.requireFrame(name);\n return { atlas: value, frame: index, name } satisfies SpriteAsset;\n },\n };\n}\n","import { DEG_TO_RAD, RAD_TO_DEG } from \"@ignifx/core\";\nimport type { MutableVec2, Vec2Like } from \"@ignifx/core\";\n\n/**\n * The one place the ignifx 2D world (metres, **+Y up**, ADR-0011) is converted into Babylon Lite's\n * sprite space (pixels, **+Y down**) and back. Every other module in this package goes through\n * these functions, so the flip lives in exactly one file\n * (`docs/architecture/11-2d-toolkit.md` §1 and §3).\n *\n * Nothing here allocates: every conversion writes into a caller-owned vector (coding standards §7).\n */\n\n/**\n * The default pixels-per-unit, matching `twoD.pixelsPerUnit`\n * (`docs/architecture/11-2d-toolkit.md` §1). At 100, a 32-pixel sprite is 0.32 metres wide.\n *\n * @public\n */\nexport const DEFAULT_PIXELS_PER_UNIT = 100;\n\n/**\n * Converts a world point in metres to a Lite layer-pixel point.\n *\n * @param x - The world x, in metres.\n * @param y - The world y, in metres, with +Y up.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @param out - The vector to write.\n * @returns `out`, in pixels with +Y down.\n *\n * @example\n * ```ts\n * worldToPixelsToRef(1.5, 0.5, 100, out); // out is (150, -50)\n * ```\n *\n * @public\n */\nexport function worldToPixelsToRef<TOut extends MutableVec2>(\n x: number,\n y: number,\n pixelsPerUnit: number,\n out: TOut,\n): TOut {\n out.x = x * pixelsPerUnit;\n out.y = -y * pixelsPerUnit;\n return out;\n}\n\n/**\n * Converts a Lite layer-pixel point back to world metres.\n *\n * @param xPx - The layer x, in pixels.\n * @param yPx - The layer y, in pixels, with +Y down.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @param out - The vector to write.\n * @returns `out`, in metres with +Y up.\n *\n * @public\n */\nexport function pixelsToWorldToRef<TOut extends MutableVec2>(\n xPx: number,\n yPx: number,\n pixelsPerUnit: number,\n out: TOut,\n): TOut {\n out.x = xPx / pixelsPerUnit;\n out.y = -yPx / pixelsPerUnit;\n return out;\n}\n\n/**\n * Converts an ignifx rotation about +Z into the rotation Lite gives a **sprite**.\n *\n * @remarks\n * `Transform.rotation2D` is degrees counter-clockwise in a +Y-up world. A sprite's quad is built in\n * Lite's +Y-down pixel space (`(corner - pivot) * sizePx`, then rotated), so the same visual turn is\n * the negated angle there. Verified against the sprite vertex shader in\n * `@babylonjs/lite@1.27.0`, `lib/sprite/sprite-pipeline.js` line 25.\n *\n * @param degrees - The ignifx rotation, in degrees counter-clockwise.\n * @returns The rotation to write to `Sprite2DProps.rotation`, in radians.\n *\n * @public\n */\nexport function spriteRotationToLite(degrees: number): number {\n return -degrees * DEG_TO_RAD;\n}\n\n/**\n * Converts a Lite sprite rotation back to ignifx degrees.\n *\n * @param radians - The `Sprite2DProps.rotation` value.\n * @returns The ignifx rotation, in degrees counter-clockwise.\n *\n * @public\n */\nexport function spriteRotationFromLite(radians: number): number {\n return -radians * RAD_TO_DEG;\n}\n\n/**\n * Converts a `Camera2D` rotation into the rotation Lite gives a **view**.\n *\n * @remarks\n * A view rotation is applied to an already-flipped world offset rather than to a sprite-local\n * offset, and the two flips cancel — so unlike {@link spriteRotationToLite} the sign is kept.\n * Verified against `sprite2DWorldToScreenToRef` in `@babylonjs/lite@1.27.0`,\n * `lib/sprite/sprite-2d-view.js`.\n *\n * @param degrees - The camera rotation, in degrees counter-clockwise.\n * @returns The rotation to write to `Sprite2DView.rotation`, in radians.\n *\n * @public\n */\nexport function viewRotationToLite(degrees: number): number {\n return degrees * DEG_TO_RAD;\n}\n\n/**\n * The zoom a `Camera2D` needs so that `orthographicSize` metres fill half the viewport's height\n * (`docs/architecture/11-2d-toolkit.md` §2.1).\n *\n * @param viewportHeightPx - The viewport height, in pixels.\n * @param orthographicSize - The camera's half-height, in metres.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @returns The `Sprite2DView.zoom` value; never zero, because Lite rejects a zero zoom.\n *\n * @public\n */\nexport function zoomForSize(viewportHeightPx: number, orthographicSize: number, pixelsPerUnit: number): number {\n const divisor = 2 * orthographicSize * pixelsPerUnit;\n if (divisor <= 0) {\n return 1;\n }\n const zoom = viewportHeightPx / divisor;\n return zoom > 0 ? zoom : 1;\n}\n\n/**\n * The inverse of {@link zoomForSize}: what half-height a zoom shows.\n *\n * @param viewportHeightPx - The viewport height, in pixels.\n * @param zoom - The `Sprite2DView.zoom` value.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @returns The half-height, in metres.\n *\n * @public\n */\nexport function sizeForZoom(viewportHeightPx: number, zoom: number, pixelsPerUnit: number): number {\n if (zoom <= 0 || pixelsPerUnit <= 0) {\n return 0;\n }\n return viewportHeightPx / (2 * zoom * pixelsPerUnit);\n}\n\n/**\n * Snaps a zoom to the nearest usable integer for a pixel-perfect camera\n * (`docs/architecture/11-2d-toolkit.md` §4).\n *\n * @remarks\n * Zooms below 1 snap to the reciprocal of an integer (`1/2`, `1/3`, …) rather than to zero, so a\n * camera that is pulled far out still lands on a whole-texel scale.\n *\n * @param zoom - The continuous zoom {@link zoomForSize} produced.\n * @returns The snapped zoom, always greater than zero.\n *\n * @public\n */\nexport function snapZoomToInteger(zoom: number): number {\n if (zoom >= 1) {\n return Math.max(1, Math.floor(zoom));\n }\n if (zoom <= 0) {\n return 1;\n }\n return 1 / Math.max(1, Math.round(1 / zoom));\n}\n\n/**\n * Snaps a layer-pixel coordinate to the whole-pixel grid a pixel-perfect camera draws on.\n *\n * @param valuePx - The coordinate, in layer pixels.\n * @param zoom - The camera's zoom; at zoom 2 the grid step is half a layer pixel.\n * @returns The snapped coordinate.\n *\n * @public\n */\nexport function snapPixel(valuePx: number, zoom: number): number {\n if (zoom <= 0) {\n return valuePx;\n }\n return Math.round(valuePx * zoom) / zoom;\n}\n\n/**\n * Places the pivot of a sprite at a world point by offsetting the position Lite draws it at.\n *\n * @remarks\n * Lite's sprite pipeline has **one pivot per layer**, not per sprite or per frame: the vertex\n * shader reads `L.pivot` out of the layer uniform (`lib/sprite/sprite-pipeline.js` lines 25 and\n * 264–265), and the per-frame `SpriteFrame.pivot` is consumed only by the *billboard* family\n * (`lib/sprite/billboard-sprite.js` lines 166–167). ignifx therefore keeps every layer on the\n * centre pivot `[0.5, 0.5]` and moves the sprite instead, which is what makes a per-frame pivot and\n * `SpriteRenderer.pivotOverride` work at all.\n *\n * @param anchorXPx - The world anchor, in layer pixels.\n * @param anchorYPx - The world anchor, in layer pixels.\n * @param pivot - The pivot in `[0, 1]` of the frame; `[0, 0]` is top-left, `[1, 1]` bottom-right.\n * @param widthPx - The drawn width, in pixels.\n * @param heightPx - The drawn height, in pixels.\n * @param rotationRadians - The sprite's Lite rotation, which the offset turns with.\n * @param out - The vector to write.\n * @returns `out`: the value to write to `Sprite2DProps.positionPx`.\n *\n * @public\n */\nexport function pivotedPositionToRef<TOut extends MutableVec2>(\n anchorXPx: number,\n anchorYPx: number,\n pivot: Vec2Like,\n widthPx: number,\n heightPx: number,\n rotationRadians: number,\n out: TOut,\n): TOut {\n const offsetX = (0.5 - pivot.x) * widthPx;\n const offsetY = (0.5 - pivot.y) * heightPx;\n if (rotationRadians === 0) {\n out.x = anchorXPx + offsetX;\n out.y = anchorYPx + offsetY;\n return out;\n }\n const cos = Math.cos(rotationRadians);\n const sin = Math.sin(rotationRadians);\n out.x = anchorXPx + offsetX * cos - offsetY * sin;\n out.y = anchorYPx + offsetX * sin + offsetY * cos;\n return out;\n}\n","import { bool, Component, createDefaults, defineSchema, entityRef, f32, i32, optional, vec2, Vec2 } from \"@ignifx/core\";\nimport {\n pixelsToWorldToRef,\n snapPixel,\n snapZoomToInteger,\n viewRotationToLite,\n worldToPixelsToRef,\n zoomForSize,\n} from \"../math/coords.js\";\nimport type { Entity, MutableVec2, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `Camera2D` (`docs/architecture/11-2d-toolkit.md` §2.1): the component that drives every world\n * sprite layer's `Sprite2DView`.\n *\n * The camera holds no Lite object of its own. A `Sprite2DView` belongs to a layer, and every world\n * layer gets the *same* view written to it each frame, which is what makes the layers move\n * together; screen-space layers keep the identity view. The 2D sync system does the writing —\n * this class owns the arithmetic and the public conversions.\n */\n\n/**\n * The half-height, in metres, a camera that declares none shows.\n *\n * @public\n */\nexport const DEFAULT_ORTHOGRAPHIC_SIZE = 5;\n\n/**\n * The reference resolution a pixel-perfect camera fits an integer zoom to.\n *\n * @public\n */\nexport const DEFAULT_REFERENCE_RESOLUTION: Vec2Like = Object.freeze({ x: 640, y: 360 });\n\n/**\n * The 2D camera.\n *\n * @remarks\n * `orthographicSize` is a **half-height in metres**, exactly as Unity's orthographic camera is, so\n * the zoom it produces is `viewportHeightPx / (2 · size · PPU)`. With `pixelPerfect` on, that zoom\n * is snapped to a whole number (or to `1/n` when the camera is pulled far out) and the camera's\n * position is snapped to the pixel grid at sync time — scripts keep their sub-pixel positions, so\n * movement stays smooth even though drawing does not.\n *\n * @example\n * ```ts\n * const camera = app.world.createEntity({ name: \"camera\" }).addComponent(Camera2D);\n * camera.orthographicSize = 3;\n * camera.pixelPerfect = true;\n * ```\n *\n * @public\n */\nexport class Camera2D extends Component {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/Camera2D\";\n\n /** One camera per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = camera2DSchema();\n\n /** Half the viewport height, in metres. */\n declare orthographicSize: number;\n\n /** Whether zoom snaps to an integer and positions snap to the pixel grid. */\n declare pixelPerfect: boolean;\n\n /** The design resolution a pixel-perfect camera fits an integer zoom to, in pixels. */\n declare referenceResolution: Vec2Like;\n\n /** The lower bound of the camera's travel, in metres, or `null` for no bound. */\n declare boundsMin: Vec2Like | null;\n\n /** The upper bound of the camera's travel, in metres, or `null` for no bound. */\n declare boundsMax: Vec2Like | null;\n\n /** The entity this camera follows, or `null`. Read by `Camera2DFollow`. */\n declare follow: Entity | null;\n\n /** How long the follow takes to catch up, in seconds. */\n declare followDamping: number;\n\n /** A constant offset added to the followed entity's position, in metres. */\n declare followOffset: Vec2Like;\n\n /** The half-size of the rectangle the target may move inside before the camera reacts, in metres. */\n declare deadZone: Vec2Like;\n\n /** Highest wins when a world has several enabled cameras. */\n declare priority: number;\n\n /** The viewport width the last sync measured, in pixels. */\n #viewportWidthPx = 0;\n\n /** The viewport height the last sync measured, in pixels. */\n #viewportHeightPx = 0;\n\n /** The pixels-per-unit the last sync used. */\n #pixelsPerUnit = 100;\n\n /** The zoom the last sync computed, after any pixel-perfect snapping. */\n #zoom = 1;\n\n /** The world centre the last sync used, after bounds clamping and pixel snapping. */\n readonly #centre: MutableVec2 = new Vec2();\n\n /** Scratch, so the conversions allocate nothing (coding standards §7). */\n readonly #scratchA: MutableVec2 = new Vec2();\n\n /** Scratch; see {@link Camera2D.screenToWorld}. */\n readonly #scratchB: MutableVec2 = new Vec2();\n\n /**\n * Builds a camera with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(Camera2D.schema));\n }\n\n /**\n * The zoom the camera last resolved to — `Sprite2DView.zoom`.\n *\n * @returns The zoom; `1` before the first sync.\n */\n get zoom(): number {\n return this.#zoom;\n }\n\n /**\n * The viewport the camera last measured, in pixels.\n *\n * @returns A read-only view of the size.\n */\n get viewportSizePx(): Vec2Like {\n return { x: this.#viewportWidthPx, y: this.#viewportHeightPx };\n }\n\n /**\n * The world point the camera is centred on, after bounds clamping and pixel-perfect snapping.\n *\n * @returns A read-only view of the centre, in metres.\n */\n get centre(): Vec2Like {\n return this.#centre;\n }\n\n /**\n * Recomputes the camera's zoom and centre. The 2D sync system calls this once per frame, before\n * it writes the view onto each world layer.\n *\n * @param worldX - The entity's world x, in metres.\n * @param worldY - The entity's world y, in metres.\n * @param viewportWidthPx - The surface width, in pixels.\n * @param viewportHeightPx - The surface height, in pixels.\n * @param pixelsPerUnit - The pixels one metre spans.\n *\n * @internal\n */\n // oxlint-disable-next-line max-params -- once per camera per frame; an options object would allocate.\n resolve(\n worldX: number,\n worldY: number,\n viewportWidthPx: number,\n viewportHeightPx: number,\n pixelsPerUnit: number,\n ): void {\n this.#viewportWidthPx = viewportWidthPx;\n this.#viewportHeightPx = viewportHeightPx;\n this.#pixelsPerUnit = pixelsPerUnit;\n const raw = zoomForSize(viewportHeightPx, this.orthographicSize, pixelsPerUnit);\n // Pixel-perfect ignores `orthographicSize` and scales the reference resolution by a whole\n // number instead, which is what makes one source texel cover an exact square of screen pixels\n // (`docs/architecture/11-2d-toolkit.md` §4). Unity's Pixel Perfect Camera does the same.\n const referenceHeight = this.referenceResolution.y;\n const scaled = this.pixelPerfect\n ? snapZoomToInteger(referenceHeight > 0 ? viewportHeightPx / referenceHeight : raw)\n : raw;\n this.#zoom = scaled > 0 ? scaled : 1;\n let centreX = worldX;\n let centreY = worldY;\n const min = this.boundsMin;\n const max = this.boundsMax;\n if (min !== null && max !== null) {\n const halfHeight = viewportHeightPx / (2 * this.#zoom * pixelsPerUnit);\n const halfWidth = viewportWidthPx / (2 * this.#zoom * pixelsPerUnit);\n centreX = clampSpan(centreX, min.x, max.x, halfWidth);\n centreY = clampSpan(centreY, min.y, max.y, halfHeight);\n }\n if (this.pixelPerfect) {\n centreX = snapPixel(centreX * pixelsPerUnit, this.#zoom) / pixelsPerUnit;\n centreY = snapPixel(centreY * pixelsPerUnit, this.#zoom) / pixelsPerUnit;\n }\n this.#centre.x = centreX;\n this.#centre.y = centreY;\n }\n\n /**\n * Converts a viewport pixel into a world point.\n *\n * @remarks\n * `x` and `y` are measured from the surface's top-left corner, which is what a `PointerEvent`\n * reports and what `@ignifx/input`'s pointer position carries. The result is in metres with +Y\n * up. Before the first frame has synced, the camera has no viewport and the result is the\n * camera's own centre.\n *\n * @param x - The viewport x, in pixels from the left edge.\n * @param y - The viewport y, in pixels from the top edge.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, in world metres.\n *\n * @example\n * ```ts\n * const world = camera.screenToWorld(pointer.x, pointer.y);\n * ```\n */\n screenToWorld(x: number, y: number, out: MutableVec2 = new Vec2()): MutableVec2 {\n const zoom = this.#zoom;\n if (this.#viewportWidthPx === 0 || zoom === 0) {\n out.x = this.#centre.x;\n out.y = this.#centre.y;\n return out;\n }\n // The view's top-left in layer pixels, then the offset the pixel sits at, unrotated.\n const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, this.#scratchA);\n const offsetX = (x - this.#viewportWidthPx * 0.5) / zoom;\n const offsetY = (y - this.#viewportHeightPx * 0.5) / zoom;\n const rotation = viewRotationToLite(this.#rotationDegrees());\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const layerX = centrePx.x + offsetX * cos + offsetY * sin;\n const layerY = centrePx.y - offsetX * sin + offsetY * cos;\n return pixelsToWorldToRef(layerX, layerY, this.#pixelsPerUnit, out);\n }\n\n /**\n * Converts a world point into a viewport pixel.\n *\n * @param point - The world point, in metres.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, in pixels from the surface's top-left corner.\n */\n worldToScreen(point: Vec2Like, out: MutableVec2 = new Vec2()): MutableVec2 {\n const zoom = this.#zoom;\n const centrePx = worldToPixelsToRef(this.#centre.x, this.#centre.y, this.#pixelsPerUnit, this.#scratchA);\n const pointPx = worldToPixelsToRef(point.x, point.y, this.#pixelsPerUnit, this.#scratchB);\n const deltaX = pointPx.x - centrePx.x;\n const deltaY = pointPx.y - centrePx.y;\n const rotation = viewRotationToLite(this.#rotationDegrees());\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n out.x = (deltaX * cos - deltaY * sin) * zoom + this.#viewportWidthPx * 0.5;\n out.y = (deltaX * sin + deltaY * cos) * zoom + this.#viewportHeightPx * 0.5;\n return out;\n }\n\n /**\n * The camera entity's rotation about +Z, in degrees counter-clockwise.\n *\n * @returns The angle; `0` when the component is not attached yet.\n */\n #rotationDegrees(): number {\n return this.entity.transform.rotation2D;\n }\n}\n\n/**\n * Clamps a camera centre so the viewport stays inside a bound.\n *\n * @remarks\n * When the bound is narrower than the viewport there is no position that keeps the viewport\n * inside it, so the camera centres on the bound instead of jittering against one edge — the\n * behaviour Godot's `limit_*` has.\n *\n * @param value - The desired centre.\n * @param min - The lower bound.\n * @param max - The upper bound.\n * @param half - Half the viewport's extent on this axis, in metres.\n * @returns The clamped centre.\n */\nfunction clampSpan(value: number, min: number, max: number, half: number): number {\n if (max - min <= half * 2) {\n return (min + max) * 0.5;\n }\n return Math.min(Math.max(value, min + half), max - half);\n}\n\n/**\n * The `Camera2D` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction camera2DSchema(): Schema {\n return defineSchema({\n orthographicSize: f32(DEFAULT_ORTHOGRAPHIC_SIZE, {\n min: Number.EPSILON,\n tooltip: \"Half the viewport height, in metres.\",\n }),\n pixelPerfect: bool(false, { tooltip: \"Snap zoom to an integer and positions to whole pixels.\" }),\n referenceResolution: vec2(DEFAULT_REFERENCE_RESOLUTION, {\n tooltip: \"The design resolution a pixel-perfect camera fits an integer zoom to.\",\n }),\n boundsMin: optional(vec2(), { tooltip: \"The lower bound of the camera's travel, in metres.\" }),\n boundsMax: optional(vec2(), { tooltip: \"The upper bound of the camera's travel, in metres.\" }),\n follow: entityRef<Entity>({ tooltip: \"The entity Camera2DFollow tracks.\" }),\n followDamping: f32(0.15, { min: 0, tooltip: \"Seconds the follow takes to catch up; 0 is rigid.\" }),\n followOffset: vec2({ x: 0, y: 0 }, { tooltip: \"A constant offset added to the followed position.\" }),\n deadZone: vec2({ x: 0, y: 0 }, { tooltip: \"Half-size of the rectangle the target moves in freely.\" }),\n priority: i32(0, { tooltip: \"Highest enabled camera wins.\" }),\n });\n}\n","import { Script, Vec2 } from \"@ignifx/core\";\nimport { Camera2D } from \"./camera-2d.js\";\nimport type { MutableVec2 } from \"@ignifx/core\";\n\n/**\n * `Camera2DFollow` (`docs/architecture/11-2d-toolkit.md` §2.1): the reference implementation of a\n * smooth, dead-zoned camera follow.\n *\n * It is a `Script`, not part of `Camera2D`, on purpose: following is a *policy*, and a game that\n * wants look-ahead, screen shake, or room-based snapping replaces this script without touching the\n * camera. `Camera2D` holds the fields (`follow`, `followDamping`, `followOffset`, `deadZone`)\n * because a scene file has to be able to author them; this script is what reads them.\n *\n * The move happens in `lateUpdate`, after every `update` has run, so the camera sees the frame's\n * final player position rather than last frame's — the single most common cause of a camera that\n * visibly lags its target by one frame. For a physics-driven target that position is the\n * **display** pose: `@ignifx/physics-2d` writes `lerp(prev, cur, fixedStepAlpha)` at the top of\n * `Update` (`01-lifecycle-and-time.md` §3, since 2026-09-08), so the camera frames the target where\n * the sprite is drawn rather than where the last fixed step left it — which, through a pixel-perfect\n * camera that quantises both independently, used to read as a shaking sprite.\n */\n\n/**\n * A damped, dead-zoned camera follow.\n *\n * @example\n * ```ts\n * const camera = app.world.createEntity({ name: \"camera\" });\n * const view = camera.addComponent(Camera2D);\n * view.follow = player;\n * view.deadZone = { x: 0.5, y: 0.3 };\n * camera.addComponent(Camera2DFollow);\n * ```\n *\n * @public\n */\nexport class Camera2DFollow extends Script {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/Camera2DFollow\";\n\n /** One follow per entity. */\n static allowMultiple = false;\n\n /** The camera this script drives, found once on attach. */\n #camera: Camera2D | null = null;\n\n /** Scratch, so following allocates nothing per frame. */\n readonly #target: MutableVec2 = new Vec2();\n\n /**\n * Finds the camera on this entity.\n */\n awake(): void {\n this.#camera = this.entity.getComponent(Camera2D);\n }\n\n /**\n * Moves the camera toward its target.\n *\n * @remarks\n * The damping is frame-rate independent: the camera covers the same fraction of the remaining\n * distance per *second*, not per frame, so a 30 fps machine and a 144 fps machine see the same\n * motion. `followDamping` is the time constant in seconds; `0` snaps.\n *\n * @param deltaTime - The scaled frame delta.\n */\n lateUpdate(deltaTime: number): void {\n const camera = this.#camera;\n const target = camera?.follow ?? null;\n if (camera === null || target === null || target.isDestroyed) {\n return;\n }\n const targetMatrix = target.transform.worldMatrix;\n const offset = camera.followOffset;\n const desiredX = (targetMatrix[12] ?? 0) + offset.x;\n const desiredY = (targetMatrix[13] ?? 0) + offset.y;\n const transform = this.entity.transform;\n const matrix = transform.worldMatrix;\n const currentX = matrix[12] ?? 0;\n const currentY = matrix[13] ?? 0;\n const zone = camera.deadZone;\n // Inside the dead zone the camera does not move at all; outside it, it chases only the part of\n // the distance that is beyond the zone, so the target rides the zone's edge.\n const wantedX = beyond(desiredX, currentX, zone.x);\n const wantedY = beyond(desiredY, currentY, zone.y);\n const damping = camera.followDamping;\n const blend = damping <= 0 ? 1 : 1 - Math.exp(-deltaTime / damping);\n this.#target.x = currentX + (wantedX - currentX) * blend;\n this.#target.y = currentY + (wantedY - currentY) * blend;\n transform.position2D = new Vec2(this.#target.x, this.#target.y);\n }\n}\n\n/**\n * The position the camera should chase, given a dead zone.\n *\n * @param desired - Where the target is.\n * @param current - Where the camera is.\n * @param half - Half the dead zone's extent on this axis, in metres.\n * @returns The camera's goal: `current` while the target is inside the zone.\n */\nfunction beyond(desired: number, current: number, half: number): number {\n const delta = desired - current;\n if (Math.abs(delta) <= half) {\n return current;\n }\n return delta > 0 ? desired - half : desired + half;\n}\n","import {\n addSpriteRendererLayer,\n createSpriteRenderer,\n disposeSpriteRenderer,\n enableDeviceLostSpriteRecovery,\n registerSpriteRenderer,\n removeSpriteRendererLayer,\n unregisterSpriteRenderer,\n} from \"@babylonjs/lite\";\nimport type {\n DeviceLostRecoveryHandle,\n EngineContext,\n Sprite2DLayer,\n SpriteRenderer,\n SurfaceContext,\n} from \"@babylonjs/lite\";\n\n/**\n * The device-only half of the sprite adapter: the second rendering context `@ignifx/2d` puts on the\n * app's surface (`docs/architecture/07-rendering.md` §1, `11-2d-toolkit.md` §1).\n *\n * A `SpriteRenderer` opens its own single-sample swapchain pass and is registered directly on the\n * engine, independent of any scene. Lite's own contract (`index.d.ts` 12193-12216) is explicit\n * about ordering: *\"Register the renderer **after** `registerScene` so it draws on top\"* — and\n * about compositing: `SpriteRendererOptions.clear` *\"Default true. Set false for HUD overlays so\n * the sprite pass preserves existing scene color\"* (12222).\n *\n * Everything here needs `engine._device`, so the module lives under `gpu/` and the root Vitest\n * coverage config excludes it; the `browser` project covers it.\n *\n * Everything here is `@internal`.\n */\n\n/**\n * The surface a sprite renderer draws into.\n *\n * @remarks\n * `EngineContext extends SurfaceContext` (`index.d.ts` 4676) and an engine's index-0 surface *is*\n * the engine itself, so a single-canvas app passes `app.lite.engine` straight through. This alias\n * exists so callers outside `src/lite/**` never have to name a Lite type.\n *\n * @internal\n */\nexport type SpriteSurface = SurfaceContext;\n\n/**\n * A straight RGBA clear value, each channel in `0` to `1`.\n *\n * @internal\n */\nexport interface ClearColor {\n /** The red channel. */\n readonly r: number;\n /** The green channel. */\n readonly g: number;\n /** The blue channel. */\n readonly b: number;\n /** The alpha channel. */\n readonly a: number;\n}\n\n/**\n * Creates the sprite renderer and pushes it onto the engine's rendering-context list.\n *\n * @remarks\n * Call this **after** the render scene is registered. `registerSpriteRenderer` appends to\n * `engine._renderingContexts` and Lite draws that list in order, so a context pushed later\n * composites later. It is idempotent (`index.d.ts` 9544).\n *\n * @param surface - The surface to draw into; the engine, for a single-canvas app.\n * @param clear - Whether the sprite pass clears first. `false` in `\"mixed\"` mode, so the 3D scene's\n * colour survives underneath.\n * @param clearColor - The clear value used when `clear` is `true`, as straight RGBA in `0` to `1`.\n * @param clearColor.r - The red channel.\n * @param clearColor.g - The green channel.\n * @param clearColor.b - The blue channel.\n * @param clearColor.a - The alpha channel.\n * @returns The registered renderer.\n *\n * @internal\n */\nexport function createRegisteredSpriteRenderer(\n surface: SpriteSurface,\n clear: boolean,\n clearColor: ClearColor,\n): SpriteRenderer {\n const renderer = createSpriteRenderer(surface, {\n layers: [],\n clear,\n clearValue: { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a },\n });\n registerSpriteRenderer(renderer);\n return renderer;\n}\n\n/**\n * Adds a layer to a renderer's draw list (`index.d.ts` 190).\n *\n * @param renderer - The sprite renderer.\n * @param layer - The layer to draw.\n *\n * @internal\n */\nexport function attachLayer(renderer: SpriteRenderer, layer: Sprite2DLayer): void {\n addSpriteRendererLayer(renderer, layer);\n}\n\n/**\n * Removes a layer from a renderer's draw list (`index.d.ts` 9666).\n *\n * @param renderer - The sprite renderer.\n * @param layer - The layer to stop drawing.\n * @returns `true` when the layer was there.\n *\n * @internal\n */\nexport function detachLayer(renderer: SpriteRenderer, layer: Sprite2DLayer): boolean {\n return removeSpriteRendererLayer(renderer, layer);\n}\n\n/**\n * Unregisters and disposes a sprite renderer (`index.d.ts` 13215 and 4078).\n *\n * @param renderer - The renderer to tear down.\n *\n * @internal\n */\nexport function destroySpriteRenderer(renderer: SpriteRenderer): void {\n unregisterSpriteRenderer(renderer);\n disposeSpriteRenderer(renderer);\n}\n\n/**\n * Turns on best-effort WebGPU device-lost recovery for every registered sprite renderer\n * (`index.d.ts` 4378).\n *\n * @remarks\n * Lite's own documentation is emphatic that ordering matters: *\"Enable this before creating or\n * loading sprite textures so their recovery sources are retained\"* (`index.d.ts` 4372-4373). The\n * extension therefore calls this in `onStart`, before any atlas or layer exists.\n *\n * @param engine - The engine to protect.\n * @param onRecovered - Called after the replacement device and every rendering context are ready.\n * @param onFailed - Called when reacquisition or rebuilding fails.\n * @returns The handle whose `disable()` turns recovery off again.\n *\n * @internal\n */\nexport function enableSpriteDeviceLostRecovery(\n engine: EngineContext,\n onRecovered: () => void,\n onFailed: (error: unknown) => void,\n): DeviceLostRecoveryHandle {\n return enableDeviceLostSpriteRecovery(engine, { onRecovered, onRecoveryFailed: onFailed });\n}\n","import { bool, Component, createDefaults, defineSchema, f32, str, vec2, Vec2 } from \"@ignifx/core\";\nimport { worldToPixelsToRef } from \"../math/coords.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport type { Camera2D } from \"../camera/camera-2d.js\";\nimport type { SpriteLayerEntry } from \"../service/layer-registry.js\";\nimport type { MutableVec2, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `ParallaxLayer` (`docs/architecture/11-2d-toolkit.md` §2.6): makes one sorting layer scroll at a\n * fraction of the camera's speed, which is what gives a side-scroller depth.\n *\n * The component owns no sprites. It reaches into the views of every Lite layer belonging to its\n * sorting layer, after the 2D sync system has written the camera's view onto them, and slides each\n * one back by `cameraPositionPx × (1 − factor)`. A factor of `1` moves with the camera (no\n * parallax); `0` is pinned to the world origin, which is what a distant sky wants.\n */\n\n/**\n * A parallax layer.\n *\n * @example\n * ```ts\n * const sky = app.world.createEntity({ name: \"sky\" }).addComponent(ParallaxLayer);\n * sky.sortingLayer = \"Background\";\n * sky.factor = { x: 0.2, y: 0.5 };\n * ```\n *\n * @public\n */\nexport class ParallaxLayer extends Component {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/ParallaxLayer\";\n\n /** One parallax setting per entity; several entities may each drive a different sorting layer. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = parallaxLayerSchema();\n\n /** Which sorting layer this component slows down. */\n declare sortingLayer: string;\n\n /** How much of the camera's motion the layer follows, per axis; `1` is no parallax. */\n declare factor: Vec2Like;\n\n /** Whether the layer's sprites repeat horizontally across the camera's view. */\n declare repeatX: boolean;\n\n /** Whether the layer's sprites repeat vertically. */\n declare repeatY: boolean;\n\n /** The world width one repetition spans, in metres; `0` disables horizontal repetition. */\n declare repeatWidth: number;\n\n /** The world height one repetition spans, in metres. */\n declare repeatHeight: number;\n\n /** Scratch, so applying the offset allocates nothing. */\n readonly #scratch: MutableVec2 = new Vec2();\n\n /**\n * Builds a parallax layer with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(ParallaxLayer.schema));\n }\n\n /**\n * Slides every matching layer's view.\n *\n * @remarks\n * Runs after the camera has written its own view, so the arithmetic is a pure offset:\n * `view.positionPx -= cameraPx × (1 − factor)`. With `repeatX`/`repeatY` the offset is taken\n * modulo one repetition, which keeps a tiled backdrop from drifting away from the camera no\n * matter how far the player walks — and keeps the number in single-precision range.\n *\n * @param entries - Every layer, as the registry describes them.\n * @param camera - The active camera.\n * @param pixelsPerUnit - The pixels one metre spans.\n *\n * @internal\n */\n applyTo(entries: readonly SpriteLayerEntry[], camera: Camera2D, pixelsPerUnit: number): void {\n const cameraPx = worldToPixelsToRef(camera.centre.x, camera.centre.y, pixelsPerUnit, this.#scratch);\n let offsetX = cameraPx.x * (1 - this.factor.x);\n let offsetY = cameraPx.y * (1 - this.factor.y);\n if (this.repeatX && this.repeatWidth > 0) {\n offsetX = wrap(offsetX, this.repeatWidth * pixelsPerUnit);\n }\n if (this.repeatY && this.repeatHeight > 0) {\n offsetY = wrap(offsetY, this.repeatHeight * pixelsPerUnit);\n }\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry === undefined || entry.screenSpace || entry.sortingLayer !== this.sortingLayer) {\n continue;\n }\n const view = entry.layer.view;\n view.positionPx[0] -= offsetX;\n view.positionPx[1] -= offsetY;\n }\n }\n}\n\n/**\n * Wraps a value into `[0, span)`, keeping the sign of the mathematical modulus.\n *\n * @param value - The value.\n * @param span - The period; must be greater than zero.\n * @returns The wrapped value.\n */\nfunction wrap(value: number, span: number): number {\n const remainder = value % span;\n return remainder < 0 ? remainder + span : remainder;\n}\n\n/**\n * The `ParallaxLayer` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction parallaxLayerSchema(): Schema {\n return defineSchema({\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Which sorting layer scrolls slowly.\" }),\n factor: vec2({ x: 0.5, y: 1 }, { tooltip: \"Fraction of the camera's motion the layer follows.\" }),\n repeatX: bool(false, { tooltip: \"Tile the layer horizontally across the camera's view.\" }),\n repeatY: bool(false, { tooltip: \"Tile the layer vertically.\" }),\n repeatWidth: f32(0, { min: 0, tooltip: \"World width of one repetition, in metres.\" }),\n repeatHeight: f32(0, { min: 0, tooltip: \"World height of one repetition, in metres.\" }),\n });\n}\n","import { color, Component, createDefaults, defineSchema, enumOf, str, vec4 } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport type { Schema, Vec4Like } from \"@ignifx/core\";\n\n/**\n * `SpriteLayerEffect` (`docs/architecture/11-2d-toolkit.md` §6): a per-layer custom fragment shader.\n *\n * Lite's 2D path has no lighting model, so effects are what a 2D game reaches for instead: a tint,\n * a dissolve, water, a heat shimmer. A layer created with a `customShader`\n * (`Sprite2DLayerOptions.customShader`, `index.d.ts` 11934) runs a WGSL fragment body with a\n * built-in `fx.time` clock and a `fx.params` vec4 the component writes every frame through\n * `setSprite2DShaderParams` (`index.d.ts` 11074).\n *\n * ## The one-shader-per-layer constraint\n *\n * `Sprite2DLayer.customShader` is `readonly` and is only set at creation. A layer's shader\n * therefore cannot change once sprites are in it, so `SpriteLayerEffect` has to exist **before**\n * the first sprite on its sorting layer is synced — put it in the scene file, or add it in\n * `awake`, not halfway through a level.\n */\n\n/**\n * The built-in effects, in the order an inspector should list them.\n *\n * @public\n */\nexport const SPRITE_EFFECT_KINDS = [\"tint\", \"custom\"] as const;\n\n/**\n * Which shader a `SpriteLayerEffect` installs.\n *\n * @public\n */\nexport type SpriteEffectKind = (typeof SPRITE_EFFECT_KINDS)[number];\n\n/**\n * The WGSL body of the built-in `tint` effect.\n *\n * @remarks\n * Multiplies the sampled texel by `fx.params.rgb` and scales its alpha by `fx.params.a`, which is\n * a per-layer tint that a per-sprite `color` cannot express — every sprite in the layer fades\n * together, in one uniform write, rather than in one instance write each.\n *\n * @public\n */\nexport const TINT_EFFECT_WGSL =\n \"let texel = textureSample(atlasTex, atlasSamp, uv); return vec4f(texel.rgb * fx.params.rgb, texel.a * fx.params.a);\";\n\n/**\n * A per-layer shader effect.\n *\n * @example\n * ```ts\n * const dusk = app.world.createEntity({ name: \"dusk\" }).addComponent(SpriteLayerEffect);\n * dusk.sortingLayer = \"Default\";\n * dusk.kind = \"tint\";\n * dusk.tint = { r: 0.6, g: 0.6, b: 0.9, a: 1 };\n * ```\n *\n * @public\n */\nexport class SpriteLayerEffect extends Component {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/SpriteLayerEffect\";\n\n /** One effect per entity; several entities may each drive a different sorting layer. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = spriteLayerEffectSchema();\n\n /** Which sorting layer the effect applies to. */\n declare sortingLayer: string;\n\n /** Which shader to install. */\n declare kind: SpriteEffectKind;\n\n /** The colour the `tint` effect multiplies by, written into `fx.params`. */\n declare tint: { readonly r: number; readonly g: number; readonly b: number; readonly a: number };\n\n /** The `fx.params` vec4 a `custom` shader reads. */\n declare params: Vec4Like;\n\n /** The WGSL fragment body a `custom` effect installs. */\n declare shader: string;\n\n /**\n * Builds an effect with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(SpriteLayerEffect.schema));\n }\n\n /**\n * The WGSL fragment body this effect installs.\n *\n * @returns The shader source.\n * @throws IgnifxError with code `IGX-1113` when `kind` is `\"custom\"` and `shader` is empty.\n */\n source(): string {\n if (this.kind === \"tint\") {\n return TINT_EFFECT_WGSL;\n }\n if (this.shader === \"\") {\n throw twoDError(TwoDErrorCode.missingShaderSource, \"A custom SpriteLayerEffect needs a WGSL fragment body.\", {\n context: { sortingLayer: this.sortingLayer, entity: this.entity.uid },\n hint: 'Set `effect.shader` to a WGSL body, or use kind: \"tint\".',\n });\n }\n return this.shader;\n }\n\n /**\n * The `fx.params` vec4 to write this frame.\n *\n * @param out - The four numbers to fill.\n * @returns `out`.\n *\n * @internal\n */\n writeParams(out: Float32Array): Float32Array {\n if (this.kind === \"tint\") {\n out[0] = this.tint.r;\n out[1] = this.tint.g;\n out[2] = this.tint.b;\n out[3] = this.tint.a;\n return out;\n }\n out[0] = this.params.x;\n out[1] = this.params.y;\n out[2] = this.params.z;\n out[3] = this.params.w;\n return out;\n }\n}\n\n/**\n * The `SpriteLayerEffect` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction spriteLayerEffectSchema(): Schema {\n return defineSchema({\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Which sorting layer the effect applies to.\" }),\n kind: enumOf(SPRITE_EFFECT_KINDS, \"tint\", { tooltip: \"Which shader to install.\" }),\n tint: color(\"#ffffffff\", { tooltip: \"The colour the tint effect multiplies by.\" }),\n params: vec4({ x: 0, y: 0, z: 0, w: 0 }, { tooltip: \"The fx.params vec4 a custom shader reads.\" }),\n shader: str(\"\", { tooltip: \"The WGSL fragment body a custom effect installs.\" }),\n });\n}\n","import { assertNever } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { DEFAULT_PIXELS_PER_UNIT } from \"../math/coords.js\";\nimport type { TileCollisionInfo, TileCollisionShape } from \"./collision-data.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The `ignifx.tilemap` document — the `.tilemap.json` file that names tile sizes, tilesets, tile\n * layers and object layers (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `11-2d-toolkit.md` §2.5).\n *\n * Two coordinate conventions meet in this file and it is worth stating both loudly, because getting\n * them backwards is the single easiest mistake to make in a tilemap pipeline:\n *\n * - **Authoring space** (everything on `TileColliderDefinition` and every editor this package\n * imports from) is cell-normalised `[0, 1]` with the origin at the **top-left** of the cell and\n * +Y pointing **down**. Tiled and LDtk both emit pixels in that orientation, and the importers\n * divide by the tile size rather than flipping.\n * - **Runtime space** (`TileCollisionShape`, `TilemapCollisionData`, and every world coordinate on\n * `TilemapObjectDefinition`) is metres with the origin at the **bottom-left** and +Y pointing\n * **up**, because that is the ignifx 2D world (ADR-0011).\n *\n * {@link tileCollisionInfo} is the one function that crosses between them, so the flip lives in\n * exactly one place — the same discipline `../math/coords.ts` applies to the render path.\n */\n\n/**\n * The `format` discriminator every `.tilemap.json` document carries.\n *\n * @public\n */\nexport const TILEMAP_FORMAT = \"ignifx.tilemap\";\n\n/**\n * The document version this build reads and writes.\n *\n * @public\n */\nexport const TILEMAP_FORMAT_VERSION = 1;\n\n/**\n * The asset type name the loader registers.\n *\n * @public\n */\nexport const TILEMAP_ASSET_TYPE = \"tilemap\";\n\n/**\n * The address suffixes that select the tilemap loader.\n *\n * @public\n */\nexport const TILEMAP_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".tilemap.json\"]);\n\n/**\n * The tile id that means \"this cell is empty\"; no tileset may claim it.\n *\n * @public\n */\nexport const EMPTY_TILE_ID = 0;\n\n/** The properties record handed back for a tile that declares none; frozen and shared. */\nconst EMPTY_PROPERTIES: Readonly<Record<string, string | number | boolean>> = Object.freeze({});\n\n/** The collision info of a cell that does not collide; frozen and shared. */\nconst NO_TILE_COLLISION: TileCollisionInfo = Object.freeze({\n shape: Object.freeze({ kind: \"none\" } as const),\n oneWay: false,\n properties: EMPTY_PROPERTIES,\n});\n\n/**\n * A tile's collision footprint **as authored**: cell-normalised `[0, 1]` units with the origin at\n * the cell's **top-left** corner and +Y pointing **down**.\n *\n * @remarks\n * This is deliberately *not* {@link TileCollisionShape}, which is cell-local **metres** with a\n * **bottom-left** origin, +Y up and counter-clockwise winding. Editors work top-down and the\n * physics world works bottom-up; {@link tileCollisionInfo} converts, and nothing else should.\n *\n * A box covering the top quarter of a cell — the usual one-way platform — is\n * `{ kind: \"box\", x: 0, y: 0, width: 1, height: 0.25, oneWay: true }`.\n *\n * @public\n */\nexport type TileColliderDefinition =\n | {\n /** Discriminant: an axis-aligned box. */\n readonly kind: \"box\";\n /** The box's left edge, in cell-normalised units. */\n readonly x: number;\n /** The box's **top** edge, in cell-normalised units measured downwards from the cell's top. */\n readonly y: number;\n /** The box's width, in cell-normalised units. */\n readonly width: number;\n /** The box's height, in cell-normalised units. */\n readonly height: number;\n /** Whether the tile is a one-way platform. Defaults to `false`. */\n readonly oneWay?: boolean;\n }\n | {\n /** Discriminant: an outline. */\n readonly kind: \"polygon\";\n /** The vertices in cell-normalised units with a top-left origin, in the editor's winding. */\n readonly points: readonly Vec2Like[];\n /** Whether the tile is a one-way platform. Defaults to `false`. */\n readonly oneWay?: boolean;\n }\n | {\n /** Discriminant: the tile renders but does not collide. */\n readonly kind: \"none\";\n };\n\n/**\n * One frame of an animated tile.\n *\n * @public\n */\nexport interface TileAnimationFrame {\n /** The atlas frame name drawn during this step. */\n readonly frame: string;\n /** How long the step lasts, in milliseconds. */\n readonly durationMs: number;\n}\n\n/**\n * One tile of a tileset: what it draws, what it collides with, and what it carries.\n *\n * @public\n */\nexport interface TileDefinition {\n /** The tile's index **within its tileset**, zero-based; the global id is `tileset.firstId + id`. */\n readonly id: number;\n /** The atlas frame the tile draws, by name. */\n readonly frame: string;\n /** The collision footprint, in cell-normalised top-left-origin units. Absent means no collider. */\n readonly collider?: TileColliderDefinition;\n /** The tile's custom properties, carried through from the editor. */\n readonly properties?: Readonly<Record<string, string | number | boolean>>;\n /** The animation frames, when the tile animates. A single frame is treated as a static tile. */\n readonly animation?: readonly TileAnimationFrame[];\n}\n\n/**\n * A block of tiles cut from one atlas, occupying a contiguous run of global tile ids.\n *\n * @public\n */\nexport interface TilesetDefinition {\n /** The tileset's name, unique within the document; also the frame-name prefix. */\n readonly name: string;\n /** The address of the `.atlas.json` the frames come from; empty for a collision-only tileset. */\n readonly atlas: string;\n /** The global id of this tileset's tile `0`. Always at least `1`, because `0` means empty. */\n readonly firstId: number;\n /** The tiles, indexed by their local {@link TileDefinition.id}. */\n readonly tiles: readonly TileDefinition[];\n}\n\n/**\n * One layer of tiles.\n *\n * @remarks\n * `tiles` is **always** the dense, decoded array in the parsed form: `width * height` global tile\n * ids in row-major order with the **top** row first, which is how every editor stores a grid.\n * `0` ({@link EMPTY_TILE_ID}) means the cell is empty. Runtime code that thinks in +Y-up cell\n * coordinates reads index `(height - 1 - cellY) * width + cellX`.\n *\n * @public\n */\nexport interface TilemapLayerDefinition {\n /** The layer's name, unique within the document. */\n readonly name: string;\n /** The sorting layer the tiles draw in (`docs/architecture/11-2d-toolkit.md` §1). */\n readonly sortingLayer: string;\n /** The order within the sorting layer; higher draws in front. */\n readonly orderInLayer: number;\n /** The layer's opacity in `[0, 1]`. */\n readonly opacity: number;\n /** The parallax multiplier; `{ x: 1, y: 1 }` moves with the camera. */\n readonly parallax: Vec2Like;\n /** Whether the layer contributes collision geometry. */\n readonly collision: boolean;\n /** The layer's width, in cells. */\n readonly width: number;\n /** The layer's height, in cells. */\n readonly height: number;\n /** `width * height` global tile ids, row-major, top row first. */\n readonly tiles: readonly number[];\n}\n\n/**\n * One object placed on the map, to be turned into an entity by a registered `TileObjectFactory`.\n *\n * @remarks\n * `x`, `y`, `width` and `height` are **world metres with +Y up**, and `x`/`y` name the object's\n * **bottom-left** corner. Importers do the conversion out of the editor's top-left pixel space, so\n * nothing downstream has to know what editor the map came from.\n *\n * @public\n */\nexport interface TilemapObjectDefinition {\n /** The object's name, as authored; not required to be unique. */\n readonly name: string;\n /** The object's type — what `app.twoD.registerTileObjectFactory` keys on. */\n readonly type: string;\n /** The left edge, in world metres. */\n readonly x: number;\n /** The bottom edge, in world metres, +Y up. */\n readonly y: number;\n /** The width, in world metres. */\n readonly width: number;\n /** The height, in world metres. */\n readonly height: number;\n /** The object's custom properties. */\n readonly properties: Readonly<Record<string, string | number | boolean>>;\n}\n\n/**\n * The parsed `.tilemap.json` document.\n *\n * @example\n * ```ts\n * const map = defineTilemap({\n * tileWidth: 32,\n * width: 2,\n * height: 1,\n * tilesets: [{ name: \"hero\", atlas: \"2d/hero.atlas.json\", firstId: 1, tiles: [{ id: 0, frame: \"hero_0\" }] }],\n * layers: [{ name: \"Ground\", tiles: [1, 0] }],\n * });\n * map.cellSize; // 0.32 — 32 px at the default 100 pixels per unit\n * ```\n *\n * @public\n */\nexport interface TilemapDefinition {\n /** Always `\"ignifx.tilemap\"`. */\n readonly format: typeof TILEMAP_FORMAT;\n /** Always `1` in this build. */\n readonly formatVersion: number;\n /** The width of one tile, in **pixels**. */\n readonly tileWidth: number;\n /** The height of one tile, in **pixels**. */\n readonly tileHeight: number;\n /**\n * The world size of one cell, in metres — `tileWidth / pixelsPerUnit`.\n *\n * @remarks\n * Collision uses this single number on both axes. A map whose tiles are not square still gets a\n * square collision cell; that is a deliberate MVP limitation and it is why the importers warn\n * nothing and simply record both pixel sizes above.\n */\n readonly cellSize: number;\n /** The map's width, in cells. */\n readonly width: number;\n /** The map's height, in cells. */\n readonly height: number;\n /** The tilesets, sorted by ascending {@link TilesetDefinition.firstId}. */\n readonly tilesets: readonly TilesetDefinition[];\n /** The tile layers, back to front: index `0` draws behind index `1`. */\n readonly layers: readonly TilemapLayerDefinition[];\n /** The objects gathered from every object layer, in document order. */\n readonly objects: readonly TilemapObjectDefinition[];\n /** The map's custom properties. */\n readonly properties: Readonly<Record<string, string | number | boolean>>;\n}\n\n/**\n * A run-length-encoded tile array, as a `.tilemap.json` may store it to keep sparse maps small.\n *\n * @public\n */\nexport interface TileRleData {\n /** Flattened `[count, value, count, value, …]` pairs; see {@link decodeTileRle}. */\n readonly rle: readonly number[];\n}\n\n/**\n * What {@link defineTilemap} accepts for one layer: every defaulted field optional, and `tiles`\n * either dense or run-length encoded.\n *\n * @public\n */\nexport interface TilemapLayerInput {\n /** The layer's name, unique within the document. */\n readonly name: string;\n /** The sorting layer. Defaults to `\"Default\"`. */\n readonly sortingLayer?: string;\n /** The order within the sorting layer. Defaults to `0`. */\n readonly orderInLayer?: number;\n /** The opacity in `[0, 1]`. Defaults to `1`. */\n readonly opacity?: number;\n /** The parallax multiplier. Defaults to `{ x: 1, y: 1 }`. */\n readonly parallax?: Vec2Like;\n /** Whether the layer collides. Defaults to `false`. */\n readonly collision?: boolean;\n /** The layer's width in cells. Defaults to the map's width. */\n readonly width?: number;\n /** The layer's height in cells. Defaults to the map's height. */\n readonly height?: number;\n /** The tile ids, dense (row-major, top row first) or run-length encoded. */\n readonly tiles: readonly number[] | TileRleData;\n}\n\n/**\n * What {@link defineTilemap} accepts: the document with every defaulted field optional.\n *\n * @public\n */\nexport interface TilemapInput {\n /** Always `\"ignifx.tilemap\"` when present. */\n readonly format?: string;\n /** The document version. */\n readonly formatVersion?: number;\n /** The width of one tile, in pixels. */\n readonly tileWidth: number;\n /** The height of one tile, in pixels. Defaults to `tileWidth`. */\n readonly tileHeight?: number;\n /** The metre size of one cell. Defaults to `tileWidth / 100`, the default pixels-per-unit. */\n readonly cellSize?: number;\n /** The map's width, in cells. */\n readonly width: number;\n /** The map's height, in cells. */\n readonly height: number;\n /** The tilesets. Defaults to none. */\n readonly tilesets?: readonly TilesetDefinition[];\n /** The tile layers, back to front. Defaults to none. */\n readonly layers?: readonly TilemapLayerInput[];\n /** The objects. Defaults to none. */\n readonly objects?: readonly TilemapObjectDefinition[];\n /** The map's custom properties. Defaults to none. */\n readonly properties?: Readonly<Record<string, string | number | boolean>>;\n}\n\n/**\n * Run-length encodes a dense tile array.\n *\n * @remarks\n * The layout is flat `[count, value, count, value, …]` pairs, read left to right, so\n * `[1, 1, 0, 0, 0]` encodes to `[2, 1, 3, 0]`. It is the same shape Tiled's chunk encoding and\n * LDtk's exports settle on, and it round-trips exactly through {@link decodeTileRle}.\n *\n * @param tiles - The dense tile ids.\n * @returns The encoded pairs; empty for an empty input.\n *\n * @example\n * ```ts\n * encodeTileRle([1, 1, 0, 0, 0]); // [2, 1, 3, 0]\n * ```\n *\n * @public\n */\nexport function encodeTileRle(tiles: readonly number[]): readonly number[] {\n const out: number[] = [];\n let index = 0;\n while (index < tiles.length) {\n const value = tiles[index] ?? EMPTY_TILE_ID;\n let count = 1;\n while (index + count < tiles.length && tiles[index + count] === value) {\n count += 1;\n }\n out.push(count, value);\n index += count;\n }\n return out;\n}\n\n/**\n * Expands the `[count, value, …]` pairs {@link encodeTileRle} produces back into a dense array.\n *\n * @param rle - The encoded pairs.\n * @returns The dense tile ids.\n * @throws IgnifxError with code `IGX-1105` when the array has an odd length, or a run count that is\n * not a finite non-negative integer.\n *\n * @example\n * ```ts\n * decodeTileRle([2, 1, 3, 0]); // [1, 1, 0, 0, 0]\n * ```\n *\n * @public\n */\nexport function decodeTileRle(rle: readonly number[]): readonly number[] {\n if (rle.length % 2 !== 0) {\n throw twoDError(\n TwoDErrorCode.invalidTilemapFile,\n `A run-length-encoded tile array must hold [count, value] pairs, and this one has ${String(rle.length)} entries.`,\n { context: { file: \"<inline>\", length: rle.length }, hint: \"Re-export the map, or pass a dense tiles array.\" },\n );\n }\n const out: number[] = [];\n for (let index = 0; index < rle.length; index += 2) {\n const count = rle[index] ?? 0;\n const value = rle[index + 1] ?? EMPTY_TILE_ID;\n if (!Number.isInteger(count) || count < 0) {\n throw twoDError(\n TwoDErrorCode.invalidTilemapFile,\n `A run-length-encoded tile array has the run count ${String(count)} at index ${String(index)}.`,\n { context: { file: \"<inline>\", index }, hint: \"Run counts must be non-negative integers.\" },\n );\n }\n for (let repeat = 0; repeat < count; repeat += 1) {\n out.push(value);\n }\n }\n return out;\n}\n\n/**\n * Fills in the defaults of a tilemap document, decodes any run-length-encoded layer, and checks the\n * invariants the renderer and the collider rely on.\n *\n * @param input - The document, as authored or as an importer emitted it.\n * @param address - What to name in an error; defaults to `\"\\<inline\\>\"`.\n * @returns The complete document, with every layer's `tiles` dense.\n * @throws IgnifxError with code `IGX-1105` when the format tag or version is wrong, a tile size is\n * not positive, a tileset's `firstId` is not positive, two layers share a name, a run-length array\n * has an odd length, or a layer's decoded tile count is not `width * height`.\n *\n * @public\n */\nexport function defineTilemap(input: TilemapInput, address = \"<inline>\"): TilemapDefinition {\n const fail = (reason: string): never => {\n throw twoDError(\n TwoDErrorCode.invalidTilemapFile,\n `${address} is not a readable ignifx.tilemap document: ${reason}.`,\n {\n context: { file: address },\n hint: \"Re-import the map with `ignifx import tilemap`, or check the format and version fields.\",\n },\n );\n };\n if (input.format !== undefined && input.format !== TILEMAP_FORMAT) {\n fail(`its format is ${input.format}, not ${TILEMAP_FORMAT}`);\n }\n if (input.formatVersion !== undefined && input.formatVersion !== TILEMAP_FORMAT_VERSION) {\n fail(`its formatVersion is ${String(input.formatVersion)}, and this build reads ${String(TILEMAP_FORMAT_VERSION)}`);\n }\n const tileWidth = input.tileWidth;\n const tileHeight = input.tileHeight ?? input.tileWidth;\n if (!(tileWidth > 0) || !(tileHeight > 0)) {\n fail(`its tile size is ${String(tileWidth)}x${String(tileHeight)} pixels, which is not positive`);\n }\n const width = input.width;\n const height = input.height;\n if (!(width > 0) || !(height > 0)) {\n fail(`its size is ${String(width)}x${String(height)} cells, which is not positive`);\n }\n\n const tilesetsInput = input.tilesets ?? [];\n for (let index = 0; index < tilesetsInput.length; index += 1) {\n const tileset = tilesetsInput[index];\n if (tileset === undefined) {\n continue;\n }\n if (!Number.isInteger(tileset.firstId) || tileset.firstId <= EMPTY_TILE_ID) {\n fail(`tileset ${tileset.name} has firstId ${String(tileset.firstId)}, and 0 is reserved for the empty tile`);\n }\n }\n // A stable ascending order is what makes `findTileset`'s \"highest firstId that fits\" a single\n // backward scan rather than a search over an arbitrary order.\n const tilesets = tilesetsInput.toSorted((left, right) => left.firstId - right.firstId);\n\n const layersInput = input.layers ?? [];\n const layers: TilemapLayerDefinition[] = [];\n const seenLayerNames = new Set<string>();\n for (let index = 0; index < layersInput.length; index += 1) {\n const layer = layersInput[index];\n if (layer === undefined) {\n continue;\n }\n if (seenLayerNames.has(layer.name)) {\n fail(`two layers are named ${layer.name}`);\n }\n seenLayerNames.add(layer.name);\n const layerWidth = layer.width ?? width;\n const layerHeight = layer.height ?? height;\n const tilesInput = layer.tiles;\n const tiles = \"rle\" in tilesInput ? decodeTileRle(tilesInput.rle) : tilesInput;\n if (tiles.length !== layerWidth * layerHeight) {\n fail(\n `layer ${layer.name} is ${String(layerWidth)}x${String(layerHeight)} cells but decodes to ${String(tiles.length)} tiles`,\n );\n }\n layers.push({\n name: layer.name,\n sortingLayer: layer.sortingLayer ?? \"Default\",\n orderInLayer: layer.orderInLayer ?? 0,\n opacity: layer.opacity ?? 1,\n parallax: layer.parallax ?? { x: 1, y: 1 },\n collision: layer.collision ?? false,\n width: layerWidth,\n height: layerHeight,\n tiles,\n });\n }\n\n return {\n format: TILEMAP_FORMAT,\n formatVersion: TILEMAP_FORMAT_VERSION,\n tileWidth,\n tileHeight,\n cellSize: input.cellSize ?? tileWidth / DEFAULT_PIXELS_PER_UNIT,\n width,\n height,\n tilesets,\n layers,\n objects: input.objects ?? [],\n properties: input.properties ?? EMPTY_PROPERTIES,\n };\n}\n\n/**\n * Resolves a global tile id to the tileset that owns it.\n *\n * @remarks\n * The owner is the tileset with the highest {@link TilesetDefinition.firstId} that is still less\n * than or equal to `tileId` — the rule Tiled's `firstgid` implies. `defineTilemap` sorts the\n * tilesets ascending, so this is a backward scan over a handful of entries.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id.\n * @returns The owning tileset, or `null` for the empty tile and for an id no tileset claims.\n *\n * @public\n */\nexport function findTileset(map: TilemapDefinition, tileId: number): TilesetDefinition | null {\n if (tileId <= EMPTY_TILE_ID) {\n return null;\n }\n for (let index = map.tilesets.length - 1; index >= 0; index -= 1) {\n const tileset = map.tilesets[index];\n if (tileset !== undefined && tileset.firstId <= tileId) {\n // An id past the end of the highest tileset belongs to nobody; no earlier tileset can claim\n // it either, because their ranges all end before this one begins.\n return tileId - tileset.firstId < tileset.tiles.length ? tileset : null;\n }\n }\n return null;\n}\n\n/**\n * Resolves a global tile id to the tile entry that describes it.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id.\n * @returns The tile entry, or `null` when no tileset claims the id.\n */\nfunction findTile(map: TilemapDefinition, tileId: number): TileDefinition | null {\n const tileset = findTileset(map, tileId);\n if (tileset === null) {\n return null;\n }\n const localId = tileId - tileset.firstId;\n const byIndex = tileset.tiles[localId];\n if (byIndex !== undefined && byIndex.id === localId) {\n return byIndex;\n }\n for (let index = 0; index < tileset.tiles.length; index += 1) {\n const tile = tileset.tiles[index];\n if (tile !== undefined && tile.id === localId) {\n return tile;\n }\n }\n return null;\n}\n\n/**\n * The atlas frame a global tile id draws.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id.\n * @returns The frame name, or `null` for the empty tile and for an id no tileset claims.\n *\n * @example\n * ```ts\n * tileFrameName(map, 1); // \"hero_0\"\n * ```\n *\n * @public\n */\nexport function tileFrameName(map: TilemapDefinition, tileId: number): string | null {\n return findTile(map, tileId)?.frame ?? null;\n}\n\n/**\n * Resolves a global tile id into the collision information a physics backend consumes.\n *\n * @remarks\n * This is the only place the authoring convention becomes the runtime one. A\n * {@link TileColliderDefinition} is cell-normalised with a **top-left** origin and +Y down; a\n * {@link TileCollisionShape} is cell-local **metres** with a **bottom-left** origin, +Y up and\n * counter-clockwise winding. So:\n *\n * - a box's bottom edge is `(1 - y - height) * cellSize`, because the authored `y` measures the\n * distance from the cell's top down to the box's *top* edge;\n * - a polygon's points each become `(x * cellSize, (1 - y) * cellSize)`, and the point **order is\n * reversed**, because mirroring a ring about a horizontal axis flips its winding — a clockwise\n * editor outline is counter-clockwise once flipped only if it is also walked backwards.\n *\n * @param map - The parsed document.\n * @param tileId - The global tile id, `0` for an empty cell.\n * @returns The tile's runtime collision info; a non-colliding, non-one-way default for the empty\n * tile, for an id no tileset claims, and for a tile that declares no collider.\n *\n * @example\n * ```ts\n * // A one-way platform authored as the top quarter of the cell, at cellSize 1:\n * tileCollisionInfo(map, 2).shape; // { kind: \"box\", x: 0, y: 0.75, width: 1, height: 0.25 }\n * ```\n *\n * @public\n */\nexport function tileCollisionInfo(map: TilemapDefinition, tileId: number): TileCollisionInfo {\n const tile = findTile(map, tileId);\n if (tile === null) {\n return NO_TILE_COLLISION;\n }\n const collider = tile.collider;\n const properties = tile.properties ?? EMPTY_PROPERTIES;\n if (collider === undefined) {\n return { shape: { kind: \"none\" }, oneWay: false, properties };\n }\n const cellSize = map.cellSize;\n switch (collider.kind) {\n case \"none\": {\n return { shape: { kind: \"none\" }, oneWay: false, properties };\n }\n case \"box\": {\n const shape: TileCollisionShape = {\n kind: \"box\",\n x: collider.x * cellSize,\n y: (1 - collider.y - collider.height) * cellSize,\n width: collider.width * cellSize,\n height: collider.height * cellSize,\n };\n return { shape, oneWay: collider.oneWay ?? false, properties };\n }\n case \"polygon\": {\n const points: Vec2Like[] = [];\n for (let index = collider.points.length - 1; index >= 0; index -= 1) {\n const point = collider.points[index];\n if (point === undefined) {\n continue;\n }\n points.push({ x: point.x * cellSize, y: (1 - point.y) * cellSize });\n }\n return { shape: { kind: \"polygon\", points }, oneWay: collider.oneWay ?? false, properties };\n }\n default: {\n return assertNever(collider, \"TileColliderDefinition.kind\");\n }\n }\n}\n","import { asset, bool, Component, createDefaults, defineSchema, str, Vec2 } from \"@ignifx/core\";\nimport { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport { createSpriteScratch, writeScratch } from \"../lite/sprite-layer.js\";\nimport { worldToPixelsToRef } from \"../math/coords.js\";\nimport { DEFAULT_SORTING_LAYER } from \"../service/sorting-layers.js\";\nimport { tileFrameName } from \"./definition.js\";\nimport type { Tilemap } from \"./tilemap.js\";\nimport type { SpriteScratch } from \"../lite/sprite-layer.js\";\nimport type { LiteBounds2D, LiteSprite2DHandle } from \"../lite/types.js\";\nimport type { SpriteLayerRegistry } from \"../service/layer-registry.js\";\nimport type { AssetHandle, ComponentHooks, MutableVec2, Schema } from \"@ignifx/core\";\n\n/**\n * `TilemapRenderer` (`docs/architecture/11-2d-toolkit.md` §2.5): draws a `Tilemap`'s cells as\n * sprites, one chunk at a time.\n *\n * ## Why chunks\n *\n * A 100x100 map is 10 000 cells. Materialising all of them as sprites costs 10 000 instance slots\n * and, worse, 10 000 per-frame comparisons. Instead the renderer materialises a chunk — 32x32 cells\n * by default — only while it intersects the camera's visible bounds\n * (`getSprite2DVisibleBoundsToRef`, `index.d.ts` 5992), and drops it again when it leaves. A chunk\n * that is up and unchanged costs **nothing** per frame: its sprites are written once, at the moment\n * the chunk is built, and never touched again. That is the property spike S6.1 measures.\n *\n * ## Why the renderer owns its sprites\n *\n * Tiles do not get a `SpriteRenderer` component each — 10 000 components and 10 000 entities is a\n * cost with no benefit, since a tile has no behaviour. The renderer places sprites into the same\n * Lite layers component-owned sprites use, through the registry's raw path, so tiles sort against\n * characters correctly. The trade is that `app.twoD.pickAt` does not resolve a tile;\n * `Tilemap.worldToCell` does, exactly and for free.\n */\n\n/** One materialised chunk. */\ninterface ChunkRecord {\n /** The chunk's column, in chunks. */\n readonly chunkX: number;\n /** The chunk's row, in chunks. */\n readonly chunkY: number;\n /** The layer keys and handles of every sprite in the chunk. */\n readonly sprites: { readonly key: string; readonly handle: LiteSprite2DHandle }[];\n}\n\n/**\n * A tilemap renderer.\n *\n * @example\n * ```ts\n * const level = app.world.createEntity({ name: \"level\" });\n * level.addComponent(Tilemap).map = app.assets.load<TilemapAsset>(\"2d/level-1.tilemap.json\").retain();\n * const renderer = level.addComponent(TilemapRenderer);\n * renderer.atlas = app.assets.load<SpriteAtlasAsset>(\"2d/tiles.atlas.json\").retain();\n * ```\n *\n * @public\n */\nexport class TilemapRenderer extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/TilemapRenderer\";\n\n /** One renderer per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = tilemapRendererSchema();\n\n /** The atlas the tile frames come from. */\n declare atlas: AssetHandle<SpriteAtlasAsset> | null;\n\n /** Which sorting layer the tiles draw on, when the document's layers name none. */\n declare sortingLayer: string;\n\n /** Whether chunks outside the camera's visible bounds are dropped. */\n declare cullChunks: boolean;\n\n /** Chunks currently materialised, keyed by `<chunkX>,<chunkY>`. */\n readonly #chunks = new Map<string, ChunkRecord>();\n\n /** The reusable props record, so building a chunk allocates one object rather than 1024. */\n readonly #scratch: SpriteScratch = createSpriteScratch();\n\n /** Scratch, so the per-chunk arithmetic allocates nothing. */\n readonly #pixels: MutableVec2 = new Vec2();\n\n /** How far animated tiles have advanced, in seconds. */\n #animationClock = 0;\n\n /** Whether every chunk must be rebuilt, because the map or the atlas changed. */\n #isStale = true;\n\n /**\n * Builds a renderer with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(TilemapRenderer.schema));\n }\n\n /**\n * Marks every chunk stale, so a recycled component rebuilds.\n */\n onAttach(): void {\n this.#isStale = true;\n }\n\n /**\n * Marks every chunk stale; the 2D sync system does the removal, because it owns the layers.\n */\n onDetach(): void {\n this.#isStale = true;\n }\n\n /**\n * How many chunks are currently materialised.\n *\n * @returns The count.\n */\n get chunkCount(): number {\n return this.#chunks.size;\n }\n\n /**\n * How many sprites the materialised chunks hold in total.\n *\n * @returns The count.\n */\n get spriteCount(): number {\n let total = 0;\n for (const chunk of this.#chunks.values()) {\n total += chunk.sprites.length;\n }\n return total;\n }\n\n /**\n * The loaded atlas, or `null`.\n *\n * @returns The atlas.\n */\n get loadedAtlas(): SpriteAtlasAsset | null {\n const handle = this.atlas;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * Forces every chunk to be rebuilt on the next sync.\n *\n * @remarks\n * `Tilemap.onTileChanged` is what normally calls this — a rewritten cell has to reach the sprite\n * that draws it, and rebuilding the chunk is both simpler and, for anything short of a per-frame\n * rewrite, cheaper than tracking one sprite per cell.\n *\n * @internal\n */\n invalidate(): void {\n this.#isStale = true;\n }\n\n /**\n * Brings the materialised chunks in line with the camera's visible bounds.\n *\n * @param map - The tilemap being drawn.\n * @param registry - The layer registry that owns the Lite layers.\n * @param bounds - The camera's visible bounds, in layer pixels, or `null` to build every chunk.\n * @param pixelsPerUnit - The pixels one metre spans.\n * @returns How many sprites were written this call; `0` on a steady frame.\n *\n * @internal\n */\n sync(map: Tilemap, registry: SpriteLayerRegistry, bounds: LiteBounds2D | null, pixelsPerUnit: number): number {\n const atlas = this.loadedAtlas;\n const definition = map.definition;\n if (atlas === null || atlas.lite.atlas === null || definition === null) {\n return 0;\n }\n if (this.#isStale) {\n this.#dropAll(registry);\n this.#isStale = false;\n }\n const chunkSize = Math.max(1, map.chunkSize);\n const cellSize = map.cellSize;\n if (cellSize <= 0) {\n return 0;\n }\n const chunksX = Math.ceil(definition.width / chunkSize);\n const chunksY = Math.ceil(definition.height / chunkSize);\n const window = this.#chunkWindow(bounds, chunkSize, cellSize, pixelsPerUnit, chunksX, chunksY);\n let written = 0;\n for (const [key, chunk] of this.#chunks) {\n if (!inWindow(chunk.chunkX, chunk.chunkY, window)) {\n this.#drop(registry, key, chunk);\n }\n }\n for (let chunkY = window.minY; chunkY <= window.maxY; chunkY += 1) {\n for (let chunkX = window.minX; chunkX <= window.maxX; chunkX += 1) {\n const key = `${String(chunkX)},${String(chunkY)}`;\n if (this.#chunks.has(key)) {\n continue;\n }\n written += this.#build(map, atlas, registry, chunkX, chunkY, chunkSize, cellSize, pixelsPerUnit);\n }\n }\n return written;\n }\n\n /**\n * Advances animated tiles and rewrites the chunks holding them.\n *\n * @param deltaSeconds - The scaled frame delta.\n * @returns `true` when a tile's frame changed, so the renderer must rebuild.\n *\n * @internal\n */\n advanceAnimation(deltaSeconds: number): boolean {\n const previous = this.#animationClock;\n this.#animationClock += deltaSeconds;\n // A tile animation is a whole-map property: if any tileset declares one, a frame boundary\n // anywhere invalidates the chunks. Rebuilding on a 100 ms grid is cheap next to tracking every\n // animated cell, and tile animations are authored in tenths of a second, not milliseconds.\n return (\n Math.floor(previous * ANIMATION_TICKS_PER_SECOND) !==\n Math.floor(this.#animationClock * ANIMATION_TICKS_PER_SECOND)\n );\n }\n\n /**\n * The animation clock animated tiles are sampled at, in seconds.\n *\n * @returns The elapsed time.\n *\n * @internal\n */\n get animationClock(): number {\n return this.#animationClock;\n }\n\n /**\n * Drops every materialised chunk.\n *\n * @param registry - The layer registry.\n *\n * @internal\n */\n dropAll(registry: SpriteLayerRegistry): void {\n this.#dropAll(registry);\n }\n\n /**\n * The range of chunks the camera can see.\n *\n * @param bounds - The camera's visible bounds, in layer pixels, or `null`.\n * @param chunkSize - Cells per chunk.\n * @param cellSize - Metres per cell.\n * @param pixelsPerUnit - Pixels per metre.\n * @param chunksX - How many chunk columns the map has.\n * @param chunksY - How many chunk rows.\n * @returns The inclusive chunk window.\n */\n // oxlint-disable-next-line max-params -- once per tilemap per frame; an options object would allocate.\n #chunkWindow(\n bounds: LiteBounds2D | null,\n chunkSize: number,\n cellSize: number,\n pixelsPerUnit: number,\n chunksX: number,\n chunksY: number,\n ): ChunkWindow {\n if (bounds === null || !this.cullChunks) {\n return { minX: 0, minY: 0, maxX: chunksX - 1, maxY: chunksY - 1 };\n }\n const matrix = this.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n // Layer pixels run +Y down, so the bounds' minY is the *top* of the world window.\n const worldMinX = bounds.minX / pixelsPerUnit - originX;\n const worldMaxX = bounds.maxX / pixelsPerUnit - originX;\n const worldMinY = -bounds.maxY / pixelsPerUnit - originY;\n const worldMaxY = -bounds.minY / pixelsPerUnit - originY;\n const span = chunkSize * cellSize;\n return {\n minX: clampIndex(Math.floor(worldMinX / span), chunksX),\n maxX: clampIndex(Math.floor(worldMaxX / span), chunksX),\n minY: clampIndex(Math.floor(worldMinY / span), chunksY),\n maxY: clampIndex(Math.floor(worldMaxY / span), chunksY),\n };\n }\n\n /**\n * Materialises one chunk's sprites.\n *\n * @param map - The tilemap.\n * @param atlas - The tile atlas.\n * @param registry - The layer registry.\n * @param chunkX - The chunk's column.\n * @param chunkY - The chunk's row.\n * @param chunkSize - Cells per chunk.\n * @param cellSize - Metres per cell.\n * @param pixelsPerUnit - Pixels per metre.\n * @returns How many sprites were created.\n */\n // oxlint-disable-next-line max-params -- once per chunk; an options object would allocate per chunk.\n #build(\n map: Tilemap,\n atlas: SpriteAtlasAsset,\n registry: SpriteLayerRegistry,\n chunkX: number,\n chunkY: number,\n chunkSize: number,\n cellSize: number,\n pixelsPerUnit: number,\n ): number {\n const definition = map.definition;\n if (definition === null) {\n return 0;\n }\n const matrix = this.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n const sizePx = cellSize * pixelsPerUnit;\n const sprites: { key: string; handle: LiteSprite2DHandle }[] = [];\n for (let layerIndex = 0; layerIndex < definition.layers.length; layerIndex += 1) {\n const layer = definition.layers[layerIndex];\n if (layer === undefined) {\n continue;\n }\n const sortingLayer = layer.sortingLayer === \"\" ? this.sortingLayer : layer.sortingLayer;\n const alpha = layer.opacity;\n const endX = Math.min(layer.width, (chunkX + 1) * chunkSize);\n const endY = Math.min(layer.height, (chunkY + 1) * chunkSize);\n for (let y = chunkY * chunkSize; y < endY; y += 1) {\n for (let x = chunkX * chunkSize; x < endX; x += 1) {\n const tileId = map.getTile(layerIndex, x, y);\n if (tileId === 0) {\n continue;\n }\n const frameName = tileFrameName(definition, tileId);\n const frame = frameName === null ? -1 : atlas.frameIndex(frameName);\n if (frame < 0) {\n continue;\n }\n const worldX = originX + (x + 0.5) * cellSize;\n const worldY = originY + (y + 0.5) * cellSize;\n const centre = worldToPixelsToRef(worldX, worldY, pixelsPerUnit, this.#pixels);\n writeScratch(this.#scratch, centre.x, centre.y, sizePx, sizePx, frame, 0, 1, 1, 1, alpha, false, false, true);\n sprites.push(registry.placeRaw(sortingLayer, atlas, \"alpha\", false, this.#scratch));\n }\n }\n }\n this.#chunks.set(`${String(chunkX)},${String(chunkY)}`, { chunkX, chunkY, sprites });\n return sprites.length;\n }\n\n /**\n * Removes one chunk's sprites.\n *\n * @param registry - The layer registry.\n * @param key - The chunk key.\n * @param chunk - The chunk record.\n */\n #drop(registry: SpriteLayerRegistry, key: string, chunk: ChunkRecord): void {\n for (let index = chunk.sprites.length - 1; index >= 0; index -= 1) {\n const sprite = chunk.sprites[index];\n if (sprite !== undefined) {\n registry.removeRaw(sprite.key, sprite.handle);\n }\n }\n this.#chunks.delete(key);\n }\n\n /**\n * Removes every chunk's sprites.\n *\n * @param registry - The layer registry.\n */\n #dropAll(registry: SpriteLayerRegistry): void {\n for (const [key, chunk] of this.#chunks) {\n this.#drop(registry, key, chunk);\n }\n this.#chunks.clear();\n }\n}\n\n/** How often an animated tile's frame is allowed to change, in ticks per second. */\nconst ANIMATION_TICKS_PER_SECOND = 10;\n\n/** An inclusive range of chunk indices. */\ninterface ChunkWindow {\n /** The first chunk column. */\n readonly minX: number;\n /** The first chunk row. */\n readonly minY: number;\n /** The last chunk column. */\n readonly maxX: number;\n /** The last chunk row. */\n readonly maxY: number;\n}\n\n/**\n * Whether a chunk is inside a window.\n *\n * @param x - The chunk column.\n * @param y - The chunk row.\n * @param window - The window.\n * @returns `true` when the chunk should stay materialised.\n */\nfunction inWindow(x: number, y: number, window: ChunkWindow): boolean {\n return x >= window.minX && x <= window.maxX && y >= window.minY && y <= window.maxY;\n}\n\n/**\n * Clamps a chunk index into a map's range.\n *\n * @param value - The index.\n * @param count - How many chunks the map has on this axis.\n * @returns The clamped index.\n */\nfunction clampIndex(value: number, count: number): number {\n return Math.min(Math.max(value, 0), Math.max(0, count - 1));\n}\n\n/**\n * The `TilemapRenderer` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction tilemapRendererSchema(): Schema {\n return defineSchema({\n atlas: asset(SpriteAtlasAsset, { tooltip: \"The atlas the tile frames come from.\" }),\n sortingLayer: str(DEFAULT_SORTING_LAYER, { tooltip: \"Sorting layer used when a map layer names none.\" }),\n cullChunks: bool(true, { tooltip: \"Drop chunks outside the camera's visible bounds.\" }),\n });\n}\n","import {\n addSprite,\n clearLayer,\n createLayer,\n removeSprite,\n setShaderParams,\n setYSort,\n setYSortOrder,\n spriteIndexOf,\n} from \"../lite/sprite-layer.js\";\nimport type { SortingLayerTable } from \"./sorting-layers.js\";\nimport type { SpriteAtlasAsset } from \"../atlas/sprite-atlas-asset.js\";\nimport type { SpriteScratch, SpriteBlendName } from \"../lite/sprite-layer.js\";\nimport type { LiteSprite2DHandle, LiteSprite2DLayer, LiteSpriteCustomShader } from \"../lite/types.js\";\nimport type { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\n\n/**\n * The pool of Lite sprite layers (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * One `Sprite2DLayer` exists per **(sorting layer, atlas, blend mode, screen-space)** tuple,\n * because Lite binds a layer to one atlas and one blend mode for its whole life (`index.d.ts` 11885\n * declares both `readonly`). Layers are created on demand as sprites appear and torn down with the\n * app; a sprite that changes any part of its key is removed from one layer and added to another,\n * which replaces its handle.\n *\n * The registry also carries the **handle-index to component** map that picking needs. Lite has no\n * per-sprite metadata slot and removes by swapping the last sprite into the freed index\n * (`lib/sprite/sprite-2d-handle.js`), so the map is a dense array kept in step by applying the same\n * swap rule.\n */\n\n/** How many sprites a new layer pre-allocates room for. */\nconst INITIAL_LAYER_CAPACITY = 64;\n\n/**\n * One Lite layer and everything the registry tracks alongside it.\n *\n * @public\n */\nexport interface SpriteLayerEntry {\n /** The composite key, built by {@link spriteLayerKey}. */\n readonly key: string;\n /** The sorting layer's name. */\n readonly sortingLayer: string;\n /** The Lite layer. */\n readonly layer: LiteSprite2DLayer;\n /** Whether the layer keeps the identity view instead of following the `Camera2D`. */\n readonly screenSpace: boolean;\n /** How many sprites the layer currently holds. */\n readonly count: number;\n /** Whether the layer is Y-sorted. */\n readonly ySort: boolean;\n}\n\n/**\n * The registry's internal record for one layer.\n */\ninterface LayerRecord {\n readonly key: string;\n readonly sortingLayer: string;\n readonly layer: LiteSprite2DLayer;\n readonly screenSpace: boolean;\n ySort: boolean;\n /** Component per dense sprite index; kept in step with Lite's swap-remove. */\n readonly components: (SpriteRenderer | null)[];\n}\n\n/**\n * Builds the composite key two sprites must share to land in one Lite layer.\n *\n * @param sortingLayer - The sorting layer's name.\n * @param atlasAddress - The atlas's address.\n * @param blend - The blend mode.\n * @param screenSpace - Whether the layer ignores the camera.\n * @returns The key.\n *\n * @public\n */\nexport function spriteLayerKey(\n sortingLayer: string,\n atlasAddress: string,\n blend: SpriteBlendName,\n screenSpace: boolean,\n): string {\n return `${sortingLayer}|${atlasAddress}|${blend}|${screenSpace ? \"screen\" : \"world\"}`;\n}\n\n/**\n * Owns every Lite sprite layer in one app.\n *\n * @public\n */\nexport class SpriteLayerRegistry {\n readonly #records = new Map<string, LayerRecord>();\n\n /** Records in draw order, rebuilt whenever a layer is created. */\n #ordered: LayerRecord[] = [];\n\n readonly #sortingLayers: SortingLayerTable;\n\n readonly #ySort: Readonly<Record<string, boolean>>;\n\n readonly #onLayerCreated: (layer: LiteSprite2DLayer) => void;\n\n readonly #onLayerRemoved: (layer: LiteSprite2DLayer) => void;\n\n /**\n * Supplies the compiled custom shader a sorting layer's layers are created with.\n *\n * @returns The shader, or `null` when no effect covers the layer.\n */\n #shaderFor: (sortingLayer: string) => LiteSpriteCustomShader | null = (): null => null;\n\n /**\n * Builds the registry.\n *\n * @param sortingLayers - Resolves a sorting-layer name to its draw order.\n * @param ySort - Which sorting layers draw back-to-front by world Y.\n * @param onLayerCreated - Called with each new Lite layer, so the sprite renderer can draw it.\n * @param onLayerRemoved - Called before a layer is dropped.\n */\n constructor(\n sortingLayers: SortingLayerTable,\n ySort: Readonly<Record<string, boolean>>,\n onLayerCreated: (layer: LiteSprite2DLayer) => void,\n onLayerRemoved: (layer: LiteSprite2DLayer) => void,\n ) {\n this.#sortingLayers = sortingLayers;\n this.#ySort = ySort;\n this.#onLayerCreated = onLayerCreated;\n this.#onLayerRemoved = onLayerRemoved;\n }\n\n /**\n * Installs the source of per-sorting-layer custom shaders.\n *\n * @remarks\n * `Sprite2DLayer.customShader` is `readonly` and is only read at creation, so a\n * `SpriteLayerEffect` has to be discoverable **before** the first sprite on its sorting layer is\n * placed. That is why the registry pulls the shader rather than the effect pushing it.\n *\n * @param provider - Returns the compiled shader for a sorting layer, or `null`.\n *\n * @internal\n */\n setShaderProvider(provider: (sortingLayer: string) => LiteSpriteCustomShader | null): void {\n this.#shaderFor = provider;\n }\n\n /**\n * Writes a sorting layer's `fx.params` vec4 onto every layer belonging to it.\n *\n * @param sortingLayer - The sorting layer's name.\n * @param params - The four components.\n *\n * @internal\n */\n writeShaderParams(sortingLayer: string, params: Float32Array): void {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined && record.sortingLayer === sortingLayer) {\n setShaderParams(record.layer, params[0] ?? 0, params[1] ?? 0, params[2] ?? 0, params[3] ?? 0);\n }\n }\n }\n\n /**\n * Every layer, in draw order.\n *\n * @returns A freshly allocated snapshot, for diagnostics.\n */\n describe(): readonly SpriteLayerEntry[] {\n const out: SpriteLayerEntry[] = [];\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined) {\n out.push({\n key: record.key,\n sortingLayer: record.sortingLayer,\n layer: record.layer,\n screenSpace: record.screenSpace,\n count: record.layer.count,\n ySort: record.ySort,\n });\n }\n }\n return out;\n }\n\n /**\n * The Lite layers, in draw order — what picking tests against.\n *\n * @param worldOnly - Whether to skip screen-space layers.\n * @param out - The array to fill; it is emptied first, so one array serves every frame.\n * @returns `out`.\n */\n collectLayers(worldOnly: boolean, out: LiteSprite2DLayer[]): LiteSprite2DLayer[] {\n out.length = 0;\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined && !(worldOnly && record.screenSpace)) {\n out.push(record.layer);\n }\n }\n return out;\n }\n\n /**\n * Walks every layer's view, so the camera can write world layers and skip screen-space ones.\n *\n * @param visit - Called with each layer and whether it follows the camera.\n *\n * @internal\n */\n forEachLayer(visit: (layer: LiteSprite2DLayer, screenSpace: boolean) => void): void {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined) {\n visit(record.layer, record.screenSpace);\n }\n }\n }\n\n /**\n * Adds a sprite to the layer its key selects, creating the layer when it is the first of its kind.\n *\n * @param component - The sprite component.\n * @param atlas - Its loaded atlas.\n * @param scratch - The reusable props record, already written.\n * @returns The key of the layer the sprite landed in.\n *\n * @internal\n */\n place(component: SpriteRenderer, atlas: SpriteAtlasAsset, scratch: SpriteScratch): string {\n const key = spriteLayerKey(component.sortingLayer, atlas.address, component.blend, component.screenSpace);\n const record = this.#ensure(key, component.sortingLayer, component.blend, component.screenSpace, atlas);\n const handle = addSprite(record.layer, scratch);\n const index = spriteIndexOf(handle);\n if (index >= 0) {\n record.components[index] = component;\n }\n component.setPlacement(handle, key);\n return key;\n }\n\n /**\n * Removes a sprite from whichever layer holds it.\n *\n * @param component - The sprite component.\n *\n * @internal\n */\n remove(component: SpriteRenderer): void {\n const placement = component.placement();\n if (placement === null) {\n return;\n }\n const record = this.#records.get(placement.key);\n const index = spriteIndexOf(placement.handle);\n if (record !== undefined && index >= 0) {\n // Lite swap-removes: the last sprite moves into the freed slot. Mirror that in the map.\n const last = record.components.length - 1;\n record.components[index] = record.components[last] ?? null;\n record.components.length = Math.max(0, last);\n }\n removeSprite(placement.handle);\n component.setPlacement(null, null);\n }\n\n /**\n * Adds a sprite that no `SpriteRenderer` owns — a tilemap's tiles.\n *\n * @remarks\n * The sprite occupies a slot in the same layers component-owned sprites use, so it sorts and\n * Y-sorts alongside them, but its slot in the pick map stays empty: `app.twoD.pickAt` resolves\n * `SpriteRenderer` components, and a tile is not one. Pick a tile with `Tilemap.worldToCell`\n * instead, which is exact and costs no draw-order search.\n *\n * @param sortingLayer - The sorting layer's name.\n * @param atlas - The atlas the sprite draws from.\n * @param blend - The blend mode.\n * @param screenSpace - Whether the layer ignores the camera.\n * @param scratch - The reusable props record, already written.\n * @returns The key and the handle.\n *\n * @internal\n */\n placeRaw(\n sortingLayer: string,\n atlas: SpriteAtlasAsset,\n blend: SpriteBlendName,\n screenSpace: boolean,\n scratch: SpriteScratch,\n ): { readonly key: string; readonly handle: LiteSprite2DHandle } {\n const key = spriteLayerKey(sortingLayer, atlas.address, blend, screenSpace);\n const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas);\n const handle = addSprite(record.layer, scratch);\n const index = spriteIndexOf(handle);\n if (index >= 0) {\n record.components[index] = null;\n }\n return { key, handle };\n }\n\n /**\n * Removes a sprite added by {@link SpriteLayerRegistry.placeRaw}.\n *\n * @param key - The key the sprite was placed under.\n * @param handle - The handle.\n *\n * @internal\n */\n removeRaw(key: string, handle: LiteSprite2DHandle): void {\n const record = this.#records.get(key);\n const index = spriteIndexOf(handle);\n if (record !== undefined && index >= 0) {\n const last = record.components.length - 1;\n record.components[index] = record.components[last] ?? null;\n record.components.length = Math.max(0, last);\n }\n removeSprite(handle);\n }\n\n /**\n * Applies a sprite's `orderInLayer` to the layer holding it.\n *\n * @remarks\n * Lite's Y-sort bias setter **throws** on a layer that has no Y-sort state\n * (`lib/sprite/sprite-2d-y-sort.js`, `setSprite2DYSortBias`), so the bias is only written to a\n * layer that is actually sorting. On a layer that is not, `orderInLayer` falls back to ordering\n * by insertion, which is exactly what `docs/architecture/11-2d-toolkit.md` §1 specifies:\n * \"applied as a Y-sort bias when Y-sort is on, or as sub-ordering by insertion when off\"*.\n *\n * @param key - The key of the layer holding the sprite.\n * @param handle - The sprite.\n * @param orderInLayer - The component's `orderInLayer`.\n *\n * @internal\n */\n applyOrderInLayer(key: string, handle: LiteSprite2DHandle, orderInLayer: number): void {\n if (this.#records.get(key)?.ySort === true) {\n setYSortOrder(handle, orderInLayer);\n }\n }\n\n /**\n * Resolves a pick hit back to the component that owns the sprite.\n *\n * @param layer - The Lite layer the hit is in.\n * @param spriteIndex - The dense index the hit reports.\n * @returns The component, or `null` when the slot is unmapped.\n *\n * @internal\n */\n componentAt(layer: LiteSprite2DLayer, spriteIndex: number): SpriteRenderer | null {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record?.layer === layer) {\n return record.components[spriteIndex] ?? null;\n }\n }\n return null;\n }\n\n /**\n * Empties every layer and drops them all.\n *\n * @internal\n */\n clear(): void {\n for (let index = 0; index < this.#ordered.length; index += 1) {\n const record = this.#ordered[index];\n if (record !== undefined) {\n clearLayer(record.layer);\n this.#onLayerRemoved(record.layer);\n }\n }\n this.#records.clear();\n this.#ordered = [];\n }\n\n /**\n * Finds or creates the layer a key names.\n *\n * @param key - The composite key.\n * @param sortingLayer - The sorting layer's name.\n * @param blend - The blend mode the layer draws with.\n * @param screenSpace - Whether the layer ignores the camera.\n * @param atlas - The atlas to bind the layer to.\n * @returns The record.\n */\n #ensure(\n key: string,\n sortingLayer: string,\n blend: SpriteBlendName,\n screenSpace: boolean,\n atlas: SpriteAtlasAsset,\n ): LayerRecord {\n const existing = this.#records.get(key);\n if (existing !== undefined) {\n return existing;\n }\n const liteAtlas = atlas.lite.atlas;\n if (liteAtlas === null) {\n throw new Error(\"a sprite layer needs an uploaded atlas; this app is headless\");\n }\n const base = this.#sortingLayers.orderOf(sortingLayer);\n // Sub-layers of one sorting layer are ordered by creation, which is stable across a run and\n // never crosses into the next sorting layer's slice.\n const order = base + this.#countIn(sortingLayer);\n const layer = createLayer(liteAtlas, {\n blend,\n order,\n capacity: INITIAL_LAYER_CAPACITY,\n customShader: this.#shaderFor(sortingLayer),\n });\n const ySort = !screenSpace && this.#ySort[sortingLayer] === true;\n if (ySort) {\n setYSort(layer, true);\n }\n const record: LayerRecord = {\n key,\n sortingLayer,\n layer,\n screenSpace,\n ySort,\n components: [],\n };\n this.#records.set(key, record);\n this.#ordered.push(record);\n this.#ordered.sort(byOrder);\n this.#onLayerCreated(layer);\n return record;\n }\n\n /**\n * How many layers a sorting layer already has, so the next one gets the next sub-order.\n *\n * @param sortingLayer - The sorting layer's name.\n * @returns The count.\n */\n #countIn(sortingLayer: string): number {\n let count = 0;\n for (const record of this.#records.values()) {\n if (record.sortingLayer === sortingLayer) {\n count += 1;\n }\n }\n return count;\n }\n}\n\n/**\n * Orders two layer records by their Lite draw order.\n *\n * @param left - One record.\n * @param right - The other.\n * @returns The comparison.\n */\nfunction byOrder(left: LayerRecord, right: LayerRecord): number {\n return left.layer.order - right.layer.order;\n}\n","import { compileLayerShader, visibleBounds } from \"../lite/sprite-layer.js\";\nimport { ParallaxLayer } from \"../sprite/parallax-layer.js\";\nimport { SpriteLayerEffect } from \"../sprite/sprite-layer-effect.js\";\nimport { TilemapRenderer } from \"../tilemap/tilemap-renderer.js\";\nimport { SpriteLayerRegistry } from \"./layer-registry.js\";\nimport { SortingLayerTable } from \"./sorting-layers.js\";\nimport type { Camera2D } from \"../camera/camera-2d.js\";\nimport type { LiteBounds2D, LiteSprite2DLayer, LiteSpriteCustomShader, LiteSpriteRenderer } from \"../lite/types.js\";\nimport type { TwoDSettings } from \"../settings.js\";\nimport type { App, Disconnect, SceneInstance, World } from \"@ignifx/core\";\n\n/**\n * The mutable state one app's 2D toolkit carries between frames: the resolved settings, the layer\n * registry, the Lite sprite renderer, and the active camera.\n *\n * It exists as its own object rather than as fields on the service because the sync system, the\n * animation system, and the service all need it, and none of them owns the others.\n *\n * ## Why the renderer is created lazily\n *\n * Lite requires the sprite renderer to be registered **after** `registerScene`, so that it\n * composites on top (`index.d.ts` 12205-12209). `@ignifx/core` registers the render scene inside\n * `app.start()`, *after* every extension's `onStart` has already run, and emits no signal when it\n * does — `RendererImpl.isSceneRegistered` is internal. So there is no hook an extension can use.\n * {@link TwoDRuntime.ensureRenderer} closes that gap: the sync system calls it at the top of every\n * `PreRender`, and the first such call happens inside Lite's own frame callback, which only runs\n * once the scene is registered and the loop is going.\n */\n\n/**\n * The Babylon Lite objects `app.twoD` owns.\n *\n * @public\n */\nexport interface TwoDLiteHandles {\n /** The sprite rendering context, or `null` under a headless app or before the first frame. */\n readonly renderer: LiteSpriteRenderer | null;\n}\n\n/**\n * What {@link TwoDRuntime} needs to build itself.\n *\n * @internal\n */\nexport interface TwoDRuntimeOptions {\n /** The app the runtime belongs to. */\n readonly app: App;\n /** The resolved `twoD` settings, options merged over the section. */\n readonly settings: TwoDSettings;\n /** The project's sorting layers, back to front. */\n readonly sortingLayers: readonly string[];\n /** Creates and registers the Lite sprite renderer; `null` under a headless app. */\n readonly createRenderer: (() => LiteSpriteRenderer) | null;\n /** Adds a layer to the renderer's draw list. */\n readonly attachLayer: (renderer: LiteSpriteRenderer, layer: LiteSprite2DLayer) => void;\n /** Removes a layer from the renderer's draw list. */\n readonly detachLayer: (renderer: LiteSpriteRenderer, layer: LiteSprite2DLayer) => void;\n /** Tears the renderer down. */\n readonly destroyRenderer: (renderer: LiteSpriteRenderer) => void;\n}\n\n/**\n * One app's 2D runtime state.\n *\n * @internal\n */\nexport class TwoDRuntime {\n readonly #app: App;\n\n #settings: TwoDSettings;\n\n readonly #sortingLayers: SortingLayerTable;\n\n readonly #registry: SpriteLayerRegistry;\n\n readonly #options: TwoDRuntimeOptions;\n\n #renderer: LiteSpriteRenderer | null = null;\n\n #hasTriedRenderer = false;\n\n #camera: Camera2D | null = null;\n\n #parallax: readonly ParallaxLayer[] = [];\n\n #syncedThisFrame = 0;\n\n #spriteCount = 0;\n\n /** Reused by {@link TwoDRuntime.cameraBounds}. */\n readonly #bounds: LiteBounds2D = { minX: 0, minY: 0, maxX: 0, maxY: 0 };\n\n /** Reused when collecting layers for a bounds read. */\n readonly #boundsLayers: LiteSprite2DLayer[] = [];\n\n /** The effects seen this frame, by sorting layer. */\n readonly #effects = new Map<string, SpriteLayerEffect>();\n\n /** Compiled shaders, cached by WGSL body so one source compiles once. */\n readonly #shaders = new Map<string, LiteSpriteCustomShader>();\n\n /** Reused by {@link TwoDRuntime.writeEffectParams}. */\n readonly #params = new Float32Array(4);\n\n /** Applies a scene file's `settings.twoD` block and spawns its tile objects. */\n #onSceneLoaded: ((scene: SceneInstance) => void) | null = null;\n\n /** Detaches the scene hook when the world goes away. */\n #disconnectScene: Disconnect | null = null;\n\n /**\n * Builds the runtime.\n *\n * @param options - The app, the settings, the sorting layers, and the Lite hooks.\n */\n constructor(options: TwoDRuntimeOptions) {\n this.#app = options.app;\n this.#settings = options.settings;\n this.#options = options;\n this.#sortingLayers = new SortingLayerTable(options.sortingLayers);\n this.#registry = new SpriteLayerRegistry(\n this.#sortingLayers,\n options.settings.ySort,\n (layer: LiteSprite2DLayer): void => {\n const renderer = this.#renderer;\n if (renderer !== null) {\n options.attachLayer(renderer, layer);\n }\n },\n (layer: LiteSprite2DLayer): void => {\n const renderer = this.#renderer;\n if (renderer !== null) {\n options.detachLayer(renderer, layer);\n }\n },\n );\n this.#registry.setShaderProvider((sortingLayer: string): LiteSpriteCustomShader | null =>\n this.#shaderFor(sortingLayer),\n );\n }\n\n /**\n * The resolved settings.\n *\n * @returns The `twoD` settings, after any scene-file override.\n */\n get settings(): TwoDSettings {\n return this.#settings;\n }\n\n /**\n * How many pixels one world metre spans.\n *\n * @returns The conversion factor.\n */\n get pixelsPerUnit(): number {\n return this.#settings.pixelsPerUnit;\n }\n\n /**\n * The sorting-layer resolver.\n *\n * @returns The table.\n */\n get sortingLayers(): SortingLayerTable {\n return this.#sortingLayers;\n }\n\n /**\n * The layer pool.\n *\n * @returns The registry.\n */\n get layers(): SpriteLayerRegistry {\n return this.#registry;\n }\n\n /**\n * The Lite sprite renderer, or `null`.\n *\n * @returns The renderer, or `null` under a headless app or before the first frame.\n */\n get renderer(): LiteSpriteRenderer | null {\n return this.#renderer;\n }\n\n /**\n * The camera the last frame drew through, or `null`.\n *\n * @returns The camera.\n */\n get mainCamera(): Camera2D | null {\n return this.#camera;\n }\n\n /**\n * How many sprites the last frame actually wrote to Lite.\n *\n * @returns The count.\n */\n get syncedLastFrame(): number {\n return this.#syncedThisFrame;\n }\n\n /**\n * How many `SpriteRenderer` components the last frame walked.\n *\n * @returns The count.\n */\n get spriteCount(): number {\n return this.#spriteCount;\n }\n\n /**\n * The surface width the views are sized against, in pixels.\n *\n * @returns The width; `0` under a headless app.\n */\n get viewportWidthPx(): number {\n const surface = this.#app.renderer.surface;\n return surface === null ? 0 : surface.width;\n }\n\n /**\n * The surface height the views are sized against, in pixels.\n *\n * @returns The height; `0` under a headless app.\n */\n get viewportHeightPx(): number {\n const surface = this.#app.renderer.surface;\n return surface === null ? 0 : surface.height;\n }\n\n /**\n * Installs the callback that reacts to a scene load.\n *\n * @remarks\n * The extension cannot connect `world.onSceneLoaded` itself: `register` runs before the world\n * exists, and `onStart` runs only when a game calls `app.start()` — which a headless tool or a\n * test may never do. `System.onWorldCreated` is the one hook that fires for every world, started\n * or not, so the sync system routes it here.\n *\n * @param handler - What to run for each loaded scene.\n */\n setSceneHandler(handler: (scene: SceneInstance) => void): void {\n this.#onSceneLoaded = handler;\n }\n\n /**\n * Connects the scene hook to a world.\n *\n * @param world - The world that was just created.\n */\n attachWorld(world: World): void {\n this.#disconnectScene?.();\n this.#disconnectScene = world.onSceneLoaded.connect((scene: SceneInstance): void => {\n this.#onSceneLoaded?.(scene);\n });\n }\n\n /**\n * Disconnects the scene hook.\n */\n detachWorld(): void {\n this.#disconnectScene?.();\n this.#disconnectScene = null;\n }\n\n /**\n * Replaces the settings, which a scene file's `settings.twoD` block does at load time.\n *\n * @param settings - The new settings.\n */\n applySettings(settings: TwoDSettings): void {\n this.#settings = settings;\n }\n\n /**\n * Records the frame's camera.\n *\n * @param camera - The camera, or `null`.\n */\n setMainCamera(camera: Camera2D | null): void {\n this.#camera = camera;\n }\n\n /**\n * Records the parallax components the sync system should offset views for.\n *\n * @param layers - The components.\n */\n setParallaxLayers(layers: readonly ParallaxLayer[]): void {\n this.#parallax = layers;\n }\n\n /**\n * Offsets each parallax layer's view by the camera's motion times `1 - factor`\n * (`docs/architecture/11-2d-toolkit.md` §2.6).\n */\n applyParallax(): void {\n const camera = this.#camera;\n if (camera === null || this.#parallax.length === 0) {\n return;\n }\n const entries = this.#registry.describe();\n for (let index = 0; index < this.#parallax.length; index += 1) {\n const layer = this.#parallax[index];\n if (layer === undefined || !layer.isEnabledInHierarchy) {\n continue;\n }\n layer.applyTo(entries, camera, this.#settings.pixelsPerUnit);\n }\n }\n\n /**\n * The layer-pixel rectangle the camera can currently see, for chunk culling.\n *\n * @remarks\n * Read off the first world layer's view, which the sync system has already written this frame.\n * Every world layer carries the same view, so any of them answers; `null` means there is no world\n * layer yet, in which case a tilemap builds every chunk and culls from the next frame on.\n *\n * @returns The bounds, or `null`.\n */\n cameraBounds(): LiteBounds2D | null {\n const layers = this.#registry.collectLayers(true, this.#boundsLayers);\n const first = layers[0];\n if (first === undefined || this.viewportWidthPx === 0) {\n return null;\n }\n return visibleBounds(first.view, this.viewportWidthPx, this.viewportHeightPx, this.#bounds);\n }\n\n /**\n * Advances every animated tile on the 2D animation clock.\n *\n * @remarks\n * Implements `AnimatedTilemapSink`, which is what lets the animation system drive tilemaps\n * without importing the renderer.\n *\n * @param world - The world holding the tilemaps.\n * @param deltaSeconds - The scaled frame delta.\n */\n advanceAnimatedTiles(world: World, deltaSeconds: number): void {\n const renderers = world.components(TilemapRenderer);\n for (let index = 0; index < renderers.length; index += 1) {\n const renderer = renderers[index];\n if (renderer !== undefined && renderer.isEnabledInHierarchy && renderer.advanceAnimation(deltaSeconds)) {\n renderer.invalidate();\n }\n }\n }\n\n /**\n * Records the enabled `SpriteLayerEffect` of each sorting layer, so the registry can reach one\n * when it creates a layer.\n *\n * @param world - The world to walk.\n */\n collectEffects(world: World): void {\n const effects = world.components(SpriteLayerEffect);\n this.#effects.clear();\n for (let index = 0; index < effects.length; index += 1) {\n const effect = effects[index];\n if (effect !== undefined && effect.isEnabledInHierarchy) {\n this.#effects.set(effect.sortingLayer, effect);\n }\n }\n const parallax: ParallaxLayer[] = [];\n const layers = world.components(ParallaxLayer);\n for (let index = 0; index < layers.length; index += 1) {\n const layer = layers[index];\n if (layer !== undefined) {\n parallax.push(layer);\n }\n }\n this.setParallaxLayers(parallax);\n }\n\n /**\n * Writes every effect's `fx.params` vec4 onto its sorting layer's Lite layers.\n */\n writeEffectParams(): void {\n for (const [sortingLayer, effect] of this.#effects) {\n effect.writeParams(this.#params);\n this.#registry.writeShaderParams(sortingLayer, this.#params);\n }\n }\n\n /**\n * The compiled custom shader a sorting layer's Lite layers are created with.\n *\n * @param sortingLayer - The sorting layer's name.\n * @returns The shader, or `null` when no effect covers the layer.\n */\n #shaderFor(sortingLayer: string): LiteSpriteCustomShader | null {\n const effect = this.#effects.get(sortingLayer);\n if (effect === undefined) {\n return null;\n }\n const source = effect.source();\n const cached = this.#shaders.get(source);\n if (cached !== undefined) {\n return cached;\n }\n const compiled = compileLayerShader(source);\n this.#shaders.set(source, compiled);\n return compiled;\n }\n\n /**\n * Publishes the frame's sync counters.\n *\n * @param synced - How many sprites were written.\n * @param total - How many sprite components were walked.\n */\n reportSynced(synced: number, total: number): void {\n this.#syncedThisFrame = synced;\n this.#spriteCount = total;\n }\n\n /**\n * Creates and registers the Lite sprite renderer, once, on the first frame that can.\n *\n * @remarks\n * Idempotent, and a no-op under a headless app or once a first attempt has failed. See the\n * module's own remarks for why this cannot happen in `onStart`.\n */\n ensureRenderer(): void {\n if (this.#hasTriedRenderer || this.#options.createRenderer === null) {\n return;\n }\n this.#hasTriedRenderer = true;\n const renderer = this.#options.createRenderer();\n this.#renderer = renderer;\n // Layers created before the renderer existed have to be attached now, in draw order.\n const entries = this.#registry.describe();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry !== undefined) {\n this.#options.attachLayer(renderer, entry.layer);\n }\n }\n }\n\n /**\n * Drops every layer and the renderer.\n */\n dispose(): void {\n this.detachWorld();\n this.#registry.clear();\n const renderer = this.#renderer;\n this.#renderer = null;\n if (renderer !== null) {\n this.#options.destroyRenderer(renderer);\n }\n }\n}\n","import type { TileCollisionInfo, TilemapCollisionChunk, TilemapCollisionData } from \"./collision-data.js\";\nimport type { Vec2Like } from \"@ignifx/core\";\n\n/**\n * The greedy merge that turns a grid of per-tile collision shapes into the handful of polygons a 2D\n * physics backend actually wants (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * A tilemap with ten thousand solid cells must not become ten thousand colliders: Rapier would\n * spend its whole broad-phase on them and the island solver would never sleep. Merging a solid\n * region into one polygon per rectangle is the standard fix, and it is worth doing at rebuild time\n * because a rebuild is rare and a step is not.\n */\n\n/**\n * The grid {@link mergeTileCollisions} walks.\n *\n * @public\n */\nexport interface CollisionMergeOptions {\n /** The edge length of one cell, in metres. */\n readonly cellSize: number;\n /** The edge length of one chunk, in cells; `32` is what `TilemapRenderer` uses. */\n readonly chunkSize: number;\n /** The grid's width, in cells. */\n readonly width: number;\n /** The grid's height, in cells. */\n readonly height: number;\n}\n\n/**\n * One maximal horizontal run of full-cell solid tiles inside a chunk, in chunk-local cells.\n */\ninterface SolidRun {\n /** The run's first column, chunk-local. */\n readonly start: number;\n /** The run's last column, chunk-local and inclusive. */\n readonly end: number;\n /** Whether an earlier row has already absorbed this run into a taller block. */\n consumed: boolean;\n}\n\n/**\n * Whether a tile's collider fills its whole cell and is not a one-way platform — the only shape the\n * rectangle merge can absorb.\n *\n * @param info - The tile's collision info, in cell-local metres.\n * @param cellSize - The edge length of one cell, in metres.\n * @returns Whether the tile is a plain, full-cell solid.\n *\n * @example\n * ```ts\n * isFullCellSolid({ shape: { kind: \"box\", x: 0, y: 0, width: 1, height: 1 }, oneWay: false, properties: {} }, 1);\n * // true\n * ```\n *\n * @public\n */\nexport function isFullCellSolid(info: TileCollisionInfo, cellSize: number): boolean {\n if (info.oneWay) {\n return false;\n }\n const shape = info.shape;\n return (\n shape.kind === \"box\" && shape.x === 0 && shape.y === 0 && shape.width === cellSize && shape.height === cellSize\n );\n}\n\n/**\n * Merges a grid of per-tile collision shapes into chunked, world-space polygons.\n *\n * @remarks\n * **Coordinates.** `infoAt` is called with cell coordinates in which `y = 0` is the **bottom** row,\n * because the ignifx 2D world is +Y up; a caller reading a `TilemapLayerDefinition`, whose rows run\n * top-first, indexes it as `(height - 1 - y) * width + x`. Everything this function emits is world\n * metres relative to the tilemap's origin, so cell `(x, y)` spans\n * `[x·cellSize, (x+1)·cellSize] × [y·cellSize, (y+1)·cellSize]`.\n *\n * **The merge.** Each chunk is handled independently, so a later edit rebuilds one chunk rather than\n * the map. Inside a chunk, cells that {@link isFullCellSolid} accepts go into a boolean grid and are\n * merged in two greedy passes: first every row is cut into maximal horizontal runs, then a run\n * extends upwards for as long as the row above holds a run with exactly the same span, which is\n * marked consumed. Each surviving block is emitted as one counter-clockwise rectangle. It is the\n * classic row-then-column greedy mesher: linear in cells plus a small scan per row, and optimal for\n * rectangles while deliberately not optimal in general — an L-shape comes out as two rectangles, not\n * one six-vertex polygon, and that is the trade the algorithm makes for being O(n).\n *\n * Anything the rectangle pass cannot absorb — a partial box, a slope polygon — is emitted as its own\n * polygon, translated into world metres. Its winding is already counter-clockwise, because\n * `tileCollisionInfo` guarantees it.\n *\n * **One-way platforms.** A one-way tile contributes no polygon at all; it contributes its collider's\n * **top edge** to `oneWayEdges`. The winding follows the same rule as a polygon: the solid material\n * is to the **left** of `from → to`. For a directed edge `d = to − from`, \"left\" is `d` rotated a\n * quarter turn counter-clockwise, `(−dy, dx)`. An upward-facing platform is solid *below* its\n * surface — that is the half you cannot pass through once you have landed — so we need\n * `(−dy, dx) = (0, −1)`, giving `dy = 0` and `dx = −1`. The edge therefore runs from its **right**\n * end to its **left** end.\n *\n * Chunks that end up with neither a polygon nor a one-way edge are omitted entirely.\n *\n * @param infoAt - The per-cell collision info, in cell coordinates with `y = 0` at the bottom.\n * @param options - The cell size, chunk size, and grid extent.\n * @param version - The version stamp to carry into the result; callers increment it per rebuild.\n * @returns The chunked collision data.\n *\n * @example\n * ```ts\n * const data = mergeTileCollisions((x, y) => tileCollisionInfo(map, tileAt(x, y)), {\n * cellSize: map.cellSize,\n * chunkSize: 32,\n * width: map.width,\n * height: map.height,\n * }, 1);\n * ```\n *\n * @public\n */\nexport function mergeTileCollisions(\n infoAt: (x: number, y: number) => TileCollisionInfo,\n options: CollisionMergeOptions,\n version: number,\n): TilemapCollisionData {\n const { cellSize, chunkSize, width, height } = options;\n const chunks: TilemapCollisionChunk[] = [];\n if (cellSize <= 0 || chunkSize <= 0 || width <= 0 || height <= 0) {\n return { cellSize, chunkSize, chunks, version };\n }\n const chunksX = Math.ceil(width / chunkSize);\n const chunksY = Math.ceil(height / chunkSize);\n for (let chunkY = 0; chunkY < chunksY; chunkY += 1) {\n for (let chunkX = 0; chunkX < chunksX; chunkX += 1) {\n const chunk = mergeChunk(infoAt, options, chunkX, chunkY);\n if (chunk !== null) {\n chunks.push(chunk);\n }\n }\n }\n return { cellSize, chunkSize, chunks, version };\n}\n\n/**\n * Merges one chunk of the grid.\n *\n * @param infoAt - The per-cell collision info.\n * @param options - The cell size, chunk size, and grid extent.\n * @param chunkX - The chunk's column index.\n * @param chunkY - The chunk's row index.\n * @returns The chunk, or `null` when it carries no geometry.\n */\nfunction mergeChunk(\n infoAt: (x: number, y: number) => TileCollisionInfo,\n options: CollisionMergeOptions,\n chunkX: number,\n chunkY: number,\n): TilemapCollisionChunk | null {\n const { cellSize, chunkSize, width, height } = options;\n const originX = chunkX * chunkSize;\n const originY = chunkY * chunkSize;\n const columns = Math.min(chunkSize, width - originX);\n const rows = Math.min(chunkSize, height - originY);\n const polygons: (readonly Vec2Like[])[] = [];\n const oneWayEdges: (readonly [Vec2Like, Vec2Like])[] = [];\n const solid = new Uint8Array(columns * rows);\n\n for (let localY = 0; localY < rows; localY += 1) {\n for (let localX = 0; localX < columns; localX += 1) {\n const cellX = originX + localX;\n const cellY = originY + localY;\n const info = infoAt(cellX, cellY);\n const shape = info.shape;\n if (shape.kind === \"none\") {\n continue;\n }\n if (info.oneWay) {\n const edge = topEdge(shape, cellX * cellSize, cellY * cellSize);\n if (edge !== null) {\n oneWayEdges.push(edge);\n }\n continue;\n }\n if (isFullCellSolid(info, cellSize)) {\n solid[localY * columns + localX] = 1;\n continue;\n }\n polygons.push(translateShape(shape, cellX * cellSize, cellY * cellSize));\n }\n }\n\n mergeSolidRuns(solid, columns, rows, originX, originY, cellSize, polygons);\n\n if (polygons.length === 0 && oneWayEdges.length === 0) {\n return null;\n }\n return { chunkX, chunkY, polygons, oneWayEdges };\n}\n\n/**\n * Runs the row-then-column greedy merge over the chunk's full-cell solid mask.\n *\n * @param solid - The `columns * rows` mask, row-major with row `0` at the bottom.\n * @param columns - The chunk's width in cells.\n * @param rows - The chunk's height in cells.\n * @param originX - The chunk's first column, in grid cells.\n * @param originY - The chunk's first row, in grid cells.\n * @param cellSize - The edge length of one cell, in metres.\n * @param out - The polygon list to append merged rectangles to.\n */\nfunction mergeSolidRuns(\n solid: Uint8Array,\n columns: number,\n rows: number,\n originX: number,\n originY: number,\n cellSize: number,\n out: (readonly Vec2Like[])[],\n): void {\n const runsByRow: SolidRun[][] = [];\n for (let localY = 0; localY < rows; localY += 1) {\n const runs: SolidRun[] = [];\n let localX = 0;\n while (localX < columns) {\n if (solid[localY * columns + localX] !== 1) {\n localX += 1;\n continue;\n }\n const start = localX;\n while (localX + 1 < columns && solid[localY * columns + localX + 1] === 1) {\n localX += 1;\n }\n runs.push({ start, end: localX, consumed: false });\n localX += 1;\n }\n runsByRow.push(runs);\n }\n\n for (let localY = 0; localY < rows; localY += 1) {\n const runs = runsByRow[localY];\n if (runs === undefined) {\n continue;\n }\n for (let index = 0; index < runs.length; index += 1) {\n const run = runs[index];\n if (run === undefined || run.consumed) {\n continue;\n }\n let top = localY;\n while (top + 1 < rows) {\n const above = findRun(runsByRow[top + 1], run.start, run.end);\n if (above === null) {\n break;\n }\n above.consumed = true;\n top += 1;\n }\n const left = (originX + run.start) * cellSize;\n const right = (originX + run.end + 1) * cellSize;\n const bottom = (originY + localY) * cellSize;\n const ceiling = (originY + top + 1) * cellSize;\n out.push([\n { x: left, y: bottom },\n { x: right, y: bottom },\n { x: right, y: ceiling },\n { x: left, y: ceiling },\n ]);\n }\n }\n}\n\n/**\n * Finds an unconsumed run with exactly the given span.\n *\n * @param runs - The candidate row's runs.\n * @param start - The span's first column.\n * @param end - The span's last column.\n * @returns The matching run, or `null`.\n */\nfunction findRun(runs: readonly SolidRun[] | undefined, start: number, end: number): SolidRun | null {\n if (runs === undefined) {\n return null;\n }\n for (let index = 0; index < runs.length; index += 1) {\n const run = runs[index];\n if (run !== undefined && !run.consumed && run.start === start && run.end === end) {\n return run;\n }\n }\n return null;\n}\n\n/**\n * Moves a cell-local shape into world metres.\n *\n * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.\n * @param offsetX - The cell's left edge, in world metres.\n * @param offsetY - The cell's bottom edge, in world metres.\n * @returns The outline, counter-clockwise, in world metres.\n */\nfunction translateShape(shape: TileCollisionInfo[\"shape\"], offsetX: number, offsetY: number): readonly Vec2Like[] {\n if (shape.kind === \"box\") {\n const left = offsetX + shape.x;\n const bottom = offsetY + shape.y;\n const right = left + shape.width;\n const top = bottom + shape.height;\n return [\n { x: left, y: bottom },\n { x: right, y: bottom },\n { x: right, y: top },\n { x: left, y: top },\n ];\n }\n if (shape.kind === \"polygon\") {\n const points: Vec2Like[] = [];\n for (let index = 0; index < shape.points.length; index += 1) {\n const point = shape.points[index];\n if (point !== undefined) {\n points.push({ x: offsetX + point.x, y: offsetY + point.y });\n }\n }\n return points;\n }\n return [];\n}\n\n/**\n * The top edge of a one-way tile's collider, wound so the solid side is to the left.\n *\n * @param shape - The tile's shape, in cell-local metres with a bottom-left origin.\n * @param offsetX - The cell's left edge, in world metres.\n * @param offsetY - The cell's bottom edge, in world metres.\n * @returns The `[from, to]` pair, right end first, or `null` when the shape has no width.\n */\nfunction topEdge(\n shape: TileCollisionInfo[\"shape\"],\n offsetX: number,\n offsetY: number,\n): readonly [Vec2Like, Vec2Like] | null {\n if (shape.kind === \"box\") {\n if (shape.width <= 0) {\n return null;\n }\n const left = offsetX + shape.x;\n const right = left + shape.width;\n const top = offsetY + shape.y + shape.height;\n return [\n { x: right, y: top },\n { x: left, y: top },\n ];\n }\n if (shape.kind === \"polygon\") {\n let left = Number.POSITIVE_INFINITY;\n let right = Number.NEGATIVE_INFINITY;\n let top = Number.NEGATIVE_INFINITY;\n for (let index = 0; index < shape.points.length; index += 1) {\n const point = shape.points[index];\n if (point === undefined) {\n continue;\n }\n left = Math.min(left, point.x);\n right = Math.max(right, point.x);\n top = Math.max(top, point.y);\n }\n if (!(right > left)) {\n return null;\n }\n return [\n { x: offsetX + right, y: offsetY + top },\n { x: offsetX + left, y: offsetY + top },\n ];\n }\n return null;\n}\n","import { resolveRelative } from \"../assets/relative.js\";\nimport { defineTilemap, TILEMAP_ASSET_TYPE, TILEMAP_FILE_EXTENSIONS } from \"./definition.js\";\nimport type { TilemapDefinition, TilemapInput } from \"./definition.js\";\nimport type { AssetLoader, LoaderContext } from \"@ignifx/core\";\n\n/**\n * The `tilemap` asset type and its loader (`docs/architecture/05-assets-and-loading.md` §5,\n * `11-2d-toolkit.md` §2.5).\n *\n * A `.tilemap.json` document is pure data — tile ids, tilesets, objects — so the loader needs no\n * device and behaves identically under a headless app, which is what lets a headless test assert\n * collision geometry and object spawning. The atlases the tilesets name are loaded by\n * `TilemapRenderer`, not here: a map with six tilesets in a scene that only shows one chunk should\n * not upload six textures at load time.\n */\n\n/**\n * A loaded tilemap document.\n *\n * @example\n * ```ts\n * const map = await app.assets.load<TilemapAsset>(\"2d/level-1.tilemap.json\").promise;\n * map.definition.layers.length; // 2\n * ```\n *\n * @public\n */\nexport class TilemapAsset {\n /** The type name the asset service registers tilemaps under. */\n static assetType: string = TILEMAP_ASSET_TYPE;\n\n /** The address the document was loaded from. */\n readonly address: string;\n\n /** The parsed document, with every tile layer decoded to a dense array. */\n readonly definition: TilemapDefinition;\n\n /** Each tileset's atlas address, resolved against this document's address. */\n readonly atlasAddresses: readonly string[];\n\n /**\n * Wraps a parsed document. The `tilemap` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The parsed document.\n *\n * @internal\n */\n constructor(address: string, definition: TilemapDefinition) {\n this.address = address;\n this.definition = definition;\n const atlases: string[] = [];\n for (let index = 0; index < definition.tilesets.length; index += 1) {\n const tileset = definition.tilesets[index];\n atlases.push(tileset === undefined ? \"\" : resolveRelative(address, tileset.atlas));\n }\n this.atlasAddresses = atlases;\n }\n\n /**\n * The atlas address a tileset's tiles come from.\n *\n * @param tilesetIndex - The tileset's index in the document.\n * @returns The address, or `\"\"` when the index is out of range.\n */\n atlasFor(tilesetIndex: number): string {\n return this.atlasAddresses[tilesetIndex] ?? \"\";\n }\n}\n\n/**\n * Builds the loader for `.tilemap.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createTilemapLoader());\n * ```\n *\n * @public\n */\nexport function createTilemapLoader(): AssetLoader<TilemapAsset> {\n return {\n type: TILEMAP_ASSET_TYPE,\n extensions: TILEMAP_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<TilemapAsset> {\n const raw = await ctx.fetchJson<TilemapInput>();\n return new TilemapAsset(ctx.address, defineTilemap(raw, ctx.address));\n },\n };\n}\n","import { asset, Component, createDefaults, defineSchema, f32, Signal, u32 } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { mergeTileCollisions } from \"./collision-merge.js\";\nimport { tileCollisionInfo } from \"./definition.js\";\nimport { TilemapAsset } from \"./tilemap-asset.js\";\nimport type { TileCollisionInfo, TilemapCollisionData } from \"./collision-data.js\";\nimport type { TilemapDefinition } from \"./definition.js\";\nimport type { AssetHandle, ComponentHooks, MutableVec2, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `Tilemap` (`docs/architecture/11-2d-toolkit.md` §2.5): the grid of tile ids a level is built\n * from, its cell arithmetic, and the merged collision geometry `@ignifx/physics-2d` consumes.\n *\n * The component holds no Lite object — `TilemapRenderer` draws it — so a headless app carries the\n * full grid and the full collision surface. That is what makes a level's collision testable\n * without a GPU, and what lets a server run the same map the client draws.\n *\n * ## Coordinates\n *\n * Cell `(0, 0)` is the **bottom-left** of the map, because ignifx 2D is +Y up (ADR-0011). The\n * document's own layers are stored top row first, as every editor writes them, and the component\n * flips on the way in. `worldToCell`/`cellToWorld` are relative to the tilemap entity's own\n * transform, so moving the entity moves the whole map.\n */\n\n/**\n * How many cells one chunk spans by default (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * @public\n */\nexport const DEFAULT_CHUNK_SIZE = 32;\n\n/**\n * One tile change, as {@link Tilemap.onTileChanged} reports it.\n *\n * @public\n */\nexport interface TileChange {\n /** The layer's index in the document. */\n readonly layer: number;\n /** The cell's column, with `0` at the left. */\n readonly x: number;\n /** The cell's row, with `0` at the **bottom**. */\n readonly y: number;\n /** The tile id that was there. */\n readonly previous: number;\n /** The tile id that is there now. */\n readonly current: number;\n}\n\n/**\n * A tilemap.\n *\n * @example\n * ```ts\n * const level = app.world.createEntity({ name: \"level\" }).addComponent(Tilemap);\n * level.map = app.assets.load<TilemapAsset>(\"2d/level-1.tilemap.json\").retain();\n * level.setTile(0, 3, 2, 0); // carve a hole in the ground layer\n * ```\n *\n * @public\n */\nexport class Tilemap extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/Tilemap\";\n\n /** One tilemap per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = tilemapSchema();\n\n /** The `.tilemap.json` document. */\n declare map: AssetHandle<TilemapAsset> | null;\n\n /** How many cells one chunk spans on each axis. */\n declare chunkSize: number;\n\n /** The metres one cell spans, overriding the document's own; `0` uses the document's. */\n declare cellSizeOverride: number;\n\n /** The mutable tile grids, bottom row first, one per document layer. */\n #grids: Int32Array[] = [];\n\n /** The document the grids were built from, so a swapped asset rebuilds them. */\n #built: TilemapAsset | null = null;\n\n /** The merged collision surface, rebuilt lazily after a change. */\n #collision: TilemapCollisionData = EMPTY_COLLISION;\n\n /** Whether the collision surface needs rebuilding. */\n #collisionDirty = true;\n\n /** Bumped on every collision rebuild, so a physics backend can skip unchanged frames. */\n #version = 0;\n\n readonly #onTileChanged = new Signal<TileChange>();\n\n readonly #onCollisionChanged = new Signal();\n\n /**\n * Builds a tilemap with the schema's defaults.\n */\n constructor() {\n super();\n Object.assign(this, createDefaults(Tilemap.schema));\n }\n\n /**\n * Drops the grids, so a recycled component does not inherit the previous one's.\n */\n onAttach(): void {\n this.#grids = [];\n this.#built = null;\n this.#collision = EMPTY_COLLISION;\n this.#collisionDirty = true;\n }\n\n /**\n * Releases the grids.\n */\n onDetach(): void {\n this.#grids = [];\n this.#built = null;\n }\n\n /**\n * Emitted whenever `setTile` changes a cell.\n *\n * @returns The signal.\n */\n get onTileChanged(): Signal<TileChange> {\n return this.#onTileChanged;\n }\n\n /**\n * Emitted after the merged collision surface has been rebuilt.\n *\n * @remarks\n * `@ignifx/physics-2d` connects to this and rebuilds only the chunks whose geometry moved. The\n * rebuild is lazy: the signal fires on the first read of {@link Tilemap.collisionData} after a\n * change, not on the `setTile` call itself, so a script that rewrites a thousand tiles in one\n * frame pays for one merge.\n *\n * @returns The signal.\n */\n get onCollisionChanged(): Signal {\n return this.#onCollisionChanged;\n }\n\n /**\n * The loaded document, or `null` while it is still loading.\n *\n * @returns The asset.\n */\n get asset(): TilemapAsset | null {\n const handle = this.map;\n return handle?.state === \"loaded\" ? handle.value : null;\n }\n\n /**\n * The parsed document, or `null`.\n *\n * @returns The definition.\n */\n get definition(): TilemapDefinition | null {\n return this.asset?.definition ?? null;\n }\n\n /**\n * How many metres one cell spans.\n *\n * @returns The cell size; `0` when nothing has loaded.\n */\n get cellSize(): number {\n if (this.cellSizeOverride > 0) {\n return this.cellSizeOverride;\n }\n return this.definition?.cellSize ?? 0;\n }\n\n /**\n * How many layers the document has.\n *\n * @returns The layer count.\n */\n get layerCount(): number {\n return this.definition?.layers.length ?? 0;\n }\n\n /**\n * The merged collision surface, rebuilt if a tile changed since the last read.\n *\n * @remarks\n * The shape is the contract `@ignifx/physics-2d` consumes: chunked, in world metres relative to\n * the tilemap entity's origin, with adjacent full-cell tiles merged into as few counter-clockwise\n * rectangles as possible.\n *\n * @returns The collision data.\n */\n get collisionData(): TilemapCollisionData {\n if (this.#collisionDirty) {\n this.#rebuildCollision();\n }\n return this.#collision;\n }\n\n /**\n * Reads a tile.\n *\n * @param layer - The layer's index in the document.\n * @param x - The cell's column, with `0` at the left.\n * @param y - The cell's row, with `0` at the bottom.\n * @returns The tile id, or `0` for an empty or out-of-range cell.\n */\n getTile(layer: number, x: number, y: number): number {\n this.#ensureGrids();\n const definition = this.definition;\n const grid = this.#grids[layer];\n const declared = definition?.layers[layer];\n if (grid === undefined || declared === undefined || !inRange(x, y, declared.width, declared.height)) {\n return 0;\n }\n return grid[y * declared.width + x] ?? 0;\n }\n\n /**\n * Writes a tile.\n *\n * @param layer - The layer's index in the document.\n * @param x - The cell's column, with `0` at the left.\n * @param y - The cell's row, with `0` at the bottom.\n * @param tileId - The tile id, or `0` to clear the cell.\n * @throws IgnifxError with code `IGX-1111` when the cell is outside the layer.\n */\n setTile(layer: number, x: number, y: number, tileId: number): void {\n this.#ensureGrids();\n const definition = this.definition;\n const grid = this.#grids[layer];\n const declared = definition?.layers[layer];\n if (grid === undefined || declared === undefined || !inRange(x, y, declared.width, declared.height)) {\n throw twoDError(\n TwoDErrorCode.tileOutOfRange,\n `Cell ${String(x)},${String(y)} is outside layer ${String(layer)}.`,\n {\n context: { x, y, layer },\n hint: \"Check the cell against Tilemap.layerSize; cell (0, 0) is the bottom-left.\",\n },\n );\n }\n const offset = y * declared.width + x;\n const previous = grid[offset] ?? 0;\n if (previous === tileId) {\n return;\n }\n grid[offset] = tileId;\n if (declared.collision) {\n this.#collisionDirty = true;\n }\n this.#onTileChanged.emit({ layer, x, y, previous, current: tileId });\n }\n\n /**\n * A layer's size, in cells.\n *\n * @param layer - The layer's index.\n * @returns The size, or a zero size for an unknown layer.\n */\n layerSize(layer: number): Vec2Like {\n const declared = this.definition?.layers[layer];\n return declared === undefined ? ZERO : { x: declared.width, y: declared.height };\n }\n\n /**\n * Converts a world point into the cell containing it.\n *\n * @remarks\n * The point is in world metres; the map's own origin is the tilemap entity's position, so a moved\n * or scaled tilemap still answers correctly. The result is floored, so a point exactly on a cell\n * boundary belongs to the cell above and to the right of it.\n *\n * @param point - The world point, in metres.\n * @param out - The vector to write.\n * @returns `out`, holding integer cell coordinates that may be outside the map.\n */\n worldToCell<TOut extends MutableVec2>(point: Vec2Like, out: TOut): TOut {\n const size = this.cellSize;\n const matrix = this.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n if (size <= 0) {\n out.x = 0;\n out.y = 0;\n return out;\n }\n out.x = Math.floor((point.x - originX) / size);\n out.y = Math.floor((point.y - originY) / size);\n return out;\n }\n\n /**\n * Converts a cell into the world point at its **centre**.\n *\n * @param x - The cell's column.\n * @param y - The cell's row, with `0` at the bottom.\n * @param out - The vector to write.\n * @returns `out`, in world metres.\n */\n cellToWorld<TOut extends MutableVec2>(x: number, y: number, out: TOut): TOut {\n const size = this.cellSize;\n const matrix = this.entity.transform.worldMatrix;\n out.x = (matrix[12] ?? 0) + (x + 0.5) * size;\n out.y = (matrix[13] ?? 0) + (y + 0.5) * size;\n return out;\n }\n\n /**\n * The collision footprint of whatever is at a cell, across every collision layer.\n *\n * @param x - The cell's column.\n * @param y - The cell's row, with `0` at the bottom.\n * @returns The topmost non-empty collider, or a `\"none\"` shape.\n */\n collisionAt(x: number, y: number): TileCollisionInfo {\n const definition = this.definition;\n if (definition === null) {\n return NO_COLLISION;\n }\n for (let layer = definition.layers.length - 1; layer >= 0; layer -= 1) {\n const declared = definition.layers[layer];\n if (declared === undefined || !declared.collision) {\n continue;\n }\n const info = tileCollisionInfo(definition, this.getTile(layer, x, y));\n if (info.shape.kind !== \"none\") {\n return info;\n }\n }\n return NO_COLLISION;\n }\n\n /**\n * Forces the collision surface to be rebuilt on the next read.\n *\n * @internal\n */\n invalidateCollision(): void {\n this.#collisionDirty = true;\n }\n\n /**\n * Builds the mutable grids from the document, flipping each layer bottom-row-first.\n */\n #ensureGrids(): void {\n const loaded = this.asset;\n if (loaded === null || loaded === this.#built) {\n return;\n }\n this.#built = loaded;\n this.#collisionDirty = true;\n const grids: Int32Array[] = [];\n const layers = loaded.definition.layers;\n for (let index = 0; index < layers.length; index += 1) {\n const layer = layers[index];\n if (layer === undefined) {\n grids.push(new Int32Array(0));\n continue;\n }\n const grid = new Int32Array(layer.width * layer.height);\n for (let row = 0; row < layer.height; row += 1) {\n // The document stores the top row first; cell row 0 is the bottom.\n const source = (layer.height - 1 - row) * layer.width;\n for (let column = 0; column < layer.width; column += 1) {\n grid[row * layer.width + column] = layer.tiles[source + column] ?? 0;\n }\n }\n grids.push(grid);\n }\n this.#grids = grids;\n }\n\n /**\n * Merges every collision layer's tiles into chunked polygons.\n */\n #rebuildCollision(): void {\n this.#ensureGrids();\n this.#collisionDirty = false;\n const definition = this.definition;\n const size = this.cellSize;\n if (definition === null || size <= 0) {\n this.#collision = EMPTY_COLLISION;\n return;\n }\n this.#version += 1;\n this.#collision = mergeTileCollisions(\n (x: number, y: number): TileCollisionInfo => this.collisionAt(x, y),\n { cellSize: size, chunkSize: Math.max(1, this.chunkSize), width: definition.width, height: definition.height },\n this.#version,\n );\n this.#onCollisionChanged.emit();\n }\n}\n\n/** The cell size a tilemap with nothing loaded reports. */\nconst ZERO: Vec2Like = Object.freeze({ x: 0, y: 0 });\n\n/** The collision surface of a tilemap with nothing loaded. */\nconst EMPTY_COLLISION: TilemapCollisionData = Object.freeze({\n cellSize: 0,\n chunkSize: 0,\n chunks: Object.freeze([]),\n version: 0,\n});\n\n/** The answer for a cell that carries no collider. */\nconst NO_COLLISION: TileCollisionInfo = Object.freeze({\n shape: Object.freeze({ kind: \"none\" as const }),\n oneWay: false,\n properties: Object.freeze({}),\n});\n\n/**\n * Whether a cell is inside a layer.\n *\n * @param x - The column.\n * @param y - The row.\n * @param width - The layer width, in cells.\n * @param height - The layer height, in cells.\n * @returns `true` when the cell exists.\n */\nfunction inRange(x: number, y: number, width: number, height: number): boolean {\n return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < width && y < height;\n}\n\n/**\n * The `Tilemap` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction tilemapSchema(): Schema {\n return defineSchema({\n map: asset(TilemapAsset, { tooltip: \"The .tilemap.json document.\" }),\n chunkSize: u32(DEFAULT_CHUNK_SIZE, { min: 1, tooltip: \"How many cells one render and collision chunk spans.\" }),\n cellSizeOverride: f32(0, { min: 0, tooltip: \"Metres per cell, overriding the document's own; 0 uses it.\" }),\n });\n}\n","import { Vec2 } from \"@ignifx/core\";\nimport { Camera2D } from \"../camera/camera-2d.js\";\nimport { centreView, createSpriteScratch, updateSprite, writeScratch, writeView } from \"../lite/sprite-layer.js\";\nimport { pivotedPositionToRef, spriteRotationToLite, viewRotationToLite, worldToPixelsToRef } from \"../math/coords.js\";\nimport { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\nimport { TilemapRenderer } from \"../tilemap/tilemap-renderer.js\";\nimport { Tilemap } from \"../tilemap/tilemap.js\";\nimport type { SpriteLayerRegistry } from \"./layer-registry.js\";\nimport type { TwoDRuntime } from \"./runtime.js\";\nimport type { SpriteScratch } from \"../lite/sprite-layer.js\";\nimport type { MutableVec2, System, SystemContext, Vec2Like, World } from \"@ignifx/core\";\n\n/**\n * The 2D sync system (`docs/architecture/11-2d-toolkit.md` §2.2,\n * `01-lifecycle-and-time.md` §3): once per frame, in `PreRender`, it selects the active\n * `Camera2D`, writes every world layer's view, and pushes every sprite whose transform or fields\n * changed into its Lite layer.\n *\n * ## Ordering\n *\n * `docs/architecture/11-2d-toolkit.md` §2.2 asks for `PreRender` order `-400`, but\n * `@ignifx/audio`'s spatial pump already occupies that exact slot\n * (`AUDIO_PUMP_ORDER`, `docs/architecture/10-audio.md` §5). Equal orders are broken by\n * registration order, which makes the interleaving depend on the order a game lists its\n * extensions in. The two systems touch nothing in common, so the tie would be harmless — but a\n * frame order that changes with an argument list is not something to leave in place, so 2D takes\n * {@link TWO_D_SYNC_ORDER} instead: after physics interpolation at `-500` has written the frame's\n * final transforms, before audio at `-400`, and well before core's render sync at `900`.\n *\n * ## Cost\n *\n * A sprite that did not move and whose fields did not change costs one integer comparison\n * (`Transform.worldMatrixVersion`), and an entity marked `isStatic` costs that comparison only\n * until its first sync. That is what keeps a 100x100 tilemap at zero per-frame sync cost once its\n * chunks are up (spike S6.1).\n */\n\n/**\n * The `PreRender` order the 2D sync system runs at.\n *\n * @remarks\n * `-450`, not the `-400` `docs/architecture/11-2d-toolkit.md` §2.2 names, because audio's pump\n * already holds `-400`. See the module's own remarks.\n *\n * @public\n */\nexport const TWO_D_SYNC_ORDER = -450;\n\n/**\n * Writes sprites and camera views into Babylon Lite once per frame.\n *\n * @public\n */\nexport class TwoDSyncSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name = \"ignifx/2d-sync\";\n\n readonly #runtime: TwoDRuntime;\n\n readonly #scratch: SpriteScratch = createSpriteScratch();\n\n readonly #pixels: MutableVec2 = new Vec2();\n\n readonly #position: MutableVec2 = new Vec2();\n\n readonly #boundsMin: MutableVec2 = new Vec2();\n\n readonly #boundsMax: MutableVec2 = new Vec2();\n\n /** Sprites seen this frame, so the ones that vanished can be dropped. */\n readonly #seen = new Set<SpriteRenderer>();\n\n /** Sprites that were placed in a layer on a previous frame. */\n readonly #placed = new Set<SpriteRenderer>();\n\n /**\n * Builds the system. The extension does this; a game never constructs one.\n *\n * @param runtime - The 2D runtime state: settings, the layer registry, and the Lite renderer.\n *\n * @internal\n */\n constructor(runtime: TwoDRuntime) {\n this.#runtime = runtime;\n }\n\n /**\n * Runs one frame's synchronisation.\n *\n * @param ctx - The world, clock, phase, and delta.\n */\n update(ctx: SystemContext): void {\n this.#runtime.ensureRenderer();\n this.#runtime.collectEffects(ctx.world);\n const camera = selectCamera(ctx.world);\n this.#runtime.setMainCamera(camera);\n this.#syncSprites(ctx.world);\n this.#syncViews(camera);\n this.#syncTilemaps(ctx.world);\n this.#runtime.writeEffectParams();\n }\n\n /**\n * Connects the scene hook to a new world.\n *\n * @remarks\n * This is the only hook that fires for every world. `register` runs before the world exists and\n * `onStart` runs only when a game calls `app.start()`, so a headless tool that loads a scene\n * without ever starting a loop would otherwise never see its `settings.twoD` block.\n *\n * @param world - The new world.\n */\n onWorldCreated(world: World): void {\n this.#runtime.attachWorld(world);\n }\n\n /**\n * Drops every layer when the world goes away.\n *\n * @param _world - The world being disposed.\n */\n onWorldDisposed(_world: World): void {\n this.#runtime.detachWorld();\n this.#placed.clear();\n this.#seen.clear();\n }\n\n /**\n * Brings each `TilemapRenderer`'s materialised chunks in line with what the camera can see.\n *\n * @remarks\n * This runs **after** the views have been written, because the chunk window is derived from the\n * camera's visible bounds and those live on a layer's view. A frame where the camera did not move\n * and no tile changed builds nothing.\n *\n * @param world - The world to walk.\n */\n #syncTilemaps(world: World): void {\n const runtime = this.#runtime;\n const renderers = world.components(TilemapRenderer);\n if (renderers.length === 0) {\n return;\n }\n const bounds = runtime.cameraBounds();\n for (let index = 0; index < renderers.length; index += 1) {\n const renderer = renderers[index];\n if (renderer === undefined || !renderer.isEnabledInHierarchy) {\n continue;\n }\n const map = renderer.entity.getComponent(Tilemap);\n if (map === null) {\n continue;\n }\n renderer.sync(map, runtime.layers, bounds, runtime.pixelsPerUnit);\n }\n }\n\n /**\n * Reconciles every `SpriteRenderer` against its Lite layer.\n *\n * @param world - The world to walk.\n */\n #syncSprites(world: World): void {\n const registry = this.#runtime.layers;\n const pixelsPerUnit = this.#runtime.pixelsPerUnit;\n const sprites = world.components(SpriteRenderer);\n this.#seen.clear();\n let synced = 0;\n for (let index = 0; index < sprites.length; index += 1) {\n const sprite = sprites[index];\n if (sprite === undefined) {\n continue;\n }\n this.#seen.add(sprite);\n const atlas = sprite.atlas;\n if (atlas === null || atlas.lite.atlas === null) {\n // Still loading, failed, or headless: nothing to draw, and nothing to pay for.\n continue;\n }\n const entity = sprite.entity;\n const isStatic = entity.isStatic;\n const matrixVersion = entity.transform.worldMatrixVersion;\n const placement = sprite.placement();\n const key = layerKeyOf(sprite, atlas.address);\n if (placement !== null && placement.key !== key) {\n // The sorting layer, atlas, blend, or space changed: the sprite moves, handle and all.\n registry.remove(sprite);\n this.#placed.delete(sprite);\n sprite.invalidate();\n }\n if (sprite.placement() !== null && !sprite.needsSync(isStatic, matrixVersion)) {\n continue;\n }\n this.#writeSprite(sprite, atlas.frameCount, pixelsPerUnit);\n const current = sprite.placement();\n if (current === null) {\n registry.place(sprite, atlas, this.#scratch);\n this.#placed.add(sprite);\n const placed = sprite.placement();\n if (placed !== null) {\n registry.applyOrderInLayer(placed.key, placed.handle, sprite.orderInLayer);\n }\n } else {\n updateSprite(current.handle, this.#scratch);\n registry.applyOrderInLayer(current.key, current.handle, sprite.orderInLayer);\n }\n sprite.markSynced(\n isStatic,\n matrixVersion,\n this.#boundsMin.x,\n this.#boundsMin.y,\n this.#boundsMax.x,\n this.#boundsMax.y,\n );\n synced += 1;\n }\n this.#dropVanished(registry);\n this.#runtime.reportSynced(synced, sprites.length);\n }\n\n /**\n * Removes sprites whose components are gone from the world.\n *\n * @param registry - The layer registry.\n */\n #dropVanished(registry: SpriteLayerRegistry): void {\n if (this.#placed.size === 0) {\n return;\n }\n for (const sprite of this.#placed) {\n if (!this.#seen.has(sprite) || sprite.isDestroyed) {\n registry.remove(sprite);\n this.#placed.delete(sprite);\n }\n }\n }\n\n /**\n * Writes one sprite's props into the reusable scratch record, and its world AABB into the two\n * scratch vectors the caller reads back.\n *\n * @param sprite - The component.\n * @param frameCount - How many frames the atlas has, so an out-of-range frame draws frame 0.\n * @param pixelsPerUnit - The pixels one metre spans.\n */\n #writeSprite(sprite: SpriteRenderer, frameCount: number, pixelsPerUnit: number): void {\n const atlas = sprite.atlas;\n const frame = sprite.frame >= 0 && sprite.frame < frameCount ? sprite.frame : 0;\n const info = atlas?.frame(frame) ?? null;\n const frameWidth = info?.widthPx ?? 0;\n const frameHeight = info?.heightPx ?? 0;\n const transform = sprite.entity.transform;\n const matrix = transform.worldMatrix;\n // Read the world matrix directly: `position2D`, `rotation2D` and `localScale2D` all allocate,\n // and `rotation2D` is the *local* angle, not the world one (`transform.ts` 349).\n const worldX = matrix[12] ?? 0;\n const worldY = matrix[13] ?? 0;\n const scaleX = Math.hypot(matrix[0] ?? 1, matrix[1] ?? 0);\n const scaleY = Math.hypot(matrix[4] ?? 0, matrix[5] ?? 1);\n const rotationDegrees = Math.atan2(matrix[1] ?? 0, matrix[0] ?? 1) * RAD_TO_DEG;\n const rotation = spriteRotationToLite(rotationDegrees);\n const widthPx = frameWidth * scaleX;\n const heightPx = frameHeight * scaleY;\n const anchor = worldToPixelsToRef(worldX, worldY, pixelsPerUnit, this.#pixels);\n const pivot = sprite.pivotOverride ?? info?.pivot ?? CENTRE_PIVOT;\n const placed = pivotedPositionToRef(anchor.x, anchor.y, pivot, widthPx, heightPx, rotation, this.#position);\n const tint = sprite.color;\n writeScratch(\n this.#scratch,\n placed.x,\n placed.y,\n widthPx,\n heightPx,\n frame,\n rotation,\n tint.r,\n tint.g,\n tint.b,\n tint.a,\n sprite.flipX,\n sprite.flipY,\n sprite.isEnabledInHierarchy,\n );\n // The world AABB of the unrotated quad, which `SpriteRenderer.bounds` reports.\n const halfWidth = widthPx / (2 * pixelsPerUnit);\n const halfHeight = heightPx / (2 * pixelsPerUnit);\n const centreX = worldX + ((0.5 - pivot.x) * widthPx) / pixelsPerUnit;\n const centreY = worldY - ((0.5 - pivot.y) * heightPx) / pixelsPerUnit;\n this.#boundsMin.x = centreX - halfWidth;\n this.#boundsMin.y = centreY - halfHeight;\n this.#boundsMax.x = centreX + halfWidth;\n this.#boundsMax.y = centreY + halfHeight;\n }\n\n /**\n * Writes the camera's view onto every world layer, and the identity view onto screen-space ones.\n *\n * @param camera - The active camera, or `null`.\n */\n #syncViews(camera: Camera2D | null): void {\n const runtime = this.#runtime;\n const width = runtime.viewportWidthPx;\n const height = runtime.viewportHeightPx;\n if (camera === null) {\n runtime.layers.forEachLayer((layer): void => {\n writeView(layer.view, 0, 0, 1, 0);\n });\n return;\n }\n const transform = camera.entity.transform;\n const matrix = transform.worldMatrix;\n camera.resolve(matrix[12] ?? 0, matrix[13] ?? 0, width, height, runtime.pixelsPerUnit);\n const centre = worldToPixelsToRef(camera.centre.x, camera.centre.y, runtime.pixelsPerUnit, this.#pixels);\n const rotation = viewRotationToLite(Math.atan2(matrix[1] ?? 0, matrix[0] ?? 1) * RAD_TO_DEG);\n const zoom = camera.zoom;\n const centreX = centre.x;\n const centreY = centre.y;\n runtime.layers.forEachLayer((layer, screenSpace): void => {\n if (screenSpace) {\n writeView(layer.view, 0, 0, 1, 0);\n return;\n }\n centreView(layer.view, centreX, centreY, width, height, zoom, rotation);\n });\n runtime.applyParallax();\n }\n}\n\n/** Degrees per radian, so the sync loop does not import a constant it would only divide by. */\nconst RAD_TO_DEG = 180 / Math.PI;\n\n/** The pivot used when neither the component nor the frame declares one. */\nconst CENTRE_PIVOT: Vec2Like = Object.freeze({ x: 0.5, y: 0.5 });\n\n/**\n * The layer key a sprite currently belongs to.\n *\n * @param sprite - The component.\n * @param atlasAddress - Its atlas's address.\n * @returns The key.\n */\nfunction layerKeyOf(sprite: SpriteRenderer, atlasAddress: string): string {\n return `${sprite.sortingLayer}|${atlasAddress}|${sprite.blend}|${sprite.screenSpace ? \"screen\" : \"world\"}`;\n}\n\n/**\n * Picks the camera the frame draws through: the highest-priority enabled `Camera2D`.\n *\n * @param world - The world to search.\n * @returns The camera, or `null` when the world has none enabled.\n *\n * @public\n */\nexport function selectCamera(world: World): Camera2D | null {\n const cameras = world.components(Camera2D);\n let best: Camera2D | null = null;\n for (let index = 0; index < cameras.length; index += 1) {\n const camera = cameras[index];\n if (camera === undefined || !camera.isEnabledInHierarchy) {\n continue;\n }\n if (best === null || camera.priority > best.priority) {\n best = camera;\n }\n }\n return best;\n}\n","import { Vec2 } from \"@ignifx/core\";\nimport { twoDError, TwoDErrorCode } from \"../errors.js\";\nimport { pickSprite, screenToLayer, visibleBounds } from \"../lite/sprite-layer.js\";\nimport { pixelsToWorldToRef } from \"../math/coords.js\";\nimport type { SpriteLayerEntry } from \"./layer-registry.js\";\nimport type { TwoDLiteHandles, TwoDRuntime } from \"./runtime.js\";\nimport type { Camera2D } from \"../camera/camera-2d.js\";\nimport type { LiteBounds2D, LiteSprite2DLayer } from \"../lite/types.js\";\nimport type { TwoDMode, TwoDSettings } from \"../settings.js\";\nimport type { SpriteRenderer } from \"../sprite/sprite-renderer.js\";\nimport type { Entity, MutableVec2, Vec2Like, World } from \"@ignifx/core\";\n\n/**\n * `app.twoD` (`docs/architecture/11-2d-toolkit.md` §1 and §5): the 2D toolkit's runtime surface.\n *\n * Everything a game reaches for that is not attached to an entity lives here — the pixels-per-unit\n * conversion, the camera the frame is drawn through, sprite picking, the tile-object factory\n * registry, the per-layer diagnostics, and the Lite escape hatch.\n */\n\n/**\n * What `app.twoD.pickAt` returns.\n *\n * @public\n */\nexport interface TwoDPick {\n /** The entity carrying the sprite that was hit. */\n readonly entity: Entity;\n /** The sprite component that was hit. */\n readonly component: SpriteRenderer;\n /** Where inside the sprite's quad the hit landed, in `[0, 1]`. */\n readonly u: number;\n /** Where inside the sprite's quad the hit landed, in `[0, 1]`. */\n readonly v: number;\n}\n\n/**\n * Builds the entities a tilemap's objects layer describes.\n *\n * @public\n */\nexport type TileObjectFactory = (context: TileObjectContext) => Entity | null;\n\n/**\n * What a {@link TileObjectFactory} is handed.\n *\n * @public\n */\nexport interface TileObjectContext {\n /** The world to create the entity in. */\n readonly world: World;\n /** The object's name, as the map wrote it. */\n readonly name: string;\n /** The object's type, which selected this factory. */\n readonly type: string;\n /** The object's bottom-left corner, in world metres relative to the tilemap entity. */\n readonly position: Vec2Like;\n /** The object's size, in world metres. */\n readonly size: Vec2Like;\n /** The object's custom properties. */\n readonly properties: Readonly<Record<string, string | number | boolean>>;\n /** The tilemap entity the object came from, so a factory can parent to it. */\n readonly tilemap: Entity;\n}\n\n/**\n * A caller-owned world-space box, so reading the camera's bounds allocates nothing.\n *\n * @public\n */\nexport interface WorldBox {\n /** The lower corner, in world metres. */\n readonly min: MutableVec2;\n /** The upper corner, in world metres. */\n readonly max: MutableVec2;\n}\n\n/**\n * The 2D service.\n *\n * @example\n * ```ts\n * const hit = app.twoD.pickAt(pointer.x, pointer.y);\n * if (hit !== null) {\n * hit.entity.destroy();\n * }\n * ```\n *\n * @public\n */\nexport class TwoDService {\n readonly #runtime: TwoDRuntime;\n\n readonly #factories = new Map<string, TileObjectFactory>();\n\n /** Reused by `pickAt`, so picking allocates nothing. */\n readonly #pickLayers: LiteSprite2DLayer[] = [];\n\n /** Reused by `visibleWorldBounds`. */\n readonly #bounds: LiteBounds2D = { minX: 0, minY: 0, maxX: 0, maxY: 0 };\n\n /** Reused by `pickAt`, so picking allocates nothing. */\n readonly #pickPoint = { x: 0, y: 0 };\n\n /** A one-element array reused by `pickAt`, because Lite's picker takes a list. */\n readonly #oneLayer: LiteSprite2DLayer[] = [];\n\n /**\n * Builds the service.\n *\n * @param runtime - The app's 2D runtime state.\n *\n * @internal\n */\n constructor(runtime: TwoDRuntime) {\n this.#runtime = runtime;\n }\n\n /**\n * How many pixels one world metre spans (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * @returns The conversion factor; `100` unless the project or a scene changed it.\n */\n get pixelsPerUnit(): number {\n return this.#runtime.pixelsPerUnit;\n }\n\n /**\n * Whether sprites are the whole frame or composite over the 3D scene.\n *\n * @returns The mode.\n */\n get mode(): TwoDMode {\n return this.#runtime.settings.mode;\n }\n\n /**\n * The resolved `twoD` settings, after any scene-file override.\n *\n * @returns The settings.\n */\n get settings(): TwoDSettings {\n return this.#runtime.settings;\n }\n\n /**\n * The camera the last frame was drawn through: the highest-priority enabled `Camera2D`.\n *\n * @returns The camera, or `null` when the world has none enabled.\n */\n get mainCamera(): Camera2D | null {\n return this.#runtime.mainCamera;\n }\n\n /**\n * The project's sorting layers, back to front.\n *\n * @returns The names.\n */\n get sortingLayers(): readonly string[] {\n return this.#runtime.sortingLayers.names;\n }\n\n /**\n * Every Lite sprite layer in draw order, for diagnostics and tests.\n *\n * @remarks\n * The snapshot is freshly allocated on each read; it is a debugging surface, not a per-frame one.\n *\n * @returns The layers.\n */\n get layers(): readonly SpriteLayerEntry[] {\n return this.#runtime.layers.describe();\n }\n\n /**\n * The Babylon Lite objects the toolkit owns. Unstable escape hatch\n * (`CONSTITUTION.md` §3.4).\n *\n * @returns The sprite rendering context, or `null` under a headless app or before the first frame.\n */\n get lite(): TwoDLiteHandles {\n return { renderer: this.#runtime.renderer };\n }\n\n /**\n * How many sprites the last frame actually wrote to Lite.\n *\n * @remarks\n * This is the number spike S6.1 watches: on a steady frame with a static tilemap it is the count\n * of sprites that genuinely moved, not the count that exist.\n *\n * @returns The count.\n */\n get syncedLastFrame(): number {\n return this.#runtime.syncedLastFrame;\n }\n\n /**\n * How many `SpriteRenderer` components the last frame walked.\n *\n * @returns The count.\n */\n get spriteCount(): number {\n return this.#runtime.spriteCount;\n }\n\n /**\n * Picks the topmost sprite under a viewport pixel (`docs/architecture/11-2d-toolkit.md` §5).\n *\n * @remarks\n * Picking is a CPU test against every world layer's instance data, in draw order — no GPU\n * readback and no frame of latency, which is what makes it usable from a click handler. It\n * resolves only `SpriteRenderer` components: a tilemap's tiles have no component, so use\n * `Tilemap.worldToCell` for those.\n *\n * @param xPx - The viewport x, in pixels from the left edge.\n * @param yPx - The viewport y, in pixels from the top edge.\n * @returns The hit, or `null` for a miss.\n */\n pickAt(xPx: number, yPx: number): TwoDPick | null {\n const layers = this.#runtime.layers.collectLayers(false, this.#pickLayers);\n // Front to back, one layer at a time: Lite's picker compares the point against each sprite's\n // stored `positionPx` without applying the view, so the point has to be unprojected through\n // *that* layer's view — and a world layer and a screen-space layer do not share one.\n for (let index = layers.length - 1; index >= 0; index -= 1) {\n const layer = layers[index];\n if (layer === undefined) {\n continue;\n }\n const point = screenToLayer(layer.view, xPx, yPx, this.#pickPoint);\n this.#oneLayer[0] = layer;\n const hit = pickSprite(this.#oneLayer, point.x, point.y);\n if (hit === null) {\n continue;\n }\n const component = this.#runtime.layers.componentAt(hit.layer, hit.spriteIndex);\n if (component !== null && component.pickable && !component.isDestroyed) {\n return { entity: component.entity, component, u: hit.u, v: hit.v };\n }\n }\n return null;\n }\n\n /**\n * The world-space rectangle the camera can currently see.\n *\n * @param out - The box to write: its `min` takes the lower corner and its `max` the upper.\n * @returns `true` when a camera and a layer existed to measure against.\n */\n visibleWorldBounds(out: WorldBox): boolean {\n const layers = this.#runtime.layers.collectLayers(true, this.#pickLayers);\n const first = layers[0];\n if (first === undefined) {\n return false;\n }\n visibleBounds(first.view, this.#runtime.viewportWidthPx, this.#runtime.viewportHeightPx, this.#bounds);\n const ppu = this.#runtime.pixelsPerUnit;\n // Layer pixels run +Y down, so the bounds' maxY is the world minimum.\n pixelsToWorldToRef(this.#bounds.minX, this.#bounds.maxY, ppu, out.min);\n pixelsToWorldToRef(this.#bounds.maxX, this.#bounds.minY, ppu, out.max);\n return true;\n }\n\n /**\n * Registers the factory that turns one kind of tilemap object into an entity\n * (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * @param type - The object `type` the map writes.\n * @param factory - Builds the entity, or returns `null` to spawn nothing.\n * @throws IgnifxError with code `IGX-1110` when a factory for the type is already registered.\n *\n * @example\n * ```ts\n * app.twoD.registerTileObjectFactory(\"spawn\", ({ world, position }) => {\n * const player = world.createEntity({ name: \"player\" });\n * player.transform.position2D = new Vec2(position.x, position.y);\n * return player;\n * });\n * ```\n */\n registerTileObjectFactory(type: string, factory: TileObjectFactory): void {\n if (this.#factories.has(type)) {\n throw twoDError(\n TwoDErrorCode.duplicateObjectFactory,\n `A tile object factory for ${type} is already registered.`,\n {\n context: { type },\n hint: \"Unregister the first one, or give the second object type its own name.\",\n },\n );\n }\n this.#factories.set(type, factory);\n }\n\n /**\n * Removes a tile-object factory.\n *\n * @param type - The object type.\n * @returns `true` when a factory was registered.\n */\n unregisterTileObjectFactory(type: string): boolean {\n return this.#factories.delete(type);\n }\n\n /**\n * The factory registered for an object type.\n *\n * @param type - The object type.\n * @returns The factory, or `null`.\n *\n * @internal\n */\n tileObjectFactory(type: string): TileObjectFactory | null {\n return this.#factories.get(type) ?? null;\n }\n\n /**\n * Converts a viewport pixel into a world point through the active camera.\n *\n * @param xPx - The viewport x.\n * @param yPx - The viewport y.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, or the origin when no camera is active.\n */\n screenToWorld(xPx: number, yPx: number, out: MutableVec2 = new Vec2()): MutableVec2 {\n const camera = this.#runtime.mainCamera;\n if (camera === null) {\n out.x = 0;\n out.y = 0;\n return out;\n }\n return camera.screenToWorld(xPx, yPx, out);\n }\n\n /**\n * Converts a world point into a viewport pixel through the active camera.\n *\n * @param point - The world point, in metres.\n * @param out - The vector to write; omitting it allocates one.\n * @returns `out`, or the origin when no camera is active.\n */\n worldToScreen(point: Vec2Like, out: MutableVec2 = new Vec2()): MutableVec2 {\n const camera = this.#runtime.mainCamera;\n if (camera === null) {\n out.x = 0;\n out.y = 0;\n return out;\n }\n return camera.worldToScreen(point, out);\n }\n}\n","import { bool, Color, defineSchema, enumOf, f32, map, RENDERING_SETTINGS_SECTION } from \"@ignifx/core\";\nimport type { App, ColorLike, RenderingSettings, Schema } from \"@ignifx/core\";\n\n/**\n * The `twoD` project settings section (`docs/architecture/04-extensions.md` §5,\n * `11-2d-toolkit.md` §1 and §7). Everything here is what a game writes in `ignifx.config.ts` or in\n * a scene file's `settings.twoD` block; the knobs a game changes per frame live on `app.twoD` and\n * on `Camera2D` instead.\n */\n\n/**\n * The section name as it appears in `ignifx.config.ts` and in a scene file's `settings` block.\n *\n * @public\n */\nexport const TWO_D_SETTINGS_SECTION = \"twoD\";\n\n/**\n * Every rendering mode the 2D toolkit supports, in the order an inspector should list them\n * (`docs/architecture/11-2d-toolkit.md` §1).\n *\n * @public\n */\nexport const TWO_D_MODES = [\"sprite\", \"mixed\"] as const;\n\n/**\n * How 2D composites with the 3D render scene.\n *\n * @remarks\n * `\"sprite\"` is a pure 2D game: sprites are the only thing drawn. `\"mixed\"` is 2.5D — the render\n * scene draws first and the sprite pass composites on top without clearing, so meshes and sprites\n * share a frame.\n *\n * @public\n */\nexport type TwoDMode = (typeof TWO_D_MODES)[number];\n\n/**\n * The resolved `twoD` settings section.\n *\n * @example\n * ```ts\n * // ignifx.config.ts\n * export default defineConfig({\n * sortingLayers: { sortingLayers: [\"Background\", \"Default\", \"Foreground\"] },\n * twoD: { mode: \"sprite\", pixelsPerUnit: 16, ySort: { Default: true } },\n * });\n * ```\n *\n * @public\n */\nexport interface TwoDSettings {\n /** Whether sprites are the whole frame (`\"sprite\"`) or composite over the 3D scene (`\"mixed\"`). */\n readonly mode: TwoDMode;\n /** How many pixels one world metre spans. Defaults to `100`. */\n readonly pixelsPerUnit: number;\n /**\n * Which sorting layers draw back-to-front by world Y rather than by `orderInLayer`. A layer the\n * record does not mention does not Y-sort.\n */\n readonly ySort: Readonly<Record<string, boolean>>;\n}\n\n/**\n * The values used for everything a project omits.\n *\n * @returns The default `twoD` section.\n *\n * @public\n */\nexport function defaultTwoDSettings(): TwoDSettings {\n return { mode: \"sprite\", pixelsPerUnit: 100, ySort: {} };\n}\n\n/**\n * The schema the `twoD` section is validated against, in `ignifx.config.ts` and in a scene file\n * alike.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function twoDSettingsSchema(): Schema {\n return defineSchema({\n mode: enumOf(TWO_D_MODES, \"sprite\"),\n pixelsPerUnit: f32(100, { min: Number.EPSILON }),\n ySort: map(bool(false)),\n });\n}\n\n/**\n * The value a `\"sprite\"`-mode frame is cleared to, read from the **core** `rendering.clearColor`\n * setting and decoded the way the 3D path decodes it.\n *\n * @remarks\n * A `\"sprite\"`-mode sprite pass owns the frame: it clears the swapchain itself and nothing the\n * render scene did survives underneath, so `rendering.clearColor` would otherwise have no effect at\n * all in a 2D game. The precedence the 3D path documents —\n * `Camera.clearColor`, then `Environment.clearColor`, then the setting\n * (`docs/architecture/07-rendering.md` §2.1) — has only its last rung here: neither of those two\n * components exists in a 2D scene, and `Camera2D` has no `clearColor` field of its own.\n *\n * Colours are sRGB everywhere in ignifx and Lite's clear values are linear, so the setting is\n * decoded on the way through exactly as `RendererImpl.applyClearColor` decodes it. That is what\n * makes a `\"sprite\"` frame and a `\"mixed\"` frame with the same setting the same colour on screen,\n * and it is also why a literal `#14181F` presents darker than its hex suggests.\n *\n * @param app - The app whose settings are read.\n * @returns The clear value, as straight linear RGBA in `0` to `1`.\n *\n * @internal\n */\nexport function spriteClearColor(app: App): ColorLike {\n const { clearColor } = app.settings.section<RenderingSettings>(RENDERING_SETTINGS_SECTION);\n return {\n r: Color.srgbToLinear(clearColor.r),\n g: Color.srgbToLinear(clearColor.g),\n b: Color.srgbToLinear(clearColor.b),\n a: clearColor.a,\n };\n}\n","import { Tilemap } from \"./tilemap.js\";\nimport type { TwoDService } from \"../service/two-d-service.js\";\nimport type { App, Entity, SceneInstance } from \"@ignifx/core\";\n\n/**\n * Spawning the entities a tilemap's objects layer describes\n * (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * A map editor's objects layer is a list of *intentions* — \"a player starts here\", \"this rectangle\n * is a trigger\" — and only the game knows what each one becomes. `app.twoD.registerTileObjectFactory`\n * is where a game says so, and this module is what runs those factories when a scene carrying a\n * `Tilemap` finishes loading.\n *\n * Objects are spawned **once per scene load**, on `world.onSceneLoaded`, after `awake` and\n * `onEnable` have flushed (`world.ts` 596-597), so a factory can reach any component the scene\n * declared.\n */\n\n/**\n * Runs the registered factory for every object in every `Tilemap` in a scene.\n *\n * @remarks\n * An object whose `type` has no registered factory is skipped silently: a map routinely carries\n * markers a given game does not use, and refusing to load the scene over one would make maps and\n * code impossible to version independently. A factory that throws is reported to `app.onError`\n * and the remaining objects still spawn, which is the same containment the frame loop gives a\n * script callback.\n *\n * A `Tilemap` whose document has not finished loading spawns nothing now; the next scene load, or\n * an explicit {@link spawnTilemapObjects} call, does it.\n *\n * @param app - The app.\n * @param service - The 2D service holding the factory registry.\n * @param scene - The scene that just loaded.\n *\n * @internal\n */\nexport function spawnTileObjects(app: App, service: TwoDService, scene: SceneInstance): void {\n const tilemaps = app.world.components(Tilemap);\n for (let index = 0; index < tilemaps.length; index += 1) {\n const tilemap = tilemaps[index];\n if (tilemap === undefined || tilemap.entity.scene !== scene) {\n continue;\n }\n spawnTilemapObjects(app, service, tilemap);\n }\n}\n\n/**\n * Runs the registered factory for every object in one tilemap.\n *\n * @param app - The app.\n * @param service - The 2D service holding the factory registry.\n * @param tilemap - The tilemap whose objects layer to walk.\n * @returns The entities that were created, in document order.\n *\n * @example\n * ```ts\n * app.twoD.registerTileObjectFactory(\"spawn\", ({ world, position }) => {\n * const player = world.createEntity({ name: \"player\" });\n * player.transform.position2D = new Vec2(position.x, position.y);\n * return player;\n * });\n * ```\n *\n * @public\n */\nexport function spawnTilemapObjects(app: App, service: TwoDService, tilemap: Tilemap): readonly Entity[] {\n const definition = tilemap.definition;\n if (definition === null) {\n return EMPTY;\n }\n const matrix = tilemap.entity.transform.worldMatrix;\n const originX = matrix[12] ?? 0;\n const originY = matrix[13] ?? 0;\n const spawned: Entity[] = [];\n for (let index = 0; index < definition.objects.length; index += 1) {\n const object = definition.objects[index];\n if (object === undefined) {\n continue;\n }\n const factory = service.tileObjectFactory(object.type);\n if (factory === null) {\n continue;\n }\n try {\n const entity = factory({\n world: app.world,\n name: object.name,\n type: object.type,\n position: { x: originX + object.x, y: originY + object.y },\n size: { x: object.width, y: object.height },\n properties: object.properties,\n tilemap: tilemap.entity,\n });\n if (entity !== null) {\n spawned.push(entity);\n }\n } catch (error: unknown) {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: tilemap.entity, component: tilemap });\n }\n }\n return spawned;\n}\n\n/** The result of spawning from a tilemap with nothing loaded. */\nconst EMPTY: readonly Entity[] = Object.freeze([]);\n","/**\n * The package's own version, reported as `Extension.version`\n * (`docs/architecture/04-extensions.md` §1). First-party packages ship one version line, so this\n * tracks `package.json` and the release tooling bumps both together.\n */\n\n/**\n * The `@ignifx/2d` version this build was cut from.\n *\n * @public\n */\nexport const VERSION = \"0.0.0\";\n","import { decodeProps, defineExtension, Phase } from \"@ignifx/core\";\nimport { TWO_D_ANIMATION_ORDER, TwoDAnimationSystem } from \"./animation/animation-system.js\";\nimport { createSpriteAnimationLoader } from \"./animation/loader.js\";\nimport { SpriteAnimator } from \"./animation/sprite-animator.js\";\nimport { createSpriteAtlasLoader } from \"./atlas/loader.js\";\nimport { defineTwoDAppProperty } from \"./augmentation.js\";\nimport { Camera2DFollow } from \"./camera/camera-2d-follow.js\";\nimport { Camera2D } from \"./camera/camera-2d.js\";\nimport { TWO_D_ERROR_MESSAGES } from \"./errors.js\";\nimport {\n attachLayer,\n createRegisteredSpriteRenderer,\n destroySpriteRenderer,\n detachLayer,\n enableSpriteDeviceLostRecovery,\n} from \"./lite/gpu/sprite-renderer.js\";\nimport { TwoDRuntime } from \"./service/runtime.js\";\nimport { selectCamera, TWO_D_SYNC_ORDER, TwoDSyncSystem } from \"./service/sync-system.js\";\nimport { TwoDService } from \"./service/two-d-service.js\";\nimport { defaultTwoDSettings, spriteClearColor, TWO_D_SETTINGS_SECTION, twoDSettingsSchema } from \"./settings.js\";\nimport { ParallaxLayer } from \"./sprite/parallax-layer.js\";\nimport { SpriteLayerEffect } from \"./sprite/sprite-layer-effect.js\";\nimport { SpriteRenderer } from \"./sprite/sprite-renderer.js\";\nimport { spawnTileObjects } from \"./tilemap/spawn-objects.js\";\nimport { createTilemapLoader } from \"./tilemap/tilemap-asset.js\";\nimport { TilemapRenderer } from \"./tilemap/tilemap-renderer.js\";\nimport { Tilemap } from \"./tilemap/tilemap.js\";\nimport { VERSION } from \"./version.js\";\nimport type { LiteSpriteRenderer } from \"./lite/types.js\";\nimport type { TwoDMode, TwoDSettings } from \"./settings.js\";\nimport type {\n App,\n Extension,\n ExtensionContext,\n JsonObject,\n JsonValue,\n SceneInstance,\n SortingLayersSettings,\n World,\n} from \"@ignifx/core\";\n\n/**\n * The `@ignifx/2d` extension (`docs/architecture/04-extensions.md` §1,\n * `11-2d-toolkit.md` §1). Registering it is the whole installation: `twoD()` gives a game\n * `app.twoD`, seven components, the `Camera2DFollow` script, three asset types, the `twoD` settings\n * section, and the two systems that drive sprites — the `PreRender` sync and the `PostUpdate`\n * animation clock.\n */\n\n/**\n * What `twoD()` accepts. Every field overrides the matching `twoD` settings section value.\n *\n * @public\n */\nexport interface TwoDOptions {\n /** Whether sprites are the whole frame (`\"sprite\"`) or composite over the 3D scene (`\"mixed\"`). */\n readonly mode?: TwoDMode;\n /** How many pixels one world metre spans. */\n readonly pixelsPerUnit?: number;\n /** Which sorting layers draw back-to-front by world Y. */\n readonly ySort?: Readonly<Record<string, boolean>>;\n}\n\n/**\n * Merges the extension's options over the resolved settings section.\n *\n * @param settings - The resolved `twoD` section.\n * @param options - What the game passed to `twoD(...)`.\n * @returns The effective settings.\n */\nfunction mergeSettings(settings: TwoDSettings, options: TwoDOptions): TwoDSettings {\n return {\n mode: options.mode ?? settings.mode,\n pixelsPerUnit: options.pixelsPerUnit ?? settings.pixelsPerUnit,\n ySort: options.ySort ?? settings.ySort,\n };\n}\n\n/**\n * The components the extension registers, in the order the API report lists them.\n *\n * @returns The classes.\n */\nfunction components(): readonly [\n typeof Camera2D,\n typeof SpriteRenderer,\n typeof SpriteAnimator,\n typeof Tilemap,\n typeof TilemapRenderer,\n typeof ParallaxLayer,\n typeof SpriteLayerEffect,\n typeof Camera2DFollow,\n] {\n return [\n Camera2D,\n SpriteRenderer,\n SpriteAnimator,\n Tilemap,\n TilemapRenderer,\n ParallaxLayer,\n SpriteLayerEffect,\n Camera2DFollow,\n ];\n}\n\n/**\n * Whether a JSON value is an object rather than an array, a primitive, or absent.\n *\n * @param value - The value read out of the scene file.\n * @returns `true` when the value can be decoded as a settings block.\n */\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads a scene file's `settings.twoD` block over the project's own settings.\n *\n * @remarks\n * `docs/architecture/11-2d-toolkit.md` §7 asks that a scene be able to override the mode, the PPU,\n * and the Y-sort table. `@ignifx/core` carries the block through to `SceneInstance.settings` as raw\n * JSON and fires `world.onSceneLoaded` once it is populated (`world.ts` 590 and 597) — but there is\n * no *validated* per-scene settings mechanism, no schema hook and no `IGX-0408` path, so the\n * extension validates its own block with `decodeProps` against the same schema\n * `registerSettings` uses. An invalid block is reported to `app.onError` and ignored rather than\n * taking the scene load down with it.\n *\n * @param app - The app.\n * @param runtime - The runtime whose settings the block replaces.\n * @param base - The settings the project resolved, which the block is applied over.\n * @param scene - The scene that just loaded.\n */\nfunction applySceneSettings(app: App, runtime: TwoDRuntime, base: TwoDSettings, scene: SceneInstance): void {\n const block = scene.settings?.[TWO_D_SETTINGS_SECTION];\n if (!isJsonObject(block)) {\n return;\n }\n const decoded = decodeProps(twoDSettingsSchema(), block, {\n entity: (): null => null,\n component: (): null => null,\n asset: (): null => null,\n });\n if (decoded.issues.length > 0) {\n app.onError.emit({\n error: new Error(`settings.twoD in ${scene.name} has ${String(decoded.issues.length)} invalid field(s)`),\n source: \"extension\",\n phase: null,\n entity: null,\n component: null,\n });\n return;\n }\n // `decodeProps` fills every absent field with its schema default, so an omitted key would\n // otherwise silently reset the project's value to 100 rather than leaving it alone. Only the\n // keys the block actually wrote may override.\n const value = decoded.value as Partial<TwoDSettings>;\n runtime.applySettings({\n mode: Object.hasOwn(block, \"mode\") && value.mode !== undefined ? value.mode : base.mode,\n pixelsPerUnit:\n Object.hasOwn(block, \"pixelsPerUnit\") && value.pixelsPerUnit !== undefined\n ? value.pixelsPerUnit\n : base.pixelsPerUnit,\n ySort: Object.hasOwn(block, \"ySort\") && value.ySort !== undefined ? value.ySort : base.ySort,\n });\n}\n\n/**\n * Registers everything the package contributes.\n *\n * @param ctx - The registration surface.\n * @param options - What the game passed to `twoD(...)`.\n */\nfunction registerTwoD(ctx: ExtensionContext, options: TwoDOptions): void {\n ctx.registerErrorCodes(TWO_D_ERROR_MESSAGES);\n ctx.registerSettings<TwoDSettings>(TWO_D_SETTINGS_SECTION, twoDSettingsSchema(), defaultTwoDSettings());\n const settings = mergeSettings(ctx.settings<TwoDSettings>(TWO_D_SETTINGS_SECTION), options);\n const app = ctx.app;\n const sorting = app.settings.section<SortingLayersSettings>(\"sortingLayers\").sortingLayers;\n const isHeadless = app.isHeadless;\n const runtime = new TwoDRuntime({\n app,\n settings,\n sortingLayers: sorting,\n createRenderer: isHeadless\n ? null\n : (): LiteSpriteRenderer =>\n // `clear: false` in \"mixed\" mode so the render scene's colour survives underneath\n // (`index.d.ts` 12222); in \"sprite\" mode the sprite pass owns the frame and clears it to\n // the project's `rendering.clearColor`, which nothing else in a 2D scene would apply.\n createRegisteredSpriteRenderer(app.lite.engine, settings.mode === \"sprite\", spriteClearColor(app)),\n attachLayer,\n detachLayer,\n destroyRenderer: destroySpriteRenderer,\n });\n const service = new TwoDService(runtime);\n ctx.registerService(TwoDService, service);\n defineTwoDAppProperty(ctx, service);\n ctx.registerSystem(new TwoDSyncSystem(runtime), { phase: Phase.PreRender, order: TWO_D_SYNC_ORDER });\n ctx.registerSystem(new TwoDAnimationSystem(runtime), { phase: Phase.PostUpdate, order: TWO_D_ANIMATION_ORDER });\n ctx.registerAssetLoader(createSpriteAtlasLoader());\n ctx.registerAssetLoader(createSpriteAnimationLoader());\n ctx.registerAssetLoader(createTilemapLoader());\n ctx.registerComponents(components());\n runtime.setSceneHandler((scene: SceneInstance): void => {\n applySceneSettings(app, runtime, settings, scene);\n spawnTileObjects(app, service, scene);\n });\n // A `Camera2D` is a camera as far as the frame is concerned, so a 2D-only world is not the\n // \"nothing is drawn\" case `IGX-0706` warns about. The world is re-examined on each ask rather\n // than the runtime's last-frame camera being reported, because core's render sync also runs once\n // inside `app.start()` — before the 2D sync system has picked a camera for the first time.\n const removeCameraSource = app.renderer.addCameraSource((world: World): boolean => selectCamera(world) !== null);\n ctx.onDispose((): void => {\n removeCameraSource();\n runtime.dispose();\n });\n}\n\n/**\n * Turns on device-lost recovery.\n *\n * @remarks\n * Recovery is enabled here, in `onStart`, and **before any atlas or layer exists**, because Lite\n * requires it: *\"Enable this before creating or loading sprite textures so their recovery sources\n * are retained\"* (`index.d.ts` 4372). `onStart` runs after every extension registered and after\n * the engine exists, but before the first frame — the only window where both conditions hold.\n *\n * @param app - The app being started.\n */\nfunction startTwoD(app: App): void {\n if (!app.isHeadless && app.renderer.features.deviceLostRecovery) {\n enableSpriteDeviceLostRecovery(\n app.lite.engine,\n (): void => {\n app.log.info(\"2D sprite resources recovered after device loss.\");\n },\n (error: unknown): void => {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: null, component: null });\n },\n );\n }\n}\n\n/**\n * The `@ignifx/2d` extension factory.\n *\n * @param options - Overrides for the `twoD` settings section.\n * @returns The extension descriptor to pass to `createApp`.\n *\n * @example\n * ```ts\n * const app = await createApp({\n * canvas,\n * extensions: [twoD({ pixelsPerUnit: 16, ySort: { Default: true } })],\n * });\n * ```\n *\n * @public\n */\nexport const twoD: (options?: TwoDOptions) => Extension = defineExtension<TwoDOptions | undefined>((raw) => {\n // `defineExtension` hands the factory whatever the caller passed, which is `undefined` when the\n // game wrote `twoD()`; the typed signature cannot express that, so the default lands here.\n const options: TwoDOptions = raw ?? {};\n return {\n name: \"@ignifx/2d\",\n version: VERSION,\n engine: \">=0.0.0 <1.0.0\",\n requires: [\"@ignifx/core\"],\n register(ctx: ExtensionContext): void {\n registerTwoD(ctx, options);\n },\n onStart(app: App): void {\n startTwoD(app);\n },\n };\n});\n","import { array, bool, defineSchema, enumOf, f32, i32, map, record, str, u32, vec2 } from \"@ignifx/core\";\nimport { SPRITE_ANIMATION_FORMAT, SPRITE_ANIMATION_FORMAT_VERSION } from \"./animation/definition.js\";\nimport { SPRITE_ATLAS_FORMAT, SPRITE_ATLAS_FORMAT_VERSION } from \"./atlas/definition.js\";\nimport { TILEMAP_FORMAT, TILEMAP_FORMAT_VERSION } from \"./tilemap/definition.js\";\nimport type { Schema } from \"@ignifx/core\";\n\n/**\n * Declarative schemas for the three file formats `@ignifx/2d` reads\n * (`docs/architecture/06-serialization-and-scene-format.md` §6).\n *\n * These exist for **documentation and tooling**, not for the loaders: a loader validates with its\n * own `defineX` function, which produces an actionable `IGX-11##` message naming the offending\n * frame or clip. The schema here is what `pnpm docs:schemas` renders into\n * `skills/ignifx/references/formats/`, and what a JSON Schema for an editor is generated from.\n *\n * The two descriptions are deliberately kept in one package so they cannot drift apart in a\n * release; a test asserts that a fixture accepted by the loader also validates against the schema.\n */\n\n/**\n * The `ignifx.spriteatlas` document schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function spriteAtlasFileSchema(): Schema {\n return defineSchema({\n format: str(SPRITE_ATLAS_FORMAT, { tooltip: \"Always ignifx.spriteatlas.\" }),\n formatVersion: u32(SPRITE_ATLAS_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n image: str(\"\", { tooltip: \"The image address, relative to this document.\" }),\n sampling: enumOf([\"linear\", \"nearest\"] as const, \"linear\", { tooltip: \"Min/mag filter; nearest for pixel art.\" }),\n premultipliedAlpha: bool(false, { tooltip: \"Whether the image's RGB is already multiplied by its alpha.\" }),\n frames: array(\n record({\n name: str(\"\", { tooltip: \"The frame's name; what #frame: addresses.\" }),\n x: f32(0, { min: 0, tooltip: \"The left edge, in image pixels.\" }),\n y: f32(0, { min: 0, tooltip: \"The top edge, in image pixels.\" }),\n w: f32(0, { min: 0, tooltip: \"The width, in image pixels.\" }),\n h: f32(0, { min: 0, tooltip: \"The height, in image pixels.\" }),\n pivot: vec2({ x: 0.5, y: 0.5 }, { tooltip: \"Pivot in [0,1] of the frame; [0,0] is top-left.\" }),\n sourceSize: vec2({ x: 0, y: 0 }, { tooltip: \"The untrimmed size, when the packer trimmed the frame.\" }),\n }),\n [],\n {\n tooltip:\n \"The frames, in the order they are indexed. Each is a record of \" +\n \"name (str, what #frame: addresses), x/y (f32, the top-left corner in image pixels), \" +\n \"w/h (f32, the size in image pixels), pivot (vec2 in [0,1] of the frame; [0,0] is top-left) \" +\n \"and sourceSize (vec2, the untrimmed size when the packer trimmed the frame).\",\n },\n ),\n });\n}\n\n/**\n * The `ignifx.spriteanimation` document schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function spriteAnimationFileSchema(): Schema {\n return defineSchema({\n format: str(SPRITE_ANIMATION_FORMAT, { tooltip: \"Always ignifx.spriteanimation.\" }),\n formatVersion: u32(SPRITE_ANIMATION_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n atlas: str(\"\", { tooltip: \"The .atlas.json address, relative to this document.\" }),\n clips: array(\n record({\n name: str(\"\", { tooltip: \"The clip's name; what SpriteAnimator.play takes.\" }),\n frames: array(str(), [], {\n tooltip: \"Atlas frame names, in play order; they need not be adjacent in the atlas.\",\n }),\n from: str(\"\", {\n tooltip:\n \"The atlas frame whose INDEX starts the range, when frames is empty. \" +\n \"Every atlas index between from and to is played, so the two must bracket a contiguous run.\",\n }),\n to: str(\"\", {\n tooltip: \"The atlas frame whose INDEX ends the range, inclusive; an index below from plays it backwards.\",\n }),\n fps: f32(12, { min: Number.EPSILON, tooltip: \"Frames per second.\" }),\n loop: bool(true, { tooltip: \"Whether the clip restarts at its end.\" }),\n events: array(\n record({\n frame: u32(0, { tooltip: \"The zero-based index within the clip, not the atlas.\" }),\n name: str(\"\", { tooltip: \"The name emitted on SpriteAnimator.onEvent.\" }),\n }),\n [],\n { tooltip: \"Events fired as the clip passes a frame.\" },\n ),\n }),\n [],\n {\n tooltip:\n \"The clips; the first is the default. Each is a record of \" +\n \"name (str, what SpriteAnimator.play takes), \" +\n \"frames (array of atlas frame names in play order, which need not be adjacent), \" +\n \"from/to (str: an INCLUSIVE range over atlas INDICES used when frames is empty — every index \" +\n \"between the two endpoints is played, in atlas order, so a range over non-adjacent frames plays \" +\n \"everything in between; to before from plays it backwards), \" +\n \"fps (f32, default 12), loop (bool, default true) and \" +\n \"events (array of { frame: u32 index within the clip, not the atlas; name: str }).\",\n },\n ),\n });\n}\n\n/**\n * The `ignifx.tilemap` document schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function tilemapFileSchema(): Schema {\n return defineSchema({\n format: str(TILEMAP_FORMAT, { tooltip: \"Always ignifx.tilemap.\" }),\n formatVersion: u32(TILEMAP_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n tileWidth: f32(32, { min: Number.EPSILON, tooltip: \"One cell's width, in pixels.\" }),\n tileHeight: f32(32, { min: Number.EPSILON, tooltip: \"One cell's height, in pixels.\" }),\n cellSize: f32(0.32, { min: Number.EPSILON, tooltip: \"One cell's size, in world metres.\" }),\n width: u32(0, { tooltip: \"The map's width, in cells.\" }),\n height: u32(0, { tooltip: \"The map's height, in cells.\" }),\n tilesets: array(\n record({\n name: str(\"\", { tooltip: \"The tileset's name; the frame-name prefix.\" }),\n atlas: str(\"\", { tooltip: \"The .atlas.json address; empty means collision-only.\" }),\n firstId: u32(1, { min: 1, tooltip: \"The global id of this tileset's first tile.\" }),\n }),\n [],\n { tooltip: \"The tilesets, ascending by firstId.\" },\n ),\n layers: array(\n record({\n name: str(\"\", { tooltip: \"The layer's name.\" }),\n sortingLayer: str(\"Default\", { tooltip: \"Which sorting layer the tiles draw on.\" }),\n orderInLayer: i32(0, { tooltip: \"Sub-order within the sorting layer.\" }),\n opacity: f32(1, { min: 0, max: 1, tooltip: \"The layer's alpha.\" }),\n parallax: vec2({ x: 1, y: 1 }, { tooltip: \"Fraction of the camera's motion the layer follows.\" }),\n collision: bool(false, { tooltip: \"Whether this layer's tiles contribute colliders.\" }),\n width: u32(0, { tooltip: \"The layer's width, in cells.\" }),\n height: u32(0, { tooltip: \"The layer's height, in cells.\" }),\n tiles: array(u32(), [], { tooltip: \"Tile ids, row-major, top row first; 0 is empty.\" }),\n }),\n [],\n { tooltip: \"The tile layers, back to front.\" },\n ),\n objects: array(\n record({\n name: str(\"\", { tooltip: \"The object's name.\" }),\n type: str(\"\", { tooltip: \"The object's type; what selects a TileObjectFactory.\" }),\n x: f32(0, { tooltip: \"The bottom-left corner, in world metres.\" }),\n y: f32(0, { tooltip: \"The bottom-left corner, in world metres.\" }),\n width: f32(0, { min: 0, tooltip: \"The width, in world metres.\" }),\n height: f32(0, { min: 0, tooltip: \"The height, in world metres.\" }),\n }),\n [],\n { tooltip: \"The objects layer.\" },\n ),\n properties: map(str(), { tooltip: \"The map's custom properties.\" }),\n });\n}\n","import { describeSchema, toJsonSchema } from \"@ignifx/core\";\nimport { SPRITE_ANIMATION_FORMAT } from \"./animation/definition.js\";\nimport { SpriteAnimator } from \"./animation/sprite-animator.js\";\nimport { SPRITE_ATLAS_FORMAT } from \"./atlas/definition.js\";\nimport { Camera2D } from \"./camera/camera-2d.js\";\nimport { spriteAtlasFileSchema, spriteAnimationFileSchema, tilemapFileSchema } from \"./file-schemas.js\";\nimport { ParallaxLayer } from \"./sprite/parallax-layer.js\";\nimport { SpriteLayerEffect } from \"./sprite/sprite-layer-effect.js\";\nimport { SpriteRenderer } from \"./sprite/sprite-renderer.js\";\nimport { TILEMAP_FORMAT } from \"./tilemap/definition.js\";\nimport { TilemapRenderer } from \"./tilemap/tilemap-renderer.js\";\nimport { Tilemap } from \"./tilemap/tilemap.js\";\nimport type { JsonSchemaObject, SchemaDescription } from \"@ignifx/core\";\n\n/**\n * The documentation harness's view of everything `@ignifx/2d` declares\n * (`scripts/README.md`, \"Schema discovery convention\";\n * `docs/architecture/16-docs-harness-and-skill.md` §3).\n *\n * The **function** form is what a package uses rather than a `schemas` object, because building the\n * record means calling `describeSchema` and module scope holds declarations only\n * (`CONSTITUTION.md` §3.5).\n */\n\n/**\n * Describes the `ignifx.spriteatlas` file format.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeSpriteAtlasFormat(): SchemaDescription {\n return describeSchema(\"ignifx/spriteatlas-file\", spriteAtlasFileSchema(), {\n title: \"Sprite atlas\",\n format: SPRITE_ATLAS_FORMAT,\n description: \"An image plus the frame rectangles inside it, in pixels with a top-left origin.\",\n });\n}\n\n/**\n * Describes the `ignifx.spriteanimation` file format.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeSpriteAnimationFormat(): SchemaDescription {\n return describeSchema(\"ignifx/spriteanimation-file\", spriteAnimationFileSchema(), {\n title: \"Sprite animation\",\n format: SPRITE_ANIMATION_FORMAT,\n description:\n \"Clips of atlas frames with a rate, a loop flag, and frame events. A clip names its frames \" +\n \"either as an explicit `frames` list of atlas frame names, played in the order written and \" +\n \"free to skip around the sheet, or as a `from`/`to` pair — and that pair is an **inclusive \" +\n \"range over atlas indices**, not two endpoints joined by name: every index between the two is \" +\n \"played, in atlas order, so a range whose endpoints are not adjacent in the sheet plays \" +\n \"whatever the packer put between them. Use `frames` for a run that is not contiguous.\",\n });\n}\n\n/**\n * Describes the `ignifx.tilemap` file format.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeTilemapFormat(): SchemaDescription {\n return describeSchema(\"ignifx/tilemap-file\", tilemapFileSchema(), {\n title: \"Tilemap\",\n format: TILEMAP_FORMAT,\n description: \"Tile size, layers of tile ids, tilesets with colliders, and an objects layer.\",\n });\n}\n\n/**\n * The JSON Schema a tool validates a `.atlas.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function spriteAtlasJsonSchema(): JsonSchemaObject {\n return toJsonSchema(spriteAtlasFileSchema());\n}\n\n/**\n * The JSON Schema a tool validates a `.spriteanim.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function spriteAnimationJsonSchema(): JsonSchemaObject {\n return toJsonSchema(spriteAnimationFileSchema());\n}\n\n/**\n * The JSON Schema a tool validates a `.tilemap.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function tilemapJsonSchema(): JsonSchemaObject {\n return toJsonSchema(tilemapFileSchema());\n}\n\n/**\n * Describes every component and file format this package declares, for the documentation harness.\n *\n * @returns The records, keyed by namespaced type id.\n *\n * @example\n * ```ts\n * describeTwoDSchemas()[\"ignifx/Camera2D\"].fields[\"orthographicSize\"].default; // 5\n * ```\n *\n * @public\n */\nexport function describeTwoDSchemas(): Readonly<Record<string, SchemaDescription>> {\n return {\n \"ignifx/Camera2D\": describeSchema(\"ignifx/Camera2D\", Camera2D.schema, {\n description: \"The 2D camera: orthographic size in metres, pixel-perfect snapping, bounds, and follow fields.\",\n }),\n \"ignifx/SpriteRenderer\": describeSchema(\"ignifx/SpriteRenderer\", SpriteRenderer.schema, {\n description: \"One sprite drawn from one frame of one atlas, on one sorting layer.\",\n }),\n \"ignifx/SpriteAnimator\": describeSchema(\"ignifx/SpriteAnimator\", SpriteAnimator.schema, {\n description: \"Plays a clip of atlas frames on ignifx's clock, respecting timeScale and pause.\",\n }),\n \"ignifx/Tilemap\": describeSchema(\"ignifx/Tilemap\", Tilemap.schema, {\n description: \"A grid of tile ids with cell arithmetic and merged collision geometry.\",\n }),\n \"ignifx/TilemapRenderer\": describeSchema(\"ignifx/TilemapRenderer\", TilemapRenderer.schema, {\n description: \"Draws a Tilemap's cells as sprites, materialising only the chunks the camera sees.\",\n }),\n \"ignifx/ParallaxLayer\": describeSchema(\"ignifx/ParallaxLayer\", ParallaxLayer.schema, {\n description: \"Scrolls one sorting layer at a fraction of the camera's speed.\",\n }),\n \"ignifx/SpriteLayerEffect\": describeSchema(\"ignifx/SpriteLayerEffect\", SpriteLayerEffect.schema, {\n description: \"A per-layer WGSL fragment effect with an fx.params vec4.\",\n }),\n \"ignifx/spriteatlas-file\": describeSpriteAtlasFormat(),\n \"ignifx/spriteanimation-file\": describeSpriteAnimationFormat(),\n \"ignifx/tilemap-file\": describeTilemapFormat(),\n };\n}\n\n/**\n * The name `pnpm docs:schemas` discovers this package's schemas under.\n *\n * @returns The same records {@link describeTwoDSchemas} returns.\n *\n * @public\n */\nexport function describeSchemas(): Readonly<Record<string, SchemaDescription>> {\n return describeTwoDSchemas();\n}\n","import { twoDError, TwoDErrorCode } from \"../../errors.js\";\nimport { DEFAULT_PIXELS_PER_UNIT } from \"../../math/coords.js\";\nimport { defineTilemap } from \"../definition.js\";\nimport type {\n TileColliderDefinition,\n TileDefinition,\n TilemapDefinition,\n TilemapLayerInput,\n TilemapObjectDefinition,\n TilesetDefinition,\n} from \"../definition.js\";\n\n/**\n * The **LDtk** importer: turns an `.ldtk` project into an `ignifx.tilemap` document for one of its\n * levels (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * Like the Tiled importer this is a pure function over parsed JSON. LDtk models a *project* of many\n * levels where ignifx models one map, so the importer picks a single level — by identifier, or the\n * first one — and flattens it.\n */\n\n/**\n * A parallax multiplier pair, structurally the `Vec2Like` the tilemap format stores. Declaring it\n * here rather than importing `Vec2Like` keeps this module's type imports to a single specifier,\n * which is the shape the formatter and the import-order rule agree on.\n */\ninterface ParallaxFactor {\n /** The horizontal multiplier; `1` moves with the camera. */\n readonly x: number;\n /** The vertical multiplier; `1` moves with the camera. */\n readonly y: number;\n}\n\n/** The name reported in `IGX-1109` context so a developer knows which importer complained. */\nconst IMPORTER_NAME = \"ldtk\";\n\n/** The layer types this importer understands; anything else is an `IGX-1109`. */\nconst SUPPORTED_LAYER_TYPES: readonly string[] = Object.freeze([\"Tiles\", \"IntGrid\", \"Entities\"]);\n\n/**\n * The name given to the synthetic tileset that carries IntGrid colliders.\n *\n * @public\n */\nexport const LDTK_INTGRID_TILESET_NAME = \"intgrid\";\n\n/**\n * The default meaning of an LDtk IntGrid value, in cell-normalised top-left-origin units.\n *\n * @remarks\n * `1` is \"solid\" — the whole cell collides. `2` is \"one-way\" — the top quarter of the cell collides,\n * and only from above. Those two conventions cover the LDtk projects people actually ship, and\n * anything else is project-specific, so {@link LdtkImportOptions.intGridColliders} replaces this\n * table wholesale. An IntGrid value with no entry still gets a tile id and a frame; it simply does\n * not collide.\n *\n * @public\n */\nexport const LDTK_DEFAULT_INTGRID_COLLIDERS: Readonly<Record<number, TileColliderDefinition>> = Object.freeze({\n 1: { kind: \"box\", x: 0, y: 0, width: 1, height: 1 },\n 2: { kind: \"box\", x: 0, y: 0, width: 1, height: 0.25, oneWay: true },\n});\n\n/**\n * How {@link importLdtkLevel} maps LDtk's conventions onto ignifx's.\n *\n * @public\n */\nexport interface LdtkImportOptions {\n /** The pixels one world metre spans. Defaults to `100`, matching `twoD.pixelsPerUnit`. */\n readonly pixelsPerUnit?: number;\n /** The `identifier` of the level to import. Defaults to the project's first level. */\n readonly level?: string;\n /** The sorting layer every layer lands in. Defaults to `\"Default\"`. */\n readonly sortingLayer?: string;\n /**\n * Maps an LDtk tileset's `relPath` onto the address of the ignifx `.atlas.json` generated from it.\n * Defaults to swapping the file extension for `.atlas.json`.\n */\n readonly atlasFor?: (relPath: string) => string;\n /** Replaces {@link LDTK_DEFAULT_INTGRID_COLLIDERS} for this import. */\n readonly intGridColliders?: Readonly<Record<number, TileColliderDefinition>>;\n}\n\n/**\n * Imports one level of an LDtk project.\n *\n * @remarks\n * Three LDtk conventions need translating, and each is a place a naive importer goes wrong:\n *\n * - **Layer order is reversed.** LDtk stores `layerInstances` front-to-back — index `0` is the\n * layer drawn on *top*. ignifx layers are back-to-front, so the list is reversed and\n * `orderInLayer` follows the reversed index.\n * - **Tile layers are sparse.** `gridTiles` is a list of `{ px, t }` placements, not a grid; the\n * importer expands it into the dense `__cWid * __cHei` array the tilemap format wants, filling\n * the gaps with `0`. `t` is a tile index *within its tileset*, so the global id is\n * `tileset.firstId + t`. A layer's `pxOffsetX`/`pxOffsetY` shift the grid; a dense grid has no\n * sub-cell placement, so the offset is rounded to whole cells.\n * - **IntGrid layers are collision, not art.** An `intGridCsv` becomes a layer with\n * `collision: true` whose ids point into a synthetic, art-less tileset named\n * {@link LDTK_INTGRID_TILESET_NAME}; see {@link LDTK_DEFAULT_INTGRID_COLLIDERS} for the value\n * mapping and {@link LdtkImportOptions.intGridColliders} for overriding it.\n *\n * A tileset's `customData` entries are read as JSON, and an entry that parses to an object with\n * `solid: true` gives its tile a full-cell box collider. Data that is not JSON, or that says\n * something else, is ignored rather than treated as an error — `customData` is a free-form field\n * and other tools put other things in it.\n *\n * Per-tile flips (`gridTiles[].f`) are dropped, as they are in the Tiled importer: the tilemap\n * format has no per-cell flip yet.\n *\n * @param ldtk - The parsed `.ldtk` project.\n * @param options - The level to pick, pixels-per-unit, the sorting layer, and the mappings.\n * @returns The `ignifx.tilemap` document for that level.\n * @throws IgnifxError with code `IGX-1109` when the project has no levels, when\n * {@link LdtkImportOptions.level} names a level that is not there, or when a layer's type is not\n * `Tiles`, `IntGrid` or `Entities`; and `IGX-1105` when what it decodes to is not a valid tilemap.\n *\n * @example\n * ```ts\n * const map = importLdtkLevel(JSON.parse(await readFile(\"world.ldtk\", \"utf8\")), { level: \"Cave\" });\n * ```\n *\n * @public\n */\nexport function importLdtkLevel(ldtk: unknown, options: LdtkImportOptions = {}): TilemapDefinition {\n const fail = (reason: string): never => {\n throw twoDError(TwoDErrorCode.unsupportedImport, `The LDtk importer cannot read this document: ${reason}.`, {\n context: { importer: IMPORTER_NAME, reason },\n hint: \"Re-save the project from LDtk 1.5 or later with the default (single-file) JSON layout.\",\n });\n };\n if (!isRecord(ldtk)) {\n return fail(\"it is not a JSON object\");\n }\n const levels = readArray(ldtk, \"levels\");\n if (levels.length === 0) {\n return fail(\"the project declares no levels\");\n }\n const wanted = options.level;\n const level = wanted === undefined ? firstRecord(levels) : findLevel(levels, wanted);\n if (level === null) {\n return fail(wanted === undefined ? \"its first level is not an object\" : `it declares no level named ${wanted}`);\n }\n\n const pixelsPerUnit = options.pixelsPerUnit ?? DEFAULT_PIXELS_PER_UNIT;\n const sortingLayer = options.sortingLayer ?? \"Default\";\n const atlasFor = options.atlasFor ?? defaultAtlasFor;\n const intGridColliders = options.intGridColliders ?? LDTK_DEFAULT_INTGRID_COLLIDERS;\n const defs = isRecord(ldtk[\"defs\"]) ? ldtk[\"defs\"] : null;\n const layerDefs = defs === null ? [] : readArray(defs, \"layers\");\n\n // LDtk stores layers front-to-back; ignifx draws index 0 first, so the list is reversed once here\n // and every downstream index — including `orderInLayer` — is in ignifx order.\n const instances: Readonly<Record<string, unknown>>[] = [];\n const rawInstances = readArray(level, \"layerInstances\");\n for (let index = rawInstances.length - 1; index >= 0; index -= 1) {\n const instance = rawInstances[index];\n if (isRecord(instance)) {\n const type = readString(instance, \"__type\", \"\");\n if (!SUPPORTED_LAYER_TYPES.includes(type)) {\n return fail(`layer ${readString(instance, \"__identifier\", \"?\")} has the unsupported type ${type}`);\n }\n instances.push(instance);\n }\n }\n\n const gridSize = resolveGridSize(instances, ldtk);\n const levelWidthPx = readNumber(level, \"pxWid\", 0);\n const levelHeightPx = readNumber(level, \"pxHei\", 0);\n const width = Math.max(1, Math.round(levelWidthPx / gridSize));\n const height = Math.max(1, Math.round(levelHeightPx / gridSize));\n\n const tilesets: TilesetDefinition[] = [];\n const tilesetsByUid = new Map<number, TilesetDefinition>();\n let nextFirstId = 1;\n const rawTilesets = defs === null ? [] : readArray(defs, \"tilesets\");\n for (let index = 0; index < rawTilesets.length; index += 1) {\n const raw = rawTilesets[index];\n if (!isRecord(raw)) {\n continue;\n }\n const tileset = readTileset(raw, nextFirstId, atlasFor);\n nextFirstId += tileset.tiles.length;\n tilesets.push(tileset);\n tilesetsByUid.set(readNumber(raw, \"uid\", -1), tileset);\n }\n\n const intGridTileset = buildIntGridTileset(instances, nextFirstId, intGridColliders);\n if (intGridTileset !== null) {\n tilesets.push(intGridTileset);\n }\n\n const layers: TilemapLayerInput[] = [];\n const objects: TilemapObjectDefinition[] = [];\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance === undefined) {\n continue;\n }\n const type = readString(instance, \"__type\", \"\");\n if (type === \"Entities\") {\n readEntities(instance, levelHeightPx, pixelsPerUnit, objects);\n continue;\n }\n const parallax = readParallax(layerDefs, readNumber(instance, \"layerDefUid\", -1));\n if (type === \"IntGrid\" && intGridTileset !== null) {\n layers.push(readIntGridLayer(instance, layers.length, sortingLayer, parallax, intGridTileset.firstId));\n continue;\n }\n if (type === \"Tiles\") {\n const tileset = tilesetsByUid.get(readNumber(instance, \"__tilesetDefUid\", -1)) ?? null;\n layers.push(readTilesLayer(instance, layers.length, sortingLayer, parallax, tileset));\n }\n }\n\n return defineTilemap(\n {\n tileWidth: gridSize,\n tileHeight: gridSize,\n cellSize: gridSize / pixelsPerUnit,\n width,\n height,\n tilesets,\n layers,\n objects,\n properties: fieldInstancesToRecord(level[\"fieldInstances\"]),\n },\n \"<ldtk>\",\n );\n}\n\n/**\n * Flattens LDtk's `[{ __identifier, __type, __value }]` field instances into a plain record.\n *\n * @remarks\n * Only `string`, `number` and `boolean` values survive. LDtk's richer field types — points, entity\n * references, arrays, enum tuples — have no equivalent in the tilemap format's flat property record\n * and are dropped rather than stringified.\n *\n * @param fields - The value of a `fieldInstances` field, or anything else.\n * @returns The flattened record; empty when `fields` is not a field-instance array.\n *\n * @example\n * ```ts\n * fieldInstancesToRecord([{ __identifier: \"facing\", __type: \"String\", __value: \"left\" }]);\n * // { facing: \"left\" }\n * ```\n *\n * @public\n */\nexport function fieldInstancesToRecord(fields: unknown): Readonly<Record<string, string | number | boolean>> {\n if (!isUnknownArray(fields)) {\n return {};\n }\n const out: Record<string, string | number | boolean> = {};\n for (let index = 0; index < fields.length; index += 1) {\n const field = fields[index];\n if (!isRecord(field)) {\n continue;\n }\n const name = field[\"__identifier\"];\n const value = field[\"__value\"];\n if (typeof name !== \"string\" || name === \"\") {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[name] = value;\n }\n }\n return out;\n}\n\n/**\n * Swaps a file extension for `.atlas.json`, the default {@link LdtkImportOptions.atlasFor}.\n *\n * @param relPath - The image path the editor recorded.\n * @returns The atlas address.\n */\nfunction defaultAtlasFor(relPath: string): string {\n const slash = Math.max(relPath.lastIndexOf(\"/\"), relPath.lastIndexOf(\"\\\\\"));\n const dot = relPath.lastIndexOf(\".\");\n return dot > slash ? `${relPath.slice(0, dot)}.atlas.json` : `${relPath}.atlas.json`;\n}\n\n/**\n * The first entry of a list that is an object.\n *\n * @param values - The parsed list.\n * @returns The first object, or `null`.\n */\nfunction firstRecord(values: readonly unknown[]): Readonly<Record<string, unknown>> | null {\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index];\n if (isRecord(value)) {\n return value;\n }\n }\n return null;\n}\n\n/**\n * Finds a level by its `identifier`.\n *\n * @param levels - The project's levels.\n * @param identifier - The level name to match.\n * @returns The level, or `null` when the project has no such level.\n */\nfunction findLevel(levels: readonly unknown[], identifier: string): Readonly<Record<string, unknown>> | null {\n for (let index = 0; index < levels.length; index += 1) {\n const level = levels[index];\n if (isRecord(level) && readString(level, \"identifier\", \"\") === identifier) {\n return level;\n }\n }\n return null;\n}\n\n/**\n * Picks the cell size of the level: the first layer's `__gridSize`, else the project default.\n *\n * @param instances - The level's layer instances, already filtered to objects.\n * @param project - The project root, for `defaultGridSize`.\n * @returns The grid size in pixels; never zero.\n */\nfunction resolveGridSize(\n instances: readonly Readonly<Record<string, unknown>>[],\n project: Readonly<Record<string, unknown>>,\n): number {\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance === undefined) {\n continue;\n }\n const size = readNumber(instance, \"__gridSize\", 0);\n if (size > 0) {\n return size;\n }\n }\n const fallback = readNumber(project, \"defaultGridSize\", 0);\n return fallback > 0 ? fallback : 16;\n}\n\n/**\n * Reads one LDtk tileset definition, including its `customData` colliders.\n *\n * @param raw - The tileset definition.\n * @param firstId - The global id this tileset's tile `0` takes.\n * @param atlasFor - The image-to-atlas address mapping.\n * @returns The tileset definition.\n */\nfunction readTileset(\n raw: Readonly<Record<string, unknown>>,\n firstId: number,\n atlasFor: (relPath: string) => string,\n): TilesetDefinition {\n const name = readString(raw, \"identifier\", `tileset${String(firstId)}`);\n const gridSize = Math.max(1, readNumber(raw, \"tileGridSize\", 16));\n const columns = readNumber(raw, \"__cWid\", Math.floor(readNumber(raw, \"pxWid\", 0) / gridSize));\n const rows = readNumber(raw, \"__cHei\", Math.floor(readNumber(raw, \"pxHei\", 0) / gridSize));\n const solid = new Set<number>();\n const customData = readArray(raw, \"customData\");\n for (let index = 0; index < customData.length; index += 1) {\n const entry = customData[index];\n if (isRecord(entry) && isSolidCustomData(entry[\"data\"])) {\n solid.add(readNumber(entry, \"tileId\", -1));\n }\n }\n const tiles: TileDefinition[] = [];\n const tileCount = Math.max(0, columns * rows);\n for (let localId = 0; localId < tileCount; localId += 1) {\n const frame = `${name}_${String(localId)}`;\n tiles.push(\n solid.has(localId)\n ? { id: localId, frame, collider: { kind: \"box\", x: 0, y: 0, width: 1, height: 1 } }\n : { id: localId, frame },\n );\n }\n return { name, atlas: atlasFor(readString(raw, \"relPath\", \"\")), firstId, tiles };\n}\n\n/**\n * Decides whether an LDtk `customData` payload marks its tile solid.\n *\n * @param data - The raw `data` string.\n * @returns Whether it parses as JSON with a `solid: true` field.\n */\nfunction isSolidCustomData(data: unknown): boolean {\n if (typeof data !== \"string\" || data === \"\") {\n return false;\n }\n try {\n const parsed: unknown = JSON.parse(data);\n return isRecord(parsed) && parsed[\"solid\"] === true;\n } catch {\n // `customData` is free-form; other tools store plain text in it. Not JSON simply means \"no\n // collider\", which is the same answer as an absent entry.\n return false;\n }\n}\n\n/**\n * Builds the synthetic, art-less tileset the IntGrid layers point into.\n *\n * @param instances - The level's layer instances, in ignifx order.\n * @param firstId - The global id the synthetic tile for IntGrid value `1` takes.\n * @param colliders - The IntGrid value to collider mapping.\n * @returns The tileset, or `null` when the level has no IntGrid data.\n */\nfunction buildIntGridTileset(\n instances: readonly Readonly<Record<string, unknown>>[],\n firstId: number,\n colliders: Readonly<Record<number, TileColliderDefinition>>,\n): TilesetDefinition | null {\n let maxValue = 0;\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance === undefined || readString(instance, \"__type\", \"\") !== \"IntGrid\") {\n continue;\n }\n const csv = readArray(instance, \"intGridCsv\");\n for (let cell = 0; cell < csv.length; cell += 1) {\n const value = csv[cell];\n if (typeof value === \"number\" && value > maxValue) {\n maxValue = value;\n }\n }\n }\n if (maxValue <= 0) {\n return null;\n }\n const tiles: TileDefinition[] = [];\n for (let value = 1; value <= maxValue; value += 1) {\n const frame = `${LDTK_INTGRID_TILESET_NAME}_${String(value)}`;\n const collider = colliders[value];\n tiles.push(collider === undefined ? { id: value - 1, frame } : { id: value - 1, frame, collider });\n }\n // The atlas address is deliberately empty: an IntGrid layer is collision, not art, and there is\n // no image to cut frames from.\n return { name: LDTK_INTGRID_TILESET_NAME, atlas: \"\", firstId, tiles };\n}\n\n/**\n * Converts an LDtk parallax factor pair into an ignifx parallax multiplier.\n *\n * @remarks\n * LDtk's `parallaxFactorX` is an offset *fraction*: `0` means the layer sits still relative to the\n * level, and a positive factor makes it lag the camera. ignifx's `parallax` is a speed multiplier\n * where `1` moves with the camera, so the two are related by `multiplier = 1 - factor`.\n *\n * @param layerDefs - The project's `defs.layers`.\n * @param uid - The `layerDefUid` to look up.\n * @returns The parallax multiplier.\n */\nfunction readParallax(layerDefs: readonly unknown[], uid: number): ParallaxFactor {\n for (let index = 0; index < layerDefs.length; index += 1) {\n const def = layerDefs[index];\n if (isRecord(def) && readNumber(def, \"uid\", -1) === uid) {\n return { x: 1 - readNumber(def, \"parallaxFactorX\", 0), y: 1 - readNumber(def, \"parallaxFactorY\", 0) };\n }\n }\n return { x: 1, y: 1 };\n}\n\n/**\n * Expands an LDtk `Tiles` layer's sparse `gridTiles` into a dense tile array.\n *\n * @param instance - The layer instance.\n * @param order - The layer's position in ignifx order.\n * @param sortingLayer - The sorting layer to place it in.\n * @param parallax - The parallax multiplier.\n * @param tileset - The tileset the layer draws from, or `null` when it names none.\n * @returns The layer input.\n */\nfunction readTilesLayer(\n instance: Readonly<Record<string, unknown>>,\n order: number,\n sortingLayer: string,\n parallax: ParallaxFactor,\n tileset: TilesetDefinition | null,\n): TilemapLayerInput {\n const columns = Math.max(0, readNumber(instance, \"__cWid\", 0));\n const rows = Math.max(0, readNumber(instance, \"__cHei\", 0));\n const gridSize = Math.max(1, readNumber(instance, \"__gridSize\", 1));\n const offsetX = Math.round(readNumber(instance, \"pxOffsetX\", 0) / gridSize);\n const offsetY = Math.round(readNumber(instance, \"pxOffsetY\", 0) / gridSize);\n const firstId = tileset === null ? 1 : tileset.firstId;\n const tiles = Array.from({ length: columns * rows }, (): number => 0);\n const gridTiles = readArray(instance, \"gridTiles\");\n for (let index = 0; index < gridTiles.length; index += 1) {\n const gridTile = gridTiles[index];\n if (!isRecord(gridTile)) {\n continue;\n }\n const px = gridTile[\"px\"];\n if (!isUnknownArray(px)) {\n continue;\n }\n const rawX = px[0];\n const rawY = px[1];\n if (typeof rawX !== \"number\" || typeof rawY !== \"number\") {\n continue;\n }\n const cellX = Math.floor(rawX / gridSize) + offsetX;\n const cellY = Math.floor(rawY / gridSize) + offsetY;\n if (cellX < 0 || cellY < 0 || cellX >= columns || cellY >= rows) {\n continue;\n }\n tiles[cellY * columns + cellX] = firstId + readNumber(gridTile, \"t\", 0);\n }\n return {\n name: readString(instance, \"__identifier\", `Layer ${String(order)}`),\n sortingLayer,\n orderInLayer: order,\n opacity: readNumber(instance, \"__opacity\", 1),\n parallax,\n collision: false,\n width: columns,\n height: rows,\n tiles,\n };\n}\n\n/**\n * Turns an LDtk `IntGrid` layer's `intGridCsv` into a collision layer over the synthetic tileset.\n *\n * @param instance - The layer instance.\n * @param order - The layer's position in ignifx order.\n * @param sortingLayer - The sorting layer to place it in.\n * @param parallax - The parallax multiplier.\n * @param firstId - The synthetic tileset's `firstId`.\n * @returns The layer input.\n */\nfunction readIntGridLayer(\n instance: Readonly<Record<string, unknown>>,\n order: number,\n sortingLayer: string,\n parallax: ParallaxFactor,\n firstId: number,\n): TilemapLayerInput {\n const columns = Math.max(0, readNumber(instance, \"__cWid\", 0));\n const rows = Math.max(0, readNumber(instance, \"__cHei\", 0));\n const csv = readArray(instance, \"intGridCsv\");\n const tiles = Array.from({ length: columns * rows }, (): number => 0);\n for (let index = 0; index < tiles.length && index < csv.length; index += 1) {\n const value = csv[index];\n if (typeof value === \"number\" && value > 0) {\n tiles[index] = firstId + (value - 1);\n }\n }\n return {\n name: readString(instance, \"__identifier\", `Layer ${String(order)}`),\n sortingLayer,\n orderInLayer: order,\n opacity: readNumber(instance, \"__opacity\", 1),\n parallax,\n collision: true,\n width: columns,\n height: rows,\n tiles,\n };\n}\n\n/**\n * Converts an LDtk `Entities` layer into tilemap objects.\n *\n * @remarks\n * `px` is the entity's **pivot** in level pixels from the level's top-left, so the box's top-left is\n * `px - pivot * size`; the layer's `pxOffset` shifts it, and the +Y flip then puts the bottom edge\n * at `(levelHeightPx - top - height) / ppu`.\n *\n * @param instance - The layer instance.\n * @param levelHeightPx - The level's height in pixels.\n * @param pixelsPerUnit - The pixels one world metre spans.\n * @param out - The object list to append to.\n */\nfunction readEntities(\n instance: Readonly<Record<string, unknown>>,\n levelHeightPx: number,\n pixelsPerUnit: number,\n out: TilemapObjectDefinition[],\n): void {\n const offsetX = readNumber(instance, \"pxOffsetX\", 0);\n const offsetY = readNumber(instance, \"pxOffsetY\", 0);\n const entities = readArray(instance, \"entityInstances\");\n for (let index = 0; index < entities.length; index += 1) {\n const entity = entities[index];\n if (!isRecord(entity)) {\n continue;\n }\n const identifier = readString(entity, \"__identifier\", \"\");\n const entityWidth = readNumber(entity, \"width\", 0);\n const entityHeight = readNumber(entity, \"height\", 0);\n const px = entity[\"px\"];\n const pivot = entity[\"__pivot\"];\n const pivotX = isUnknownArray(pivot) && typeof pivot[0] === \"number\" ? pivot[0] : 0;\n const pivotY = isUnknownArray(pivot) && typeof pivot[1] === \"number\" ? pivot[1] : 0;\n const pivotPxX = isUnknownArray(px) && typeof px[0] === \"number\" ? px[0] : 0;\n const pivotPxY = isUnknownArray(px) && typeof px[1] === \"number\" ? px[1] : 0;\n const left = pivotPxX + offsetX - pivotX * entityWidth;\n const top = pivotPxY + offsetY - pivotY * entityHeight;\n const properties = fieldInstancesToRecord(entity[\"fieldInstances\"]);\n const named = properties[\"name\"];\n out.push({\n name: typeof named === \"string\" && named !== \"\" ? named : identifier,\n type: identifier,\n x: left / pixelsPerUnit,\n y: (levelHeightPx - top - entityHeight) / pixelsPerUnit,\n width: entityWidth / pixelsPerUnit,\n height: entityHeight / pixelsPerUnit,\n properties,\n });\n }\n}\n\n/**\n * Narrows an unknown JSON value to a plain object.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown JSON value to an array without widening its elements to `any`.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Reads a numeric field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a finite number.\n * @returns The number.\n */\nfunction readNumber(source: Readonly<Record<string, unknown>>, key: string, fallback: number): number {\n const value = source[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Reads a string field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a string.\n * @returns The string.\n */\nfunction readString(source: Readonly<Record<string, unknown>>, key: string, fallback: string): string {\n const value = source[key];\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Reads an array field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @returns The array, or an empty one when the field is missing or not an array.\n */\nfunction readArray(source: Readonly<Record<string, unknown>>, key: string): readonly unknown[] {\n const value = source[key];\n return isUnknownArray(value) ? value : [];\n}\n","import { twoDError, TwoDErrorCode } from \"../../errors.js\";\nimport { DEFAULT_PIXELS_PER_UNIT } from \"../../math/coords.js\";\nimport { defineTilemap } from \"../definition.js\";\nimport type {\n TileAnimationFrame,\n TileColliderDefinition,\n TileDefinition,\n TilemapDefinition,\n TilemapLayerInput,\n TilemapObjectDefinition,\n TilesetDefinition,\n} from \"../definition.js\";\n\n/**\n * The **Tiled** importer: turns a `.tmj` (Tiled's JSON map format) into an `ignifx.tilemap`\n * document (`docs/architecture/11-2d-toolkit.md` §2.5).\n *\n * It is a pure function over already-parsed JSON — no file system, no network, no asset system — so\n * it runs identically in the Vite plugin, in a CLI importer and in a test. Orthogonal maps only;\n * isometric and hexagonal are post-MVP and are rejected rather than silently mangled.\n */\n\n/** The three high bits Tiled packs the horizontal, vertical and diagonal flip flags into. */\nconst TILED_GID_MASK = 0x1fffffff;\n\n/** The name reported in `IGX-1109` context so a developer knows which importer complained. */\nconst IMPORTER_NAME = \"tiled\";\n\n/**\n * How {@link importTiledMap} maps Tiled's conventions onto ignifx's.\n *\n * @public\n */\nexport interface TiledImportOptions {\n /** The pixels one world metre spans. Defaults to `100`, matching `twoD.pixelsPerUnit`. */\n readonly pixelsPerUnit?: number;\n /** The sorting layer every tile layer lands in unless it says otherwise. Defaults to `\"Default\"`. */\n readonly sortingLayer?: string;\n /**\n * Maps a Tiled tileset's `image` path onto the address of the ignifx `.atlas.json` that was\n * generated from it. Defaults to swapping the file extension for `.atlas.json`.\n */\n readonly atlasFor?: (imageSource: string) => string;\n}\n\n/**\n * Flattens Tiled's `[{ name, type, value }]` property arrays into a plain record.\n *\n * @remarks\n * Only `string`, `number` and `boolean` values survive; Tiled's `object` and `class` property types\n * carry editor-side references that mean nothing at runtime, and are dropped rather than stringified\n * into something that looks meaningful but is not. `color` and `file` properties are strings in the\n * JSON and come through as strings.\n *\n * @param properties - The value of a Tiled `properties` field, or anything else.\n * @returns The flattened record; empty when `properties` is not a Tiled property array.\n *\n * @example\n * ```ts\n * tiledPropertiesToRecord([{ name: \"biome\", type: \"string\", value: \"cave\" }]); // { biome: \"cave\" }\n * ```\n *\n * @public\n */\nexport function tiledPropertiesToRecord(properties: unknown): Readonly<Record<string, string | number | boolean>> {\n if (!isUnknownArray(properties)) {\n return {};\n }\n const out: Record<string, string | number | boolean> = {};\n for (let index = 0; index < properties.length; index += 1) {\n const entry = properties[index];\n if (!isRecord(entry)) {\n continue;\n }\n const name = entry[\"name\"];\n const value = entry[\"value\"];\n if (typeof name !== \"string\" || name === \"\") {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[name] = value;\n }\n }\n return out;\n}\n\n/**\n * Imports a Tiled JSON map.\n *\n * @remarks\n * Three Tiled features are rejected outright with `IGX-1109` rather than approximated: a non\n * orthogonal `orientation`, an `infinite` map (whose layers are chunked rather than dense), and\n * base64/compressed layer `data` (which arrives as a string). Everything else degrades quietly —\n * image layers and group layers are skipped, and unknown properties are carried through.\n *\n * Tiled stores the horizontal, vertical and diagonal flip flags in the top three bits of every\n * global tile id. ignifx has no per-cell flip yet, so those bits are **masked off** and the tile\n * draws unflipped; without the mask a flipped tile would resolve to a nonsensical tileset.\n *\n * The frame names this importer emits are `<tilesetName>_<localTileIndex>` — the same names\n * the grid-atlas generator gives the frames it cuts out of the tileset image, which is the contract\n * that lets `TilemapRenderer` look a tile's sprite up without a side table.\n *\n * @param tmj - The parsed `.tmj` document.\n * @param options - Pixels-per-unit, the default sorting layer, and the atlas address mapping.\n * @returns The `ignifx.tilemap` document.\n * @throws IgnifxError with code `IGX-1109` when the document is not an orthogonal, finite,\n * uncompressed Tiled map, and `IGX-1105` when what it decodes to is not a valid tilemap.\n *\n * @example\n * ```ts\n * const map = importTiledMap(JSON.parse(await readFile(\"cave.tmj\", \"utf8\")), { pixelsPerUnit: 32 });\n * ```\n *\n * @public\n */\nexport function importTiledMap(tmj: unknown, options: TiledImportOptions = {}): TilemapDefinition {\n const fail = (reason: string): never => {\n throw twoDError(TwoDErrorCode.unsupportedImport, `The Tiled importer cannot read this document: ${reason}.`, {\n context: { importer: IMPORTER_NAME, reason },\n hint: \"Re-export the map from Tiled as an orthogonal, finite map with uncompressed CSV layer data.\",\n });\n };\n if (!isRecord(tmj)) {\n return fail(\"it is not a JSON object\");\n }\n const orientation = readString(tmj, \"orientation\", \"orthogonal\");\n if (orientation !== \"orthogonal\") {\n return fail(`its orientation is ${orientation}, and only orthogonal maps are supported`);\n }\n if (tmj[\"infinite\"] === true) {\n return fail(\"it is an infinite map, whose layers are stored as chunks rather than a dense grid\");\n }\n\n const pixelsPerUnit = options.pixelsPerUnit ?? DEFAULT_PIXELS_PER_UNIT;\n const defaultSortingLayer = options.sortingLayer ?? \"Default\";\n const atlasFor = options.atlasFor ?? defaultAtlasFor;\n const tileWidth = readNumber(tmj, \"tilewidth\", 0);\n const tileHeight = readNumber(tmj, \"tileheight\", tileWidth);\n const width = readNumber(tmj, \"width\", 0);\n const height = readNumber(tmj, \"height\", 0);\n const mapHeightPx = height * tileHeight;\n\n const tilesets: TilesetDefinition[] = [];\n const rawTilesets = readArray(tmj, \"tilesets\");\n for (let index = 0; index < rawTilesets.length; index += 1) {\n const raw = rawTilesets[index];\n if (!isRecord(raw)) {\n continue;\n }\n if (typeof raw[\"source\"] === \"string\") {\n return fail(`tileset ${String(index)} is an external .tsx reference, which this importer cannot resolve`);\n }\n tilesets.push(readTileset(raw, index, tileWidth, tileHeight, atlasFor));\n }\n\n const layers: TilemapLayerInput[] = [];\n const objects: TilemapObjectDefinition[] = [];\n const rawLayers = readArray(tmj, \"layers\");\n for (let index = 0; index < rawLayers.length; index += 1) {\n const raw = rawLayers[index];\n if (!isRecord(raw)) {\n continue;\n }\n const type = readString(raw, \"type\", \"\");\n if (type === \"tilelayer\") {\n layers.push(readTileLayer(raw, layers.length, width, height, defaultSortingLayer, fail));\n continue;\n }\n if (type === \"objectgroup\") {\n readObjectLayer(raw, mapHeightPx, pixelsPerUnit, objects);\n }\n // Image layers and group layers carry nothing the tilemap format models; skipping them is\n // friendlier than refusing a map that merely has a reference image pinned to it.\n }\n\n return defineTilemap(\n {\n tileWidth,\n tileHeight,\n cellSize: tileWidth / pixelsPerUnit,\n width,\n height,\n tilesets,\n layers,\n objects,\n properties: tiledPropertiesToRecord(tmj[\"properties\"]),\n },\n \"<tiled>\",\n );\n}\n\n/**\n * Swaps a file extension for `.atlas.json`, the default {@link TiledImportOptions.atlasFor}.\n *\n * @param imageSource - The image path the editor recorded.\n * @returns The atlas address.\n */\nfunction defaultAtlasFor(imageSource: string): string {\n const slash = Math.max(imageSource.lastIndexOf(\"/\"), imageSource.lastIndexOf(\"\\\\\"));\n const dot = imageSource.lastIndexOf(\".\");\n return dot > slash ? `${imageSource.slice(0, dot)}.atlas.json` : `${imageSource}.atlas.json`;\n}\n\n/**\n * Reads one embedded Tiled tileset.\n *\n * @param raw - The tileset object.\n * @param index - Its position in the `tilesets` array, used to name an unnamed tileset.\n * @param tileWidth - The map's tile width in pixels, for normalising colliders.\n * @param tileHeight - The map's tile height in pixels, for normalising colliders.\n * @param atlasFor - The image-to-atlas address mapping.\n * @returns The tileset definition.\n */\nfunction readTileset(\n raw: Readonly<Record<string, unknown>>,\n index: number,\n tileWidth: number,\n tileHeight: number,\n atlasFor: (imageSource: string) => string,\n): TilesetDefinition {\n const name = readString(raw, \"name\", `tileset${String(index)}`);\n const image = readString(raw, \"image\", \"\");\n const tileCount = readNumber(raw, \"tilecount\", 0);\n const overrides = new Map<number, Readonly<Record<string, unknown>>>();\n const rawTiles = readArray(raw, \"tiles\");\n for (let tileIndex = 0; tileIndex < rawTiles.length; tileIndex += 1) {\n const entry = rawTiles[tileIndex];\n if (isRecord(entry)) {\n overrides.set(readNumber(entry, \"id\", -1), entry);\n }\n }\n const tiles: TileDefinition[] = [];\n for (let localId = 0; localId < tileCount; localId += 1) {\n tiles.push(readTile(overrides.get(localId), localId, name, tileWidth, tileHeight));\n }\n return { name, atlas: atlasFor(image), firstId: readNumber(raw, \"firstgid\", 1), tiles };\n}\n\n/**\n * Reads one tile of a Tiled tileset, filling in the parts Tiled only writes when they are not empty.\n *\n * @param entry - The `tiles[]` override for this local id, when there is one.\n * @param localId - The tile's index within its tileset.\n * @param tilesetName - The frame-name prefix.\n * @param tileWidth - The map's tile width in pixels.\n * @param tileHeight - The map's tile height in pixels.\n * @returns The tile definition.\n */\nfunction readTile(\n entry: Readonly<Record<string, unknown>> | undefined,\n localId: number,\n tilesetName: string,\n tileWidth: number,\n tileHeight: number,\n): TileDefinition {\n const frame = `${tilesetName}_${String(localId)}`;\n if (entry === undefined) {\n return { id: localId, frame };\n }\n const properties = tiledPropertiesToRecord(entry[\"properties\"]);\n const oneWay = properties[\"oneWay\"] === true;\n const collider = readCollider(entry[\"objectgroup\"], tileWidth, tileHeight, oneWay);\n const animation = readAnimation(entry[\"animation\"], tilesetName);\n return {\n id: localId,\n frame,\n ...(collider === null ? {} : { collider }),\n ...(Object.keys(properties).length === 0 ? {} : { properties }),\n ...(animation === null ? {} : { animation }),\n };\n}\n\n/**\n * Turns a per-tile `objectgroup` into a cell-normalised collider.\n *\n * @remarks\n * Tiled lets an artist draw any number of shapes on a tile; the tilemap format models one, so the\n * first shape wins. A shape with a `polygon` array becomes a polygon collider (its points are\n * relative to the object's own origin, so the object position is added back in); anything else with\n * a positive size becomes a box. Both stay in the editor's top-left-origin normalised space —\n * `tileCollisionInfo` performs the flip into metres.\n *\n * @param objectGroup - The tile's `objectgroup` field.\n * @param tileWidth - The map's tile width in pixels.\n * @param tileHeight - The map's tile height in pixels.\n * @param oneWay - Whether the tile's `oneWay` property is set.\n * @returns The collider, or `null` when the tile declares none and is not a bare one-way tile.\n */\nfunction readCollider(\n objectGroup: unknown,\n tileWidth: number,\n tileHeight: number,\n oneWay: boolean,\n): TileColliderDefinition | null {\n const group = isRecord(objectGroup) ? objectGroup : null;\n const shapes = group === null ? [] : readArray(group, \"objects\");\n for (let index = 0; index < shapes.length; index += 1) {\n const shape = shapes[index];\n if (!isRecord(shape)) {\n continue;\n }\n const originX = readNumber(shape, \"x\", 0);\n const originY = readNumber(shape, \"y\", 0);\n const polygon = shape[\"polygon\"];\n if (isUnknownArray(polygon)) {\n const points: { readonly x: number; readonly y: number }[] = [];\n for (let pointIndex = 0; pointIndex < polygon.length; pointIndex += 1) {\n const point = polygon[pointIndex];\n if (isRecord(point)) {\n points.push({\n x: (originX + readNumber(point, \"x\", 0)) / tileWidth,\n y: (originY + readNumber(point, \"y\", 0)) / tileHeight,\n });\n }\n }\n if (points.length >= 3) {\n return { kind: \"polygon\", points, ...(oneWay ? { oneWay: true } : {}) };\n }\n continue;\n }\n const shapeWidth = readNumber(shape, \"width\", 0);\n const shapeHeight = readNumber(shape, \"height\", 0);\n if (shapeWidth > 0 && shapeHeight > 0) {\n return {\n kind: \"box\",\n x: originX / tileWidth,\n y: originY / tileHeight,\n width: shapeWidth / tileWidth,\n height: shapeHeight / tileHeight,\n ...(oneWay ? { oneWay: true } : {}),\n };\n }\n }\n // A tile marked one-way but drawn with no shape is still meant to be a platform; giving it the\n // whole cell is the only reading that does what the author asked.\n return oneWay ? { kind: \"box\", x: 0, y: 0, width: 1, height: 1, oneWay: true } : null;\n}\n\n/**\n * Turns Tiled's `[{ tileid, duration }]` animation into {@link TileAnimationFrame}s.\n *\n * @param animation - The tile's `animation` field.\n * @param tilesetName - The frame-name prefix.\n * @returns The frames, or `null` when the tile does not animate.\n */\nfunction readAnimation(animation: unknown, tilesetName: string): readonly TileAnimationFrame[] | null {\n if (!isUnknownArray(animation) || animation.length === 0) {\n return null;\n }\n const frames: TileAnimationFrame[] = [];\n for (let index = 0; index < animation.length; index += 1) {\n const step = animation[index];\n if (!isRecord(step)) {\n continue;\n }\n frames.push({\n frame: `${tilesetName}_${String(readNumber(step, \"tileid\", 0))}`,\n durationMs: readNumber(step, \"duration\", 0),\n });\n }\n return frames.length === 0 ? null : frames;\n}\n\n/**\n * Reads one Tiled tile layer.\n *\n * @param raw - The layer object.\n * @param order - The layer's position among the emitted layers, used as the default draw order.\n * @param mapWidth - The map's width in cells.\n * @param mapHeight - The map's height in cells.\n * @param defaultSortingLayer - The sorting layer to use when the layer names none.\n * @param fail - The `IGX-1109` thrower.\n * @returns The layer input.\n */\nfunction readTileLayer(\n raw: Readonly<Record<string, unknown>>,\n order: number,\n mapWidth: number,\n mapHeight: number,\n defaultSortingLayer: string,\n fail: (reason: string) => never,\n): TilemapLayerInput {\n const name = readString(raw, \"name\", `Layer ${String(order)}`);\n const data = raw[\"data\"];\n if (typeof data === \"string\") {\n fail(\n `layer ${name} stores its data as a string, and compressed layer data is not supported; export uncompressed CSV/array data`,\n );\n }\n if (!isUnknownArray(data)) {\n return fail(`layer ${name} has no tile data array`);\n }\n const tiles: number[] = [];\n for (let index = 0; index < data.length; index += 1) {\n const gid = data[index];\n tiles.push(typeof gid === \"number\" ? gid & TILED_GID_MASK : 0);\n }\n const properties = tiledPropertiesToRecord(raw[\"properties\"]);\n const sortingLayer = properties[\"sortingLayer\"];\n const orderInLayer = properties[\"orderInLayer\"];\n return {\n name,\n sortingLayer: typeof sortingLayer === \"string\" ? sortingLayer : defaultSortingLayer,\n orderInLayer: typeof orderInLayer === \"number\" ? orderInLayer : order,\n opacity: readNumber(raw, \"opacity\", 1),\n parallax: { x: readNumber(raw, \"parallaxx\", 1), y: readNumber(raw, \"parallaxy\", 1) },\n collision: properties[\"collision\"] === true,\n width: readNumber(raw, \"width\", mapWidth),\n height: readNumber(raw, \"height\", mapHeight),\n tiles,\n };\n}\n\n/**\n * Reads one Tiled object layer, appending its objects to the map's flat object list.\n *\n * @remarks\n * Tiled measures an object rectangle from the **map's top-left** in pixels, with `y` at the\n * rectangle's top. ignifx wants world metres with +Y up and `y` at the bottom, so the conversion is\n * `xM = x / ppu` and `yM = (mapHeightPx - y - height) / ppu`.\n *\n * @param raw - The layer object.\n * @param mapHeightPx - The map's height in pixels.\n * @param pixelsPerUnit - The pixels one world metre spans.\n * @param out - The object list to append to.\n */\nfunction readObjectLayer(\n raw: Readonly<Record<string, unknown>>,\n mapHeightPx: number,\n pixelsPerUnit: number,\n out: TilemapObjectDefinition[],\n): void {\n const objects = readArray(raw, \"objects\");\n for (let index = 0; index < objects.length; index += 1) {\n const object = objects[index];\n if (!isRecord(object)) {\n continue;\n }\n const objectHeight = readNumber(object, \"height\", 0);\n out.push({\n name: readString(object, \"name\", \"\"),\n // Tiled 1.9 renamed the object's `type` field to `class`; both spellings are in the wild.\n type: readString(object, \"type\", readString(object, \"class\", \"\")),\n x: readNumber(object, \"x\", 0) / pixelsPerUnit,\n y: (mapHeightPx - readNumber(object, \"y\", 0) - objectHeight) / pixelsPerUnit,\n width: readNumber(object, \"width\", 0) / pixelsPerUnit,\n height: objectHeight / pixelsPerUnit,\n properties: tiledPropertiesToRecord(object[\"properties\"]),\n });\n }\n}\n\n/**\n * Narrows an unknown JSON value to a plain object.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is a non-null, non-array object.\n */\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Narrows an unknown JSON value to an array without widening its elements to `any`.\n *\n * @param value - The parsed JSON value.\n * @returns Whether it is an array.\n */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Reads a numeric field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a finite number.\n * @returns The number.\n */\nfunction readNumber(source: Readonly<Record<string, unknown>>, key: string, fallback: number): number {\n const value = source[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Reads a string field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @param fallback - What to return when the field is missing or not a string.\n * @returns The string.\n */\nfunction readString(source: Readonly<Record<string, unknown>>, key: string, fallback: string): string {\n const value = source[key];\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Reads an array field.\n *\n * @param source - The object to read from.\n * @param key - The field name.\n * @returns The array, or an empty one when the field is missing or not an array.\n */\nfunction readArray(source: Readonly<Record<string, unknown>>, key: string): readonly unknown[] {\n const value = source[key];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