@ignifx/core 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +14712 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +30063 -0
- package/dist/index.js.map +1 -0
- package/package.json +49 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["candidate","MILLISECONDS_PER_SECOND","bag","defaultNow","MATRIX_LENGTH","adapterScreenToRay","adapterWorldToScreen","colorKey","MIN_RESOLUTION_SCALE","MAX_RESOLUTION_SCALE","hostDevicePixelRatio","readString","readNumber","readBoolean","readString","readBoolean","object","DEFAULT_FIXED_DELTA_TIME","DEFAULT_MAXIMUM_DELTA_TIME","compare","PHASE_COUNT","MILLISECONDS_PER_SECOND","MILLISECONDS_PER_SECOND"],"sources":["../src/errors/error-codes.ts","../src/errors/ignifx-error.ts","../src/signal/signal.ts","../src/assets/address.ts","../src/math/math-utils.ts","../src/assets/types.ts","../src/assets/asset-handle.ts","../src/assets/asset-ref.ts","../src/assets/fetcher.ts","../src/assets/loader-context.ts","../src/assets/manifest.ts","../src/assets/request-queue.ts","../src/assets/assets-service.ts","../src/lifecycle/callbacks.ts","../src/schema/issues.ts","../src/schema/schema.ts","../src/handles/handle.ts","../src/component/internals.ts","../src/component/component.ts","../src/script/script.ts","../src/component/component-registry.ts","../src/coroutine/coroutine-host.ts","../src/diagnostics/diagnostics-group.ts","../src/diagnostics/frame-sample.ts","../src/diagnostics/diagnostics.ts","../src/errors/error-code-registry.ts","../src/app/types.ts","../src/app/version.ts","../src/assets/delivery-system.ts","../src/assets/generic-loaders.ts","../src/entity/internals.ts","../src/math/mat4.ts","../src/lite/camera.ts","../src/lite/node.ts","../src/lite/picking.ts","../src/schema/types.ts","../src/schema/field-kinds.ts","../src/render/camera.ts","../src/lite/gpu/environment.ts","../src/math/color.ts","../src/render/environment-asset.ts","../src/render/gpu/environment-install.ts","../src/render/environment.ts","../src/lite/light.ts","../src/lite/shadow.ts","../src/lite/gpu/shadow-generator.ts","../src/render/gpu/light-shadows.ts","../src/lite/gpu/picker.ts","../src/lite/gpu/render-diagnostics-gpu.ts","../src/lite/gpu/screenshot-capture.ts","../src/lite/gpu/warm-up.ts","../src/lite/render-diagnostics.ts","../src/lite/render-features.ts","../src/lite/scene.ts","../src/render/gpu/renderer-gpu.ts","../src/lite/material.ts","../src/render/material-asset.ts","../src/render/rendering-settings.ts","../src/render/renderer.ts","../src/render/light.ts","../src/render/loaders/environment-loader.ts","../src/lite/font.ts","../src/render/font-asset.ts","../src/render/loaders/font-loader.ts","../src/render/loaders/material-loader.ts","../src/lite/gpu/gltf.ts","../src/render/model-asset.ts","../src/render/loaders/model-loader.ts","../src/lite/gpu/texture.ts","../src/render/texture-asset.ts","../src/render/loaders/texture-loader.ts","../src/lite/gpu/mesh.ts","../src/render/mesh-asset.ts","../src/render/gpu/mesh-instance.ts","../src/render/mesh-renderer.ts","../src/render/gpu/model-instance.ts","../src/render/model.ts","../src/lite/gpu/post-process.ts","../src/render/gpu/post-process-chain.ts","../src/render/post-process-stack.ts","../src/render/render-sync-system.ts","../src/serialization/json-view.ts","../src/schema/internal.ts","../src/schema/encode.ts","../src/schema/describe.ts","../src/serialization/scene-file.ts","../src/serialization/scene-asset.ts","../src/serialization/validate.ts","../src/serialization/scene-loader.ts","../src/math/vec3.ts","../src/math/quat.ts","../src/math/vec2.ts","../src/transform/transform-internals.ts","../src/transform/transform.ts","../src/extension/define-extension.ts","../src/extension/core-extension.ts","../src/extension/service-registry.ts","../src/extension/extension-context.ts","../src/extension/semver-range.ts","../src/extension/host.ts","../src/layers/layer-mask.ts","../src/layers/layer-table.ts","../src/lifecycle/frame-state.ts","../src/platform/webgpu.ts","../src/lite/gpu/render-path.ts","../src/lite/render.ts","../src/lite/engine.ts","../src/lite/gpu/device-loss.ts","../src/lite/loop.ts","../src/log/log-level.ts","../src/log/console-sink.ts","../src/log/logger.ts","../src/platform/platform.ts","../src/scheduler/deferred-queue.ts","../src/lifecycle/pause-filter.ts","../src/scheduler/scheduler.ts","../src/schema/validate.ts","../src/settings/settings-store.ts","../src/time/clock.ts","../src/time/time.ts","../src/component/component-store.ts","../src/component/reference-tracker.ts","../src/tags/tag-set.ts","../src/entity/entity-path.ts","../src/entity/entity.ts","../src/handles/handle-allocator.ts","../src/ids/random-source.ts","../src/ids/ulid.ts","../src/lifecycle/script-list.ts","../src/lifecycle/lifecycle-queue.ts","../src/render/raycast.ts","../src/scene/scene-instance.ts","../src/serialization/overrides.ts","../src/serialization/expand.ts","../src/serialization/uid-remap.ts","../src/serialization/load.ts","../src/world/world.ts","../src/app/events.ts","../src/app/app.ts","../src/log/memory-sink.ts","../src/math/vec4.ts","../src/render/schemas.ts","../src/serialization/serialize.ts","../src/script/wait.ts"],"sourcesContent":["/**\n * The error code registry data: the subsystem ranges from\n * `docs/architecture/15-devtools-and-diagnostics.md` §1, the codes `@ignifx/core` itself owns, and\n * the format rule every code must satisfy.\n *\n * This module is pure data plus one predicate; it imports nothing, which is what lets\n * {@link IgnifxError} depend on it without a cycle (coding standards §4).\n */\n\n/**\n * The two-digit prefix each subsystem owns inside the `IGX-####` space\n * (`docs/architecture/15-devtools-and-diagnostics.md` §1). A code is the prefix followed by a\n * two-digit ordinal, so `rendering` owns `IGX-0700` through `IGX-0799`.\n *\n * @example\n * ```ts\n * const code = `IGX-${ErrorRange.rendering}01` satisfies ErrorCode; // \"IGX-0701\"\n * ```\n *\n * @public\n */\nexport const ErrorRange = {\n /** App lifecycle, phases, time, coroutines, destruction. */\n lifecycle: \"01\",\n /** Components, scripts, and their registration. */\n components: \"02\",\n /** Scenes, scene instances, layers. */\n scenes: \"03\",\n /** The extension host and its contract. */\n extensions: \"04\",\n /** Asset handles, loaders, and caching. */\n assets: \"05\",\n /** Schemas, scene/prefab JSON, references. */\n serialization: \"06\",\n /** The renderer and the Babylon Lite adapter. */\n rendering: \"07\",\n /** Input devices, actions, and bindings. */\n input: \"08\",\n /** 3D physics. */\n physics: \"09\",\n /** Audio buses, sources, and clips. */\n audio: \"10\",\n /** The 2D toolkit. */\n twoD: \"11\",\n /** The 3D toolkit. */\n threeD: \"12\",\n /** The UI overlay. */\n ui: \"13\",\n /** Platform integration (browser, Electron). */\n platform: \"14\",\n /** Devtools, logging, and diagnostics. */\n devtools: \"15\",\n} as const;\n\n/**\n * The union of the two-digit subsystem prefixes declared by `ErrorRange`.\n *\n * @public\n */\nexport type ErrorRange = (typeof ErrorRange)[keyof typeof ErrorRange];\n\n/**\n * The first digit of the range reserved for extensions published outside the `@ignifx` scope\n * (`IGX-9000` through `IGX-9999`). First-party subsystems never allocate here.\n *\n * @public\n */\nexport const THIRD_PARTY_ERROR_PREFIX = \"9\";\n\n/**\n * The shape of every ignifx diagnostic code: the literal `IGX-` followed by four digits.\n *\n * @remarks\n * The template literal is the widest useful type; it accepts strings such as `\"IGX-1\"` that are not\n * real codes. {@link isValidErrorCode} is the runtime check, `CoreErrorCode` is the narrowed\n * string-literal union for the codes this package owns, and extensions narrow their own the same\n * way.\n *\n * @public\n */\nexport type ErrorCode = `IGX-${number}`;\n\n/**\n * Every diagnostic code `@ignifx/core` can throw, keyed by an intention-revealing name so call\n * sites read as prose and the compiler catches typos (coding standards §5.2 — `as const` objects in\n * place of enums).\n *\n * @example\n * ```ts\n * throw new IgnifxError(CoreErrorCode.mutationAfterDestroy, \"The entity has been destroyed.\", {\n * context: { entity: entity.uid },\n * });\n * ```\n *\n * @remarks\n * Code blocks reserved for other first-party packages, which cannot import this table\n * (`docs/architecture/00-overview.md` §2): `@ignifx/cli` owns `IGX-1401`–`IGX-1419`;\n * `@ignifx/vite-plugin` owns `IGX-0550`–`IGX-0599` and `IGX-0650`–`IGX-0699`. Core allocates its\n * own codes from the bottom of each range and, in the platform range, from `IGX-1420` upward.\n *\n * @public\n */\nexport const CoreErrorCode = {\n /** An entity, component, or app was used after it had been destroyed or disposed. */\n mutationAfterDestroy: \"IGX-0101\",\n /** `destroyImmediate()` was called from inside a lifecycle callback. */\n destroyImmediateInCallback: \"IGX-0102\",\n /** A signal handler asked for deferred delivery on a signal that has no scheduler. */\n deferredSignalWithoutScheduler: \"IGX-0103\",\n /** A signal handler threw and no handler-error reporter was installed. */\n signalHandlerThrew: \"IGX-0104\",\n /** `app.step()` was called while Babylon Lite's render loop was driving the frames. */\n stepOutsideHeadless: \"IGX-0105\",\n /** An app was used after `app.dispose()` had run. */\n appDisposed: \"IGX-0106\",\n /** A part of the app was reached before `createApp()` had finished building it. */\n appNotReady: \"IGX-0107\",\n /** A `Time` property was set to a value outside its documented domain. */\n invalidTimeValue: \"IGX-0108\",\n /** A component declared through `requires` is missing from the entity. */\n requiredComponentMissing: \"IGX-0201\",\n /** A second instance of a component type that does not allow multiples was added. */\n multipleComponentsNotAllowed: \"IGX-0202\",\n /** Two component types were registered under the same `typeId`. */\n duplicateComponentTypeId: \"IGX-0203\",\n /** A component without a `typeId` was serialized. */\n componentTypeIdMissing: \"IGX-0204\",\n /** `Transform` was removed or disabled; every entity must keep exactly one enabled transform. */\n transformIsNotRemovable: \"IGX-0205\",\n /** A component's engine-assigned state was read before the engine attached it to an entity. */\n componentNotAttached: \"IGX-0206\",\n /** A scene was instantiated before it had finished loading. */\n sceneNotLoaded: \"IGX-0301\",\n /** Instantiating a scene would place an instance inside itself. */\n sceneInstanceCycle: \"IGX-0302\",\n /** A layer name that the project settings do not declare was used. */\n unknownLayer: \"IGX-0303\",\n /** Two layer slots were given the same name. */\n duplicateLayerName: \"IGX-0304\",\n /** The project settings declare more layer names than the 32 available slots. */\n tooManyLayers: \"IGX-0305\",\n /** Reparenting an entity under its own descendant would make the scene tree cyclic. */\n parentingCycle: \"IGX-0306\",\n /** A scene file names a component `typeId` that no extension has registered. */\n unknownComponentTypeId: \"IGX-0307\",\n /** A file handed to the scene loader does not carry the `ignifx.scene` format header. */\n notASceneFile: \"IGX-0308\",\n /** An operation that only accepts a scene root was given an entity that has a parent. */\n entityIsNotSceneRoot: \"IGX-0309\",\n /** Two extensions defined the same app property. */\n appPropertyAlreadyDefined: \"IGX-0401\",\n /** The `requires` graph of the registered extensions contains a cycle. */\n extensionRequiresCycle: \"IGX-0402\",\n /** An extension declares a `requires` entry that was never registered. */\n extensionMissing: \"IGX-0403\",\n /** An extension's `engine` range does not match the running core version. */\n extensionEngineMismatch: \"IGX-0404\",\n /** `ctx.require()` asked for a service that no earlier extension registered. */\n serviceNotRegistered: \"IGX-0405\",\n /** Two extensions were registered under the same name. */\n duplicateExtensionName: \"IGX-0406\",\n /** `ctx.settings()` asked for a settings section that was never registered. */\n unknownSettingsSection: \"IGX-0407\",\n /** A project settings section did not validate against the schema its extension registered. */\n invalidSettings: \"IGX-0408\",\n /** An extension dispatched a physics callback from outside the fixed loop. */\n physicsCallbackOutsideFixedStep: \"IGX-0409\",\n /** A second, different simulation scene was handed to a world that already has one. */\n simulationSceneAlreadySet: \"IGX-0410\",\n /** An asset's value was read before the asset finished loading. */\n assetNotLoaded: \"IGX-0501\",\n /** An asset load was aborted through its `AbortSignal`. */\n assetLoadAborted: \"IGX-0502\",\n /** An asset promise outlived the app that owned it. */\n assetAppDisposed: \"IGX-0503\",\n /** No registered loader claims the address's type or extension. */\n assetNoLoader: \"IGX-0504\",\n /** An asset load failed after its last retry. */\n assetLoadFailed: \"IGX-0505\",\n /** Two loaders were registered for the same asset type. */\n duplicateAssetLoader: \"IGX-0506\",\n /** A serialized number was `NaN` or infinite. */\n nonFiniteNumber: \"IGX-0601\",\n /** A serialized `$entity`/`$component` reference could not be resolved. */\n unresolvedReference: \"IGX-0602\",\n /** A scene, prefab, or manifest declares a format version this build cannot read. */\n unsupportedFormatVersion: \"IGX-0603\",\n /** A scene instance's override hash does not match the scene file it was recorded against. */\n instanceHashMismatch: \"IGX-0604\",\n /** A value had the wrong JavaScript or JSON type for its schema field kind. */\n schemaTypeMismatch: \"IGX-0605\",\n /** A value had the right type but fell outside its schema field's declared value domain. */\n schemaOutOfRange: \"IGX-0606\",\n /** A schema declaration or a property bag named a field the schema does not declare. */\n schemaUnknownField: \"IGX-0607\",\n /** A scene file failed structural validation against the generated scene-file JSON Schema. */\n sceneFileInvalid: \"IGX-0608\",\n /** An instance override declares a `path` the override grammar does not accept. */\n invalidOverridePath: \"IGX-0609\",\n /** WebGPU is not available in the current environment. */\n webGpuUnavailable: \"IGX-0701\",\n /** A runtime handle was used after disposal, or was not created by ignifx. */\n invalidRuntime: \"IGX-0702\",\n /** Shadows were requested from a light kind Babylon Lite cannot shadow. */\n shadowsUnsupportedForLight: \"IGX-0703\",\n /** A rendering feature opt-in was requested after the render scene had been registered. */\n renderingFeatureTooLate: \"IGX-0704\",\n /** A second `Environment` was enabled in one world; the most recent one wins. */\n multipleEnvironments: \"IGX-0705\",\n /** A world rendered with no enabled camera, so nothing was drawn. */\n noEnabledCamera: \"IGX-0706\",\n /** A screenshot was requested with no render loop running, so no frame will ever be presented. */\n screenshotNeedsRenderLoop: \"IGX-0707\",\n /** A material file declares a family this build cannot construct. */\n unsupportedMaterialKind: \"IGX-0708\",\n /** An asset file does not carry the format header its loader requires. */\n invalidAssetFile: \"IGX-0709\",\n /** A `PostProcessStack` was attached without the `postProcessing` rendering feature. */\n postProcessingFeatureOff: \"IGX-0710\",\n /** The host exposes no Web Crypto implementation. */\n cryptoUnavailable: \"IGX-1420\",\n /** An error code was registered twice. */\n duplicateErrorCode: \"IGX-1501\",\n /** An error code does not match `IGX-####` in a known range. */\n malformedErrorCode: \"IGX-1502\",\n /** A diagnostics counter group was registered twice. */\n duplicateDiagnosticsGroup: \"IGX-1503\",\n /** A diagnostics counter name was not declared when its group was registered. */\n unknownDiagnosticsCounter: \"IGX-1504\",\n /** A `switch` over a union reached a case the type system said was impossible. */\n unreachableCase: \"IGX-1505\",\n} as const;\n\n/**\n * The union of the codes `@ignifx/core` owns. Use it to narrow `catch` blocks to core failures.\n *\n * @public\n */\nexport type CoreErrorCode = (typeof CoreErrorCode)[keyof typeof CoreErrorCode];\n\n/**\n * The one-line message template for every `CoreErrorCode`. Templates name context keys in\n * braces (`{entity}`); the throwing call site substitutes the values it has and puts the same\n * identifiers in {@link IgnifxError.context} so production builds stay useful without the prose.\n *\n * @public\n */\nexport const CORE_ERROR_MESSAGES: Readonly<Record<CoreErrorCode, string>> = {\n \"IGX-0101\": \"{target} has been destroyed and can no longer be used.\",\n \"IGX-0102\": \"destroyImmediate() cannot run inside the {phase} callback; use destroy() instead.\",\n \"IGX-0103\": \"Deferred signal delivery needs a scheduler; construct the signal with a deferred queue.\",\n \"IGX-0104\": \"A signal handler threw.\",\n \"IGX-0105\": \"step() is only available in headless mode or while the render loop is stopped.\",\n \"IGX-0106\": \"The app has been disposed; {member} is no longer available.\",\n \"IGX-0107\": \"{member} is not available until createApp() resolves.\",\n \"IGX-0108\": \"{property} must be {domain}; got {value}.\",\n \"IGX-0201\": \"{component} requires {required} on the same entity.\",\n \"IGX-0202\": \"{component} does not allow multiple instances on one entity.\",\n \"IGX-0203\": \"The component type id {typeId} is already registered by {owner}.\",\n \"IGX-0204\": \"{component} cannot be serialized because it has no typeId.\",\n \"IGX-0205\": \"Transform cannot be removed or disabled.\",\n \"IGX-0206\": \"{component} is not attached to an entity yet.\",\n \"IGX-0301\": \"The scene {scene} is not loaded yet.\",\n \"IGX-0302\": \"Instantiating {scene} under {entity} would nest the scene inside itself.\",\n \"IGX-0303\": \"{layer} is not a layer declared in the project settings.\",\n \"IGX-0304\": \"The layer name {layer} is declared twice.\",\n \"IGX-0305\": \"The project settings declare {count} layers; at most {limit} fit in the 32 slots.\",\n \"IGX-0306\": \"{entity} cannot be parented to {parent}, which is inside its own subtree.\",\n \"IGX-0307\": \"{typeId} is not a registered component type.\",\n \"IGX-0308\": \"{file} is not an ignifx scene file.\",\n \"IGX-0309\": \"{entity} is not a scene root; only roots can move between scene instances.\",\n \"IGX-0401\": \"The app property {property} is already defined by {owner}.\",\n \"IGX-0402\": \"The extension requires graph contains a cycle: {cycle}.\",\n \"IGX-0403\": \"{extension} requires {required}, which is not registered.\",\n \"IGX-0404\": \"{extension} supports engine {range} but the running core is {version}.\",\n \"IGX-0405\": \"The service {service} required by {extension} is not registered.\",\n \"IGX-0406\": \"The extension name {extension} is registered twice.\",\n \"IGX-0407\": \"{section} is not a registered settings section.\",\n \"IGX-0408\": \"The {section} settings section is invalid: {issues}.\",\n \"IGX-0409\": \"Physics callbacks are dispatched inside the fixed loop only; {callback} was not.\",\n \"IGX-0410\": \"A world has one simulation scene, and this world already has a different one.\",\n \"IGX-0501\": \"The asset {asset} has no value yet because it is still loading.\",\n \"IGX-0502\": \"Loading {asset} was aborted.\",\n \"IGX-0503\": \"The app that owned the asset {asset} was disposed before loading finished.\",\n \"IGX-0504\": \"No loader is registered for {asset}.\",\n \"IGX-0505\": \"Loading {asset} from {url} failed after {attempts} attempts.\",\n \"IGX-0506\": \"A loader for the asset type {type} is already registered.\",\n \"IGX-0601\": \"{field} must be a finite number.\",\n \"IGX-0602\": \"The reference {reference} in {scene} could not be resolved.\",\n \"IGX-0603\": \"{file} declares format version {version}, which this build cannot read.\",\n \"IGX-0604\": \"The overrides recorded for {scene} do not match the scene file.\",\n \"IGX-0605\": \"{field} has the wrong type for a {kind} field.\",\n \"IGX-0606\": \"{field} is outside the declared value domain.\",\n \"IGX-0607\": \"{field} is not a field this schema declares.\",\n \"IGX-0608\": \"{file} does not match the scene file schema.\",\n \"IGX-0609\": \"{path} is not a valid instance override path.\",\n \"IGX-0701\": \"WebGPU is not available in this environment.\",\n \"IGX-0702\": \"This handle was already disposed, or was not created by ignifx.\",\n \"IGX-0703\": \"Babylon Lite has no shadow generator for a {lightType} light.\",\n \"IGX-0704\": \"The rendering feature {feature} must be enabled before the scene is registered.\",\n \"IGX-0705\": \"{entity} enabled a second Environment in this world; the most recent one wins.\",\n \"IGX-0706\": \"This world has no enabled camera, so nothing is drawn.\",\n \"IGX-0707\": \"captureScreenshot() needs a running render loop; a headless app never presents a frame.\",\n \"IGX-0708\": \"{asset} declares the material kind {kind}, which this build cannot construct.\",\n \"IGX-0709\": \"{file} is not an {format} file.\",\n \"IGX-0710\": \"{entity} attached a PostProcessStack, but rendering.features.postProcessing is off.\",\n \"IGX-1420\": \"This host does not expose Web Crypto.\",\n \"IGX-1501\": \"The error code {code} is already registered by {owner}.\",\n \"IGX-1502\": \"{code} is not a valid IGX-#### code in a known range.\",\n \"IGX-1503\": \"The diagnostics group {group} is already registered.\",\n \"IGX-1504\": \"{counter} is not a counter of the diagnostics group {group}.\",\n \"IGX-1505\": \"Unreachable case reached for {what}.\",\n};\n\n/** The fixed length of an `IGX-####` code. */\nconst ERROR_CODE_LENGTH = 8;\n\n/** Where the four digits start inside an `IGX-####` code. */\nconst ERROR_CODE_DIGITS_OFFSET = 4;\n\n/** The characters allowed in the numeric part of a code. */\nconst DIGITS = \"0123456789\";\n\n/**\n * Reports whether a string is a well-formed ignifx error code.\n *\n * @remarks\n * The rule has exactly two parts and the `ignifx/error-code-format` lint rule mirrors it:\n *\n * 1. the string is `IGX-` followed by four ASCII digits, and\n * 2. the first two digits are one of the fifteen `ErrorRange` prefixes, or the first digit is\n * {@link THIRD_PARTY_ERROR_PREFIX} (the third-party block `IGX-9000`–`IGX-9999`).\n *\n * @param code - The candidate code.\n * @returns `true` when the code is well formed and inside an allocated range. The signature is a\n * type predicate, so a validated string narrows to {@link ErrorCode} without a type assertion.\n *\n * @example\n * ```ts\n * isValidErrorCode(\"IGX-0701\"); // true — rendering\n * isValidErrorCode(\"IGX-9042\"); // true — third party\n * isValidErrorCode(\"IGX-1601\"); // false — no subsystem owns 16\n * ```\n *\n * @public\n */\nexport function isValidErrorCode(code: string): code is ErrorCode {\n // The literal below is the prefix the `ignifx/error-code-format` rule looks for. This function is\n // the validator that rule mirrors, not a throw site, so the rule is switched off for one line.\n // eslint-disable-next-line ignifx/error-code-format -- see the comment above\n if (code.length !== ERROR_CODE_LENGTH || !code.startsWith(\"IGX-\")) {\n return false;\n }\n const digits = code.slice(ERROR_CODE_DIGITS_OFFSET);\n for (const digit of digits) {\n if (!DIGITS.includes(digit)) {\n return false;\n }\n }\n const prefix = digits.slice(0, 2);\n if (prefix.startsWith(THIRD_PARTY_ERROR_PREFIX)) {\n return true;\n }\n for (const range of Object.values(ErrorRange)) {\n if (range === prefix) {\n return true;\n }\n }\n return false;\n}\n","import { CoreErrorCode, type ErrorCode } from \"./error-codes.js\";\n\n/**\n * The identifiers that make a failure actionable: entity and component uids, asset keys, layer\n * names, extension names. Values are primitives so the whole record survives being sent to a\n * devtools panel or a log sink without cloning engine objects.\n *\n * @public\n */\nexport type ErrorContext = Readonly<Record<string, string | number | boolean | null>>;\n\n/**\n * How much of an error is spelled out in `Error.message`.\n *\n * @remarks\n * `\"development\"` writes the full sentence, the context values, and the hint. `\"production\"` keeps\n * the code and the *names* of the context keys and drops every value and the prose, so shipped\n * games neither leak content paths nor pay for message strings (`CONSTITUTION.md` §3.9). The\n * structured `code`, `context`, and `hint` properties are populated in both modes.\n *\n * @public\n */\nexport type ErrorFormatMode = \"development\" | \"production\";\n\n/**\n * Options accepted by {@link IgnifxError}. Extends the standard `ErrorOptions`, so `cause` keeps\n * the original failure when an error is wrapped.\n *\n * @public\n */\nexport interface IgnifxErrorOptions extends ErrorOptions {\n /** Identifiers that locate the failure. Defaults to an empty record. */\n readonly context?: ErrorContext;\n /** One sentence telling the developer what to do about it. Defaults to `null`. */\n readonly hint?: string | null;\n /** How verbose `message` should be. Defaults to `\"development\"`. */\n readonly mode?: ErrorFormatMode;\n}\n\n/** Shared empty context so the common case allocates nothing. */\nconst EMPTY_CONTEXT: ErrorContext = {};\n\n/**\n * Builds the `Error.message` of an {@link IgnifxError}.\n *\n * @remarks\n * Development messages read `IGX-0201: Mover requires Rigidbody. [entity=01J…] Hint: add it.`\n * Production messages read `IGX-0201 [entity]` — enough to look the code up in the registry and to\n * know which identifiers the `context` property carries, with no prose in the bundle.\n *\n * @param code - The stable diagnostic code.\n * @param message - The actionable development sentence.\n * @param context - Identifiers that locate the failure.\n * @param hint - A remedy sentence, or `null`.\n * @param mode - Whether to format for development or production.\n * @returns The formatted message.\n *\n * @example\n * ```ts\n * formatErrorMessage(\"IGX-0303\", \"Enemy is not a declared layer.\", { layer: \"Enemy\" }, null, \"production\");\n * // \"IGX-0303 [layer]\"\n * ```\n *\n * @public\n */\nexport function formatErrorMessage(\n code: ErrorCode,\n message: string,\n context: ErrorContext,\n hint: string | null,\n mode: ErrorFormatMode,\n): string {\n const keys = Object.keys(context);\n if (mode === \"production\") {\n return keys.length === 0 ? code : `${code} [${keys.join(\", \")}]`;\n }\n let formatted = `${code}: ${message}`;\n if (keys.length > 0) {\n const parts: string[] = [];\n for (const key of keys) {\n parts.push(`${key}=${String(context[key] ?? null)}`);\n }\n formatted += ` [${parts.join(\", \")}]`;\n }\n if (hint !== null && hint.length > 0) {\n formatted += ` Hint: ${hint}`;\n }\n return formatted;\n}\n\n/**\n * The error every ignifx API throws for misuse (`CONSTITUTION.md` §3.9). It always carries a stable\n * `IGX-####` `code` and the `context` identifiers needed to find the offending object,\n * so a production build can compact the human-readable half without losing meaning.\n *\n * @example\n * ```ts\n * try {\n * world.instantiate(scene);\n * } catch (error) {\n * if (isIgnifxError(error) && error.code === CoreErrorCode.sceneNotLoaded) {\n * await scene.load();\n * }\n * }\n * ```\n *\n * @public\n */\nexport class IgnifxError extends Error {\n /** The stable diagnostic code for this failure. */\n readonly code: ErrorCode;\n\n /** Identifiers that locate the failure (entity uid, component type id, asset key, …). */\n readonly context: ErrorContext;\n\n /** One sentence telling the developer how to fix it, or `null` when there is nothing to add. */\n readonly hint: string | null;\n\n /**\n * Creates an ignifx error.\n *\n * @param code - The stable `IGX-####` code for the failure.\n * @param message - An actionable description of what went wrong, used in development mode.\n * @param options - Context, hint, format mode, and the standard `cause`.\n */\n constructor(code: ErrorCode, message: string, options?: IgnifxErrorOptions) {\n const context = options?.context ?? EMPTY_CONTEXT;\n const hint = options?.hint ?? null;\n super(formatErrorMessage(code, message, context, hint, options?.mode ?? \"development\"), options);\n this.name = \"IgnifxError\";\n this.code = code;\n this.context = context;\n this.hint = hint;\n }\n}\n\n/**\n * Narrows an unknown value — a `catch` binding, a rejected promise, a signal payload — to an\n * {@link IgnifxError}.\n *\n * @param value - The value to test.\n * @returns `true` when the value is an ignifx error produced by this copy of `@ignifx/core`.\n *\n * @example\n * ```ts\n * app.onError.connect((report) => {\n * if (isIgnifxError(report.error)) {\n * console.warn(report.error.code, report.error.context);\n * }\n * });\n * ```\n *\n * @public\n */\nexport function isIgnifxError(value: unknown): value is IgnifxError {\n return value instanceof IgnifxError;\n}\n\n/**\n * The default branch of an exhaustive `switch` (coding standards §5.2). The compiler rejects the\n * call as soon as a new union member is left unhandled, and at runtime it throws rather than\n * falling through silently.\n *\n * @param value - The value the type system proved impossible.\n * @param what - What was being switched over, for the message.\n * @throws IgnifxError with code `IGX-1505`; the function never returns.\n *\n * @example\n * ```ts\n * switch (level) {\n * case \"debug\":\n * return 10;\n * default:\n * return assertNever(level, \"log level\");\n * }\n * ```\n *\n * @public\n */\nexport function assertNever(value: never, what: string): never {\n throw new IgnifxError(CoreErrorCode.unreachableCase, `Unreachable case reached for ${what}.`, {\n context: { what, value: String(value) },\n });\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\n\n/**\n * A listener attached to a {@link Signal}.\n *\n * @public\n */\nexport type SignalHandler<T> = (value: T) => void;\n\n/**\n * Detaches a handler from a {@link Signal}. Calling it more than once is a no-op.\n *\n * @public\n */\nexport type Disconnect = () => void;\n\n/**\n * Anything whose destruction should take its signal connections with it: an `Entity`, a\n * `Component`, a `SceneInstance`. Connecting with an `owner` is how scripts avoid leaking handlers,\n * and the `ignifx/signal-connect-owner` lint rule requires it inside a `Script`\n * (`docs/architecture/02-scene-graph.md` §8).\n *\n * @public\n */\nexport interface SignalOwner {\n /** Whether the owner has already been destroyed. */\n readonly isDestroyed: boolean;\n /**\n * Emitted once when the owner is destroyed; the signal uses it to detach the handler.\n *\n * @remarks\n * Typed as {@link SignalLike} rather than {@link Signal} so that an owner may expose a precisely\n * typed signal — `Entity.onDestroyed` is a `Signal<Entity>` per\n * `docs/architecture/02-scene-graph.md` §4. `Signal` carries private state, which makes it\n * invariant in `T`; the read-only interface is not, and `connect` is all this contract needs.\n */\n readonly onDestroyed: SignalLike<unknown>;\n}\n\n/**\n * The scheduler that runs deferred deliveries. The core frame loop implements it on the\n * `EndOfFrame` phase; tests can pass a queue that runs callbacks on demand.\n *\n * @public\n */\nexport interface DeferredQueue {\n /**\n * Schedules a callback to run at the next flush point.\n *\n * @param callback - The delivery to run.\n */\n enqueue(callback: () => void): void;\n}\n\n/**\n * Options for {@link Signal.connect}.\n *\n * @public\n */\nexport interface ConnectOptions {\n /** Disconnect the handler after its first delivery. */\n readonly once?: boolean;\n /**\n * Queue the delivery on the signal's {@link DeferredQueue} instead of calling the handler inside\n * `emit` (Godot's `CONNECT_DEFERRED`).\n */\n readonly deferred?: boolean;\n /** Disconnect the handler automatically when this object is destroyed. */\n readonly owner?: SignalOwner;\n}\n\n/**\n * Options for the {@link Signal} constructor, where `T` is the payload the signal emits.\n *\n * @public\n */\nexport interface SignalOptions<T> {\n /** The scheduler used by `deferred` connections. Without it, `deferred: true` throws. */\n readonly deferredQueue?: DeferredQueue;\n /**\n * Where handler exceptions go. When set, every exception is reported here and delivery continues;\n * when absent, the first exception is rethrown as `IGX-0104` once every handler has run. The app\n * passes a reporter that routes to `app.onError`. It must not throw.\n */\n readonly onHandlerError?: (error: unknown, signal: Signal<T>) => void;\n}\n\n/**\n * The read-only half of a {@link Signal}: what a public API exposes when callers may subscribe but\n * must not emit, where `T` is the payload the signal emits.\n *\n * @example\n * ```ts\n * interface Assets {\n * readonly onLoaded: SignalLike<AssetHandle>;\n * }\n * ```\n *\n * @public\n */\nexport interface SignalLike<T = void> {\n /** How many handlers are currently attached. */\n readonly connectionCount: number;\n\n /**\n * Attaches a handler.\n *\n * @param handler - The listener.\n * @param options - `once`, `deferred`, and `owner`.\n * @returns A function that detaches the handler.\n */\n connect(handler: SignalHandler<T>, options?: ConnectOptions): Disconnect;\n}\n\n/** One attached handler. `handler === null` marks the entry dead and awaiting compaction. */\nclass Connection<T> {\n handler: SignalHandler<T> | null;\n readonly once: boolean;\n readonly deferred: boolean;\n /** Index into the owning signal's connection list; kept current by swap-remove. */\n index: number;\n /** Detaches the auto-disconnect handler from `owner.onDestroyed`. */\n ownerDisconnect: Disconnect | null = null;\n\n constructor(handler: SignalHandler<T>, once: boolean, deferred: boolean, index: number) {\n this.handler = handler;\n this.once = once;\n this.deferred = deferred;\n this.index = index;\n }\n}\n\n/** Returned when connecting to a signal on behalf of an already-destroyed owner. */\nfunction noopDisconnect(): void {\n // Nothing was connected, so nothing has to be detached.\n}\n\n/**\n * A typed, synchronous, many-listener event (`docs/architecture/02-scene-graph.md` §8). Signals are\n * the \"signal up\" half of the engine's *call down, signal up* convention: a parent calls methods on\n * the children it owns, a child announces what happened and lets interested parties subscribe.\n *\n * @remarks\n * Delivery guarantees:\n *\n * - Handlers run in connection order, synchronously, inside {@link Signal.emit}.\n * - A handler connected *during* an emit runs on the next emit, never the one in flight.\n * - A handler disconnected during an emit never runs again, including in the emit in flight.\n * - One handler throwing does not stop delivery to the others.\n * - Nothing is allocated per emit on the non-deferred path (coding standards §7).\n *\n * The payload type `T` defaults to `void`, so `signal.emit()` takes no argument.\n *\n * @example\n * ```ts\n * class Health extends Script {\n * readonly onDied = new Signal<Entity>();\n * damage(amount: number): void {\n * this.hp -= amount;\n * if (this.hp <= 0) {\n * this.onDied.emit(this.entity);\n * }\n * }\n * }\n *\n * health.onDied.connect((entity) => this.spawnLoot(entity), { owner: this, once: true });\n * ```\n *\n * @public\n */\nexport class Signal<T = void> implements SignalLike<T> {\n readonly #connections: Connection<T>[] = [];\n readonly #deferredQueue: DeferredQueue | null;\n readonly #onHandlerError: ((error: unknown, signal: Signal<T>) => void) | null;\n #liveCount = 0;\n #deadCount = 0;\n #emitDepth = 0;\n\n /**\n * Creates a signal.\n *\n * @param options - The deferred-delivery scheduler and the handler-error reporter. Both are\n * supplied by the app for engine signals; a signal a script owns usually needs neither.\n */\n constructor(options?: SignalOptions<T>) {\n this.#deferredQueue = options?.deferredQueue ?? null;\n this.#onHandlerError = options?.onHandlerError ?? null;\n }\n\n /**\n * How many handlers are currently attached.\n *\n * @returns The live connection count.\n */\n get connectionCount(): number {\n return this.#liveCount;\n }\n\n /**\n * Attaches a handler.\n *\n * @param handler - The listener.\n * @param options - `once` to detach after the first delivery, `deferred` to queue delivery on the\n * signal's {@link DeferredQueue}, and `owner` to detach when the owner is destroyed.\n * @returns A function that detaches the handler; calling it twice is a no-op.\n * @throws IgnifxError with code `IGX-0103` when `deferred` is requested and the signal was\n * constructed without a {@link DeferredQueue}.\n *\n * @example\n * ```ts\n * const stop = app.events.onSceneLoaded.connect((scene) => this.spawn(scene), { owner: this });\n * stop();\n * ```\n */\n connect(handler: SignalHandler<T>, options?: ConnectOptions): Disconnect {\n const deferred = options?.deferred ?? false;\n if (deferred && this.#deferredQueue === null) {\n throw new IgnifxError(\n CoreErrorCode.deferredSignalWithoutScheduler,\n \"Deferred signal delivery needs a scheduler; construct the signal with a deferred queue.\",\n { hint: \"Engine signals reached through the app already have one; a signal you own does not.\" },\n );\n }\n const owner = options?.owner;\n if (owner !== undefined && owner.isDestroyed) {\n // Connecting on behalf of a destroyed owner is a no-op rather than an error: teardown order\n // between two destroyed objects is not something game code should have to reason about.\n return noopDisconnect;\n }\n const connection = new Connection<T>(handler, options?.once ?? false, deferred, this.#connections.length);\n this.#connections.push(connection);\n this.#liveCount += 1;\n if (owner !== undefined) {\n connection.ownerDisconnect = owner.onDestroyed.connect(() => {\n this.#remove(connection);\n });\n }\n return () => {\n this.#remove(connection);\n };\n }\n\n /**\n * Delivers a value to every attached handler, in connection order.\n *\n * @param value - The payload. Omitted for `Signal<void>`.\n * @throws IgnifxError with code `IGX-0104` wrapping the first handler exception, when the signal\n * was constructed without an `onHandlerError` reporter.\n */\n emit(value: T): void {\n const connections = this.#connections;\n // Snapshotting the length — not the array — is what makes a handler connected during this emit\n // run on the *next* emit, with no per-emit allocation.\n const count = connections.length;\n if (count === 0) {\n return;\n }\n this.#emitDepth += 1;\n let firstError: unknown = null;\n let errorCount = 0;\n for (let index = 0; index < count; index += 1) {\n const connection = connections[index];\n if (connection === undefined) {\n continue;\n }\n const handler = connection.handler;\n if (handler === null) {\n continue;\n }\n const isOnce = connection.once;\n if (isOnce) {\n this.#remove(connection);\n }\n try {\n if (connection.deferred && this.#deferredQueue !== null) {\n this.#deferredQueue.enqueue(() => {\n // A `once` connection is already detached; any other must still be attached at flush\n // time, so disconnecting before the queue drains cancels the delivery.\n if (isOnce || connection.handler !== null) {\n handler(value);\n }\n });\n } else {\n handler(value);\n }\n } catch (error) {\n errorCount += 1;\n if (this.#onHandlerError === null) {\n if (errorCount === 1) {\n firstError = error;\n }\n } else {\n this.#onHandlerError(error, this);\n }\n }\n }\n this.#emitDepth -= 1;\n if (this.#emitDepth === 0 && this.#deadCount > 0) {\n this.#compact();\n }\n if (errorCount > 0 && this.#onHandlerError === null) {\n throw new IgnifxError(CoreErrorCode.signalHandlerThrew, \"A signal handler threw.\", {\n cause: firstError,\n context: { errorCount, handlerCount: count },\n hint: \"Handle the failure in the handler, or give the signal an onHandlerError reporter.\",\n });\n }\n }\n\n /**\n * Detaches the first connection made with this handler. Detaching a handler that is not connected\n * is a no-op.\n *\n * @param handler - The listener to detach.\n */\n disconnect(handler: SignalHandler<T>): void {\n for (const connection of this.#connections) {\n if (connection.handler === handler) {\n this.#remove(connection);\n return;\n }\n }\n }\n\n /** Detaches every handler, including the auto-disconnect hooks held on owners. */\n clear(): void {\n // Iterating a copy keeps `#remove`'s swap-remove from shifting entries out from under the loop.\n // `clear` is a teardown operation, never a per-frame one, so the copy costs nothing that matters.\n for (const connection of this.#connections.slice()) {\n this.#remove(connection);\n }\n }\n\n /**\n * Marks a connection dead and, when no emit is in flight, removes it by swapping the last entry\n * into its slot. During an emit the entry is left as a tombstone so indices stay stable, and the\n * outermost emit compacts.\n *\n * @param connection - The connection to detach.\n */\n #remove(connection: Connection<T>): void {\n if (connection.handler === null) {\n return;\n }\n connection.handler = null;\n this.#liveCount -= 1;\n const ownerDisconnect = connection.ownerDisconnect;\n if (ownerDisconnect !== null) {\n connection.ownerDisconnect = null;\n ownerDisconnect();\n }\n if (this.#emitDepth > 0) {\n this.#deadCount += 1;\n return;\n }\n this.#swapRemove(connection.index);\n }\n\n /** Removes every tombstone left behind by an emit. */\n #compact(): void {\n const connections = this.#connections;\n for (let index = connections.length - 1; index >= 0; index -= 1) {\n const connection = connections[index];\n if (connection !== undefined && connection.handler === null) {\n this.#swapRemove(index);\n }\n }\n this.#deadCount = 0;\n }\n\n /**\n * Removes the entry at an index by moving the last entry into its place.\n *\n * @param index - The slot to vacate.\n */\n #swapRemove(index: number): void {\n const connections = this.#connections;\n const last = connections.length - 1;\n if (index !== last) {\n const moved = connections[last];\n if (moved !== undefined) {\n connections[index] = moved;\n moved.index = index;\n }\n }\n connections.pop();\n }\n}\n","/**\n * Address arithmetic (`docs/architecture/05-assets-and-loading.md` §2): splitting the sub-asset\n * fragment off, recognising the URL forms that bypass the asset root, joining a relative address\n * onto that root, and picking the longest registered extension an address ends with.\n *\n * Everything here is a pure function over strings so the rules can be tested without a service, an\n * app, or a network.\n */\n\n/** The URL schemes §2 accepts verbatim: an address in one of these is never joined to the root. */\nconst ABSOLUTE_PREFIXES: readonly string[] = Object.freeze([\"http://\", \"https://\", \"blob:\", \"data:\"]);\n\n/** The separator between an address and its sub-asset fragment. */\nconst FRAGMENT_SEPARATOR = \"#\";\n\n/** The separator between the asset root and a relative address. */\nconst PATH_SEPARATOR = \"/\";\n\n/**\n * An address split into the part that resolves to a URL and the part loaders interpret.\n *\n * @internal\n */\nexport interface SplitAddress {\n /** The address with the fragment removed. */\n readonly path: string;\n /** The text after the first `#`, or `null` when the address carries none. */\n readonly fragment: string | null;\n}\n\n/**\n * Splits a sub-asset fragment off an address.\n *\n * @remarks\n * Only the *first* `#` separates; everything after it is the fragment, so a grammar such as\n * `#frame:a#b` reaches the loader intact. A `data:` URL is never split: its payload may legitimately\n * contain a `#`, and it has no sub-assets to name.\n *\n * @param address - The address as game code wrote it.\n * @returns The path and the fragment.\n *\n * @example\n * ```ts\n * splitFragment(\"models/hero.glb#animation:Run\"); // { path: \"models/hero.glb\", fragment: \"animation:Run\" }\n * ```\n *\n * @internal\n */\nexport function splitFragment(address: string): SplitAddress {\n if (address.startsWith(\"data:\")) {\n return { path: address, fragment: null };\n }\n const index = address.indexOf(FRAGMENT_SEPARATOR);\n if (index < 0) {\n return { path: address, fragment: null };\n }\n return { path: address.slice(0, index), fragment: address.slice(index + 1) };\n}\n\n/**\n * Reports whether an address is already a URL the service can fetch as it stands.\n *\n * @param path - A fragment-free address.\n * @returns `true` for `http://`, `https://`, `blob:`, and `data:`.\n *\n * @internal\n */\nexport function isAbsoluteAddress(path: string): boolean {\n for (let index = 0; index < ABSOLUTE_PREFIXES.length; index += 1) {\n const prefix = ABSOLUTE_PREFIXES[index];\n if (prefix !== undefined && path.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Joins a relative address onto the asset root with exactly one separator.\n *\n * @param root - The asset root; an empty root leaves the address alone.\n * @param path - A fragment-free relative address.\n * @returns The URL to fetch.\n *\n * @example\n * ```ts\n * joinRoot(\"assets/\", \"models/hero.glb\"); // \"assets/models/hero.glb\"\n * ```\n *\n * @internal\n */\nexport function joinRoot(root: string, path: string): string {\n if (root.length === 0) {\n return path;\n }\n const base = root.endsWith(PATH_SEPARATOR) ? root.slice(0, -1) : root;\n const tail = path.startsWith(PATH_SEPARATOR) ? path.slice(1) : path;\n return `${base}${PATH_SEPARATOR}${tail}`;\n}\n\n/**\n * Picks the longest registered extension an address ends with, so `.scene.json` wins over `.json`.\n *\n * @param path - A fragment-free address.\n * @param extensions - Every registered extension, each with its leading dot.\n * @returns The winning extension in lower case, or `null` when none matches.\n *\n * @example\n * ```ts\n * matchExtension(\"levels/1.scene.json\", [\".json\", \".scene.json\"]); // \".scene.json\"\n * ```\n *\n * @internal\n */\nexport function matchExtension(path: string, extensions: Iterable<string>): string | null {\n const lower = path.toLowerCase();\n let best: string | null = null;\n for (const extension of extensions) {\n if (lower.endsWith(extension) && (best === null || extension.length > best.length)) {\n best = extension;\n }\n }\n return best;\n}\n\n/**\n * Normalises an extension the way the registry stores it: lower case, with a leading dot.\n *\n * @param extension - The extension as an extension author wrote it.\n * @returns The normalised form.\n *\n * @internal\n */\nexport function normalizeExtension(extension: string): string {\n const lower = extension.toLowerCase();\n return lower.startsWith(\".\") ? lower : `.${lower}`;\n}\n\n/**\n * The scheme in-memory assets are registered under (`Assets.register`). An address that starts with\n * it names a value built in code — a `MeshAsset.box(...)`, a `MaterialAsset.pbr(...)` — rather than\n * a file, so nothing fetches it and nothing can write it into a scene file.\n *\n * @internal\n */\nexport const MEMORY_ADDRESS_PREFIX = \"memory:\";\n\n/**\n * Reports whether an address names an in-memory asset rather than a file.\n *\n * @param address - The address to test.\n * @returns `true` when the address carries the `memory:` scheme.\n *\n * @example\n * ```ts\n * isMemoryAddress(\"memory:mesh/01J9Z6M7E5S3A0V2Q4R8T1Y6WX\"); // true\n * ```\n *\n * @internal\n */\nexport function isMemoryAddress(address: string): boolean {\n return address.startsWith(MEMORY_ADDRESS_PREFIX);\n}\n","/**\n * Scalar helpers shared by the vector, quaternion and matrix types and by game code.\n *\n * Angles are **degrees** in every public API unless the name ends in `Rad`/`Radians`\n * (coding standards §5.1, ADR-0011). Every function here is a pure scalar function: none of them\n * allocate, so they are safe in per-frame code (coding standards §7).\n */\n\n/**\n * The default tolerance for approximate float comparisons. Chosen for single-precision positions in\n * metres: `Float32Array` round-tripping loses roughly 1e-7 of relative precision, so 1e-6 is the\n * smallest value that does not report false differences on data that has been through the GPU.\n *\n * @public\n */\nexport const EPSILON: number = 1e-6;\n\n/**\n * Multiplier that converts degrees to radians.\n *\n * @public\n */\nexport const DEG_TO_RAD: number = Math.PI / 180;\n\n/**\n * Multiplier that converts radians to degrees.\n *\n * @public\n */\nexport const RAD_TO_DEG: number = 180 / Math.PI;\n\n/**\n * Converts an angle from degrees to radians.\n *\n * @param degrees - The angle in degrees.\n * @returns The same angle in radians.\n *\n * @public\n */\nexport function degToRad(degrees: number): number {\n return degrees * DEG_TO_RAD;\n}\n\n/**\n * Converts an angle from radians to degrees.\n *\n * @param radians - The angle in radians.\n * @returns The same angle in degrees.\n *\n * @public\n */\nexport function radToDeg(radians: number): number {\n return radians * RAD_TO_DEG;\n}\n\n/**\n * Constrains a value to an inclusive range.\n *\n * @param value - The value to constrain.\n * @param min - The lower bound.\n * @param max - The upper bound.\n * @returns `min` when `value` is smaller, `max` when it is larger, otherwise `value` unchanged.\n * `NaN` propagates.\n *\n * @example\n * ```ts\n * clamp(12, 0, 10); // 10\n * ```\n *\n * @public\n */\nexport function clamp(value: number, min: number, max: number): number {\n if (value < min) {\n return min;\n }\n if (value > max) {\n return max;\n }\n return value;\n}\n\n/**\n * Constrains a value to the 0–1 range.\n *\n * @param value - The value to constrain.\n * @returns The value clamped into `[0, 1]`.\n *\n * @public\n */\nexport function clamp01(value: number): number {\n return clamp(value, 0, 1);\n}\n\n/**\n * Linearly interpolates between two values. The interpolant is **not** clamped, so values outside\n * `[0, 1]` extrapolate; wrap `t` in {@link clamp01} when that is not wanted.\n *\n * @param a - The value returned at `t === 0`.\n * @param b - The value returned at `t === 1`.\n * @param t - The interpolant.\n * @returns The interpolated value.\n *\n * @example\n * ```ts\n * lerp(0, 10, 0.25); // 2.5\n * ```\n *\n * @public\n */\nexport function lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\n/**\n * The inverse of {@link lerp}: finds the interpolant that maps `a`–`b` onto `value`.\n *\n * @param a - The value that maps to 0.\n * @param b - The value that maps to 1.\n * @param value - The value to locate.\n * @returns The interpolant, clamped into `[0, 1]`. Returns 0 when `a` and `b` are equal.\n *\n * @public\n */\nexport function inverseLerp(a: number, b: number, value: number): number {\n if (a === b) {\n return 0;\n }\n return clamp01((value - a) / (b - a));\n}\n\n/**\n * Smoothly interpolates between two edges with a Hermite curve (the GLSL `smoothstep`), easing in\n * and out instead of the straight ramp of {@link lerp}.\n *\n * @param edge0 - The value below which the result is 0.\n * @param edge1 - The value above which the result is 1.\n * @param x - The value to map.\n * @returns A value in `[0, 1]`. Degenerate edges (`edge0 === edge1`) step from 0 to 1 at the edge.\n *\n * @example\n * ```ts\n * smoothStep(0, 1, 0.5); // 0.5, but with zero slope at 0 and 1\n * ```\n *\n * @public\n */\nexport function smoothStep(edge0: number, edge1: number, x: number): number {\n if (edge0 === edge1) {\n return x < edge0 ? 0 : 1;\n }\n const t = clamp01((x - edge0) / (edge1 - edge0));\n return t * t * (3 - 2 * t);\n}\n\n/**\n * Moves a value towards a target without overshooting it.\n *\n * @param current - The value to move.\n * @param target - The value to move towards.\n * @param maxDelta - The largest step allowed this call; negative values move away from the target.\n * @returns The stepped value, exactly `target` once the remaining distance fits in `maxDelta`.\n *\n * @example\n * ```ts\n * // frame-rate independent approach at 2 units per second\n * health = moveTowards(health, 100, 2 * time.deltaTime);\n * ```\n *\n * @public\n */\nexport function moveTowards(current: number, target: number, maxDelta: number): number {\n const delta = target - current;\n if (Math.abs(delta) <= maxDelta) {\n return target;\n }\n return current + (delta < 0 ? -maxDelta : maxDelta);\n}\n\n/**\n * Wraps a value into `[0, length)`, the way a looping animation time behaves. Unlike `%` the result\n * is never negative.\n *\n * @param t - The value to wrap.\n * @param length - The positive period to wrap into.\n * @returns The wrapped value, clamped into `[0, length]` so float error cannot escape the range.\n *\n * @example\n * ```ts\n * repeat(-1, 4); // 3\n * ```\n *\n * @public\n */\nexport function repeat(t: number, length: number): number {\n return clamp(t - Math.floor(t / length) * length, 0, length);\n}\n\n/**\n * Bounces a value back and forth between 0 and `length`, the way a ping-pong animation behaves.\n *\n * @param t - The value to fold.\n * @param length - The positive half-period to fold into.\n * @returns A value in `[0, length]` that rises then falls as `t` increases.\n *\n * @example\n * ```ts\n * pingPong(5, 4); // 3\n * ```\n *\n * @public\n */\nexport function pingPong(t: number, length: number): number {\n return length - Math.abs(repeat(t, length * 2) - length);\n}\n\n/**\n * Compares two numbers with an absolute tolerance. Use this instead of `===` on anything that has\n * been through a matrix, a quaternion or a `Float32Array`.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @param epsilon - The largest difference still considered equal. Defaults to {@link EPSILON}.\n * @returns `true` when the values differ by no more than `epsilon`. `NaN` is never approximately\n * equal to anything, including itself.\n *\n * @public\n */\nexport function approximately(a: number, b: number, epsilon: number = EPSILON): boolean {\n return Math.abs(a - b) <= epsilon;\n}\n\n/**\n * The sign of a value, with zero treated as positive (matching Unity's `Mathf.Sign`, and unlike\n * `Math.sign`, which returns 0 and `-0`).\n *\n * @param value - The value to inspect.\n * @returns `-1` for negative values, `1` for positive values and for both `0` and `-0`, and `NaN`\n * for `NaN`.\n *\n * @public\n */\nexport function sign(value: number): number {\n if (Number.isNaN(value)) {\n return Number.NaN;\n }\n return value < 0 ? -1 : 1;\n}\n\n/**\n * Wraps an angle in degrees into `[-180, 180)`, the range rotations are most readable in.\n *\n * @param degrees - The angle to wrap.\n * @returns The equivalent angle in `[-180, 180)`; exactly `180` wraps to `-180`.\n *\n * @example\n * ```ts\n * wrapAngleDegrees(370); // 10\n * wrapAngleDegrees(-190); // 170\n * ```\n *\n * @public\n */\nexport function wrapAngleDegrees(degrees: number): number {\n return repeat(degrees + 180, 360) - 180;\n}\n\n/**\n * The shortest signed rotation from one angle to another, in degrees.\n *\n * @param fromDegrees - The starting angle.\n * @param toDegrees - The target angle.\n * @returns The signed difference in `[-180, 180)`.\n *\n * @example\n * ```ts\n * deltaAngleDegrees(350, 10); // 20, not -340\n * ```\n *\n * @public\n */\nexport function deltaAngleDegrees(fromDegrees: number, toDegrees: number): number {\n return wrapAngleDegrees(toDegrees - fromDegrees);\n}\n\n/**\n * Interpolates between two angles in degrees the short way around the circle.\n *\n * @param fromDegrees - The angle returned at `t === 0`.\n * @param toDegrees - The angle approached at `t === 1`.\n * @param t - The interpolant; not clamped, matching {@link lerp}.\n * @returns The interpolated angle. It is not wrapped, so feeding the result back in is stable.\n *\n * @example\n * ```ts\n * lerpAngleDegrees(350, 10, 0.5); // 360\n * ```\n *\n * @public\n */\nexport function lerpAngleDegrees(fromDegrees: number, toDegrees: number, t: number): number {\n return fromDegrees + deltaAngleDegrees(fromDegrees, toDegrees) * t;\n}\n","import { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { App } from \"../app/types.js\";\nimport type { ErrorCode } from \"../errors/error-codes.js\";\nimport type { IgnifxErrorOptions } from \"../errors/ignifx-error.js\";\nimport type { LiteEngine } from \"../lite/scene.js\";\nimport type { JsonObject } from \"../schema/json.js\";\nimport type { SignalLike } from \"../signal/signal.js\";\n\n/**\n * The asset contract (`docs/architecture/05-assets-and-loading.md` §2–§5): addresses, handles,\n * loaders, the manifest, and the `app.assets` service itself.\n *\n * The module declares types plus one error class — no service behaviour — so that loaders written\n * in other packages (`@ignifx/audio`, `@ignifx/2d`, the GPU loaders of `07-rendering.md`) can be\n * written against it without importing the implementation, and so that nothing here imports\n * `@babylonjs/lite` (coding standards §4; the `LoaderContext.lite` escape hatch carries the engine\n * handle through as the adapter's own re-exported type alias).\n */\n\n/**\n * The serializable form of an asset reference (`docs/architecture/05-assets-and-loading.md` §2).\n * It is a plain object so that it survives `JSON.stringify` and the schema codec unchanged; the way\n * to turn one into a handle is `app.assets.load(ref)`, never a method on the reference.\n *\n * @typeParam T - The loaded value type this reference points at. It is a compile-time marker only:\n * `assetOf` is never assigned at runtime and is never serialized. It exists so that\n * `AssetRef<TextureAsset>` and `AssetRef<ModelAsset>` are different types.\n *\n * @example\n * ```ts\n * const hero: AssetRef<ModelAsset> = assetRef(\"models/hero.glb\");\n * const handle = app.assets.load(hero);\n * ```\n *\n * @public\n */\nexport interface AssetRef<T = unknown> {\n /** The address, for example `models/hero.glb` or `sprites/ui.atlas.json#frame:button_idle`. */\n readonly address: string;\n /** The asset type name, when the address alone does not identify it. */\n readonly type?: string;\n /** Compile-time marker for the loaded value type; never present at runtime. */\n readonly assetOf?: T;\n}\n\n/**\n * Where an {@link AssetHandle} is in its life\n * (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * @public\n */\nexport type AssetState = \"loading\" | \"loaded\" | \"failed\" | \"released\";\n\n/**\n * The reference-counted handle every load returns\n * (`docs/architecture/05-assets-and-loading.md` §3). Handles are shared: two loads of the same\n * `(address, type)` return the same object with `refCount` incremented, and each `load` must be\n * paired with exactly one {@link AssetHandle.release}.\n *\n * @typeParam T - The loaded value type.\n *\n * @remarks\n * A handle never becomes an invalid object. After the last holder releases it and the collector\n * has run, `state` is `\"released\"` and reading `value` throws `IGX-0501`; loading the same address\n * again starts a fresh load and returns a fresh handle.\n *\n * @example\n * ```ts\n * const model = app.assets.load<ModelAsset>(\"models/hero.glb\");\n * // In a coroutine: `yield model.promise` resumes on the first Update after delivery.\n * await model.promise;\n * model.release();\n * ```\n *\n * @public\n */\nexport interface AssetHandle<T = unknown> {\n /** The address this handle was requested under, fragment included. */\n readonly address: string;\n /** The asset type the loader is registered under, for example `\"model\"`. */\n readonly type: string;\n /** Where the handle is in its life. */\n readonly state: AssetState;\n /**\n * The loaded value.\n *\n * @throws IgnifxError with code `IGX-0501` unless `state` is `\"loaded\"`.\n */\n readonly value: T;\n /** Resolves with {@link AssetHandle.value} at delivery, or rejects with an {@link AssetLoadError}. */\n readonly promise: Promise<T>;\n /** How far along the load is, in `[0, 1]`; bytes-weighted when the sizes are known. */\n readonly progress: number;\n /** Why the load failed, or `null` when it has not. */\n readonly error: AssetLoadError | null;\n /** How many holders the handle has. */\n readonly refCount: number;\n /**\n * Adds a holder.\n *\n * @returns This handle, so a retain reads inline.\n */\n retain(): this;\n /** Removes a holder. At zero the asset is unloaded after `assets.gcDelay` seconds. */\n release(): void;\n /** Emitted at delivery when hot reload replaced the value; `value` is already the new one. */\n readonly onReplaced: SignalLike<T>;\n /**\n * Releases one holder when the handle leaves a `using` block — exactly {@link AssetHandle.release}\n * (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * @example\n * ```ts\n * using icon = app.assets.load<TextureAsset>(\"ui/icon.png\");\n * await icon.promise;\n * ```\n */\n [Symbol.dispose](): void;\n}\n\n/**\n * Options accepted by every load entry point of {@link Assets}.\n *\n * @public\n */\nexport interface LoadOptions {\n /** Aborts this request. Whether it aborts the shared load is documented on {@link Assets.load}. */\n readonly signal?: AbortSignal;\n /** Higher runs first; ties break in request order. Defaults to `0`. */\n readonly priority?: number;\n /** The asset type, when the address's extension does not identify it. */\n readonly type?: string;\n /**\n * Called at delivery whenever this request's progress changed.\n *\n * @param fraction - How far along the load is, in `[0, 1]`.\n */\n readonly onProgress?: (fraction: number) => void;\n}\n\n/**\n * A group of loads requested together\n * (`docs/architecture/05-assets-and-loading.md` §4).\n *\n * @public\n */\nexport interface BatchHandle {\n /** Settles once every handle in the batch has settled; rejects with the first failure. */\n readonly promise: Promise<void>;\n /** The mean of the batch's handle progresses, in `[0, 1]`. */\n readonly progress: number;\n /** The handles the batch retains. */\n readonly handles: readonly AssetHandle[];\n /** Releases every handle the batch retains. Calling it twice is a no-op. */\n release(): void;\n /** Aborts every load the batch started and releases it. */\n cancel(): void;\n}\n\n/**\n * One address in the manifest (`docs/architecture/05-assets-and-loading.md` §7).\n *\n * @public\n */\nexport interface AssetManifestEntry {\n /** The address game code asks for. */\n readonly address: string;\n /** The URL to fetch, usually content-hashed in production builds. */\n readonly url: string;\n /** The byte size, when the build knows it; it makes progress bytes-weighted. */\n readonly bytes?: number;\n /** The content hash, for cache validation. */\n readonly hash?: string;\n /** The asset type, when the extension does not identify it. */\n readonly type?: string;\n /** The group labels this entry belongs to, such as `\"boot\"` or `\"level1\"`. */\n readonly groups?: readonly string[];\n /**\n * The `.meta.json` sidecar the build read for this address, verbatim\n * (`docs/architecture/05-assets-and-loading.md` §7). Loaders read the sub-object they own — the\n * texture loader reads `meta.texture`, the model loader reads `meta.model` — and ignore the rest,\n * so one sidecar can carry options for several tools.\n *\n * @example\n * ```json\n * { \"groups\": [\"level1\"], \"texture\": { \"srgb\": true, \"mipMaps\": false } }\n * ```\n */\n readonly meta?: JsonObject;\n}\n\n/**\n * The address-to-URL table generated by `@ignifx/vite-plugin`\n * (`docs/architecture/05-assets-and-loading.md` §7).\n *\n * @public\n */\nexport interface AssetManifest {\n /** The file's format discriminator. */\n readonly format: \"ignifx.manifest\";\n /** The format version this build can read. */\n readonly formatVersion: 1;\n /** The asset root every relative address is resolved against. */\n readonly root: string;\n /** Every addressed file. */\n readonly entries: readonly AssetManifestEntry[];\n}\n\n/**\n * What a loader is handed for one load\n * (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @remarks\n * The three `fetch*` methods share one code path: the bytes are streamed through the service's\n * priority queue, counted into the handle's progress, and aborted with {@link LoaderContext.signal}.\n * A loader that reaches the network any other way loses progress, cancellation, and retries.\n *\n * @public\n */\nexport interface LoaderContext {\n /** The address being loaded, fragment included. */\n readonly address: string;\n /** The URL the address resolved to, fragment stripped. */\n readonly url: string;\n /** The `#fragment` part of the address, or `null` when it carries none. */\n readonly fragment: string | null;\n /** The asset type the loader is registered under. */\n readonly type: string;\n /** The app the load belongs to. */\n readonly app: App;\n /** Aborted when the request is cancelled or the app is disposed. */\n readonly signal: AbortSignal;\n /**\n * Fetches the address as bytes, with progress and cancellation.\n *\n * @returns The response body.\n */\n fetchBytes(): Promise<ArrayBuffer>;\n /**\n * Fetches the address as UTF-8 text.\n *\n * @returns The decoded body.\n */\n fetchText(): Promise<string>;\n /**\n * Fetches the address and parses it as JSON.\n *\n * @typeParam J - The parsed shape, as the loader declares it.\n * @returns The parsed body.\n */\n fetchJson<J = unknown>(): Promise<J>;\n /**\n * Loads another asset as a dependency of this one: its progress counts into this load and the\n * retain it takes is released when this asset is unloaded.\n *\n * @typeParam D - The dependency's loaded value type.\n * @param ref - The dependency's address or reference.\n * @param options - Priority, type, progress, and cancellation.\n * @returns The dependency's handle, once it has been delivered.\n */\n loadDependency<D>(ref: AssetRef<D> | string, options?: LoadOptions): Promise<AssetHandle<D>>;\n /**\n * Reports progress for loaders that cannot express it in bytes.\n *\n * @param fraction - How far along the load is, in `[0, 1]`.\n */\n reportProgress(fraction: number): void;\n /**\n * The `.meta.json` sidecar the build recorded for this address, or `null` when the manifest lists\n * none (`docs/architecture/05-assets-and-loading.md` §7).\n *\n * @remarks\n * Read the sub-object your loader owns and ignore the rest: one sidecar carries options for\n * several tools, and `groups` in it belongs to the manifest generator, not to a loader.\n *\n * @example\n * ```ts\n * const srgb = asRecord(ctx.meta?.[\"texture\"])?.[\"srgb\"] === true;\n * ```\n */\n readonly meta: JsonObject | null;\n /** Unstable Babylon Lite escape hatch for GPU loaders (`docs/architecture/00-overview.md` §3). */\n readonly lite: { readonly engine: LiteEngine };\n}\n\n/**\n * How one asset type is turned into a value\n * (`docs/architecture/05-assets-and-loading.md` §5). Loaders are pure with respect to the world:\n * they produce values and never create entities.\n *\n * @typeParam T - The value the loader produces.\n *\n * @example\n * ```ts\n * const jsonLoader: AssetLoader<unknown> = {\n * type: \"json\",\n * extensions: [\".json\"],\n * load: (ctx) => ctx.fetchJson(),\n * };\n * ```\n *\n * @public\n */\nexport interface AssetLoader<T = unknown> {\n /** The type name the loader is registered under, for example `\"texture\"`. */\n readonly type: string;\n /** The address suffixes that select this loader, each with its leading dot. */\n readonly extensions: readonly string[];\n /**\n * Produces the value.\n *\n * @param ctx - The address, the fetch helpers, and the abort signal.\n * @returns The loaded value.\n */\n load(ctx: LoaderContext): Promise<T>;\n /**\n * Releases whatever the value owns — GPU buffers, audio nodes, object URLs.\n *\n * @param value - The value {@link AssetLoader.load} produced.\n * @param ctx - The same context the load ran with.\n */\n unload?(value: T, ctx: LoaderContext): void;\n /**\n * Re-produces the value in development hot reload. Defaults to unload plus load.\n *\n * @param ctx - The context for the new load.\n * @param previous - The value being replaced.\n * @returns The new value.\n */\n reload?(ctx: LoaderContext, previous: T): Promise<T>;\n /**\n * Extracts a sub-asset named by an address fragment, such as `#animation:Run`.\n *\n * @remarks\n * Declaring it is what makes `models/hero.glb#animation:Run` load the base address once and share\n * it: the fragment handle retains the base handle and its value is whatever this returns. A\n * loader that does not declare it is invoked with the fragment in {@link LoaderContext.fragment}\n * and owns the whole address itself.\n *\n * @param fragment - The text after `#`.\n * @param value - The base address's value.\n * @returns The sub-asset.\n */\n parseFragment?(fragment: string, value: T): unknown;\n}\n\n/**\n * An asset type declared without a loader, so that addresses resolve to a type before the loader\n * that reads them is registered (`docs/architecture/04-extensions.md` §1).\n *\n * @public\n */\nexport interface AssetTypeDefinition {\n /** The type name, for example `\"texture\"`. */\n readonly type: string;\n /** The address suffixes that select it, each with its leading dot. */\n readonly extensions: readonly string[];\n}\n\n/**\n * The aggregate payload of {@link Assets.onProgress}: how the current batch of work is going\n * (`docs/architecture/05-assets-and-loading.md` §4).\n *\n * @public\n */\nexport interface AssetProgress {\n /** How many of the loads in flight have settled. */\n readonly loaded: number;\n /** How many loads are in the current run. */\n readonly total: number;\n /** Bytes received so far. */\n readonly bytesLoaded: number;\n /** Bytes expected, as far as the manifest and the response headers say. */\n readonly bytesTotal: number;\n}\n\n/**\n * The `assets` project settings section\n * (`docs/architecture/04-extensions.md` §5, `05-assets-and-loading.md` §4).\n *\n * @public\n */\nexport interface AssetsSettings {\n /** The asset root relative addresses resolve against. Defaults to `\"assets\"`. */\n readonly root: string;\n /** Manifest group labels loaded during `app.start()`. Defaults to none. */\n readonly preload: readonly string[];\n /** How many fetches may be in flight at once. Defaults to `6`. */\n readonly concurrency: number;\n /** How many seconds a zero-reference asset stays cached. Defaults to `5`. */\n readonly gcDelay: number;\n /** How many times a failed fetch is retried. Defaults to `2`. */\n readonly retries: number;\n}\n\n/**\n * Options accepted by {@link Assets.register}.\n *\n * @public\n */\nexport interface RegisterAssetOptions {\n /** The asset type the value is published under, for example `\"mesh\"` or `\"material\"`. */\n readonly type: string;\n /**\n * The address to publish it at. Defaults to a generated `memory:<type>/<ulid>`; pass one only to\n * make an in-code asset reachable by name from `app.assets.get`.\n */\n readonly address?: string;\n}\n\n/**\n * The `fetch` implementation the service performs every read through\n * (`docs/architecture/05-assets-and-loading.md` §8). Injecting it is how headless tests supply\n * deterministic responses and how a Node app maps addresses onto `fs` (Phase 9).\n *\n * @public\n */\nexport type FetchLike = typeof globalThis.fetch;\n\n/**\n * The asset service, reached as `app.assets`\n * (`docs/architecture/05-assets-and-loading.md` §4).\n *\n * @example\n * ```ts\n * const batch = app.assets.loadAll([\"ui/font.ttf\", \"sprites/hero.png\"]);\n * app.assets.onProgress.connect((p) => bar.set(p.loaded / p.total));\n * await batch.promise;\n * ```\n *\n * @public\n */\nexport interface Assets {\n /**\n * Requests an asset and returns its handle immediately.\n *\n * @remarks\n * Completion is delivered in the `PreUpdate` phase of a later frame, never mid-phase: `state`\n * flips and `promise` settles at that one point\n * (`docs/architecture/01-lifecycle-and-time.md` §3 step 2).\n *\n * An `options.signal` abort drops *this* request's hold. It aborts the shared load only when no\n * other request is still interested in it; a load two scripts asked for keeps going when one of\n * them cancels, and the shared handle still resolves.\n *\n * @typeParam T - The loaded value type.\n * @param ref - The address, or a reference carrying one.\n * @param options - Priority, type, progress, and cancellation.\n * @returns The shared handle, with one more holder.\n * @throws IgnifxError with code `IGX-0504` when no loader claims the address, or `IGX-0106` when\n * the app has been disposed.\n */\n load<T>(ref: AssetRef<T> | string, options?: LoadOptions): AssetHandle<T>;\n /**\n * Requests an asset and waits for the same delivery point {@link Assets.load} settles at.\n *\n * @typeParam T - The loaded value type.\n * @param ref - The address, or a reference carrying one.\n * @param options - Priority, type, progress, and cancellation.\n * @returns The handle, once it has loaded.\n */\n loadAsync<T>(ref: AssetRef<T> | string, options?: LoadOptions): Promise<AssetHandle<T>>;\n /**\n * Requests several assets as one batch.\n *\n * @param refs - The addresses or references.\n * @param options - Priority, type, progress, and cancellation, applied to every member.\n * @returns The batch.\n */\n loadAll(refs: readonly (AssetRef | string)[], options?: LoadOptions): BatchHandle;\n /**\n * Loads every manifest entry carrying a group label.\n *\n * @param group - The label, such as `\"boot\"`.\n * @param options - Priority, progress, and cancellation.\n * @returns The batch; empty when the manifest knows no such group.\n */\n preloadGroup(group: string, options?: LoadOptions): BatchHandle;\n /**\n * Looks a cached handle up without changing its reference count.\n *\n * @typeParam T - The loaded value type.\n * @param address - The address, fragment included.\n * @returns The handle, or `null` when the address is not cached.\n */\n get<T>(address: string): AssetHandle<T> | null;\n /**\n * Removes one holder from a handle, by object or by address.\n *\n * @param handleOrAddress - The handle, or the address it was requested under.\n */\n release(handleOrAddress: AssetHandle | string): void;\n /** Unloads every zero-reference asset now, without waiting for {@link Assets.gcDelay}. */\n gc(): void;\n /** How many seconds a zero-reference asset stays cached. `0` unloads at the next delivery. */\n gcDelay: number;\n /**\n * Resolves an address to the URL the service fetches.\n *\n * @param address - The address; the fragment is stripped.\n * @returns The manifest's URL for the address, or `<root>/<address>`.\n */\n resolveUrl(address: string): string;\n /**\n * Registers a loader. Extensions normally call `ctx.registerAssetLoader` instead.\n *\n * @param loader - The loader.\n * @throws IgnifxError with code `IGX-0506` when the type is already registered.\n */\n registerLoader(loader: AssetLoader): void;\n /**\n * Declares an asset type that has no loader yet.\n *\n * @param type - The type name and the extensions that select it.\n */\n registerType(type: AssetTypeDefinition): void;\n /**\n * Publishes a value built in code as an asset, so an `asset()` field can hold it\n * (`docs/architecture/05-assets-and-loading.md` §3). This is what `MeshAsset.box(…)` and\n * `MaterialAsset.pbr(…)` return.\n *\n * @remarks\n * The handle is created already `loaded`, under a synthetic `memory:<type>/<ulid>` address, with\n * one holder — the caller. It plays by the ordinary rules from there: `retain`/`release` count,\n * the collector unloads it `gcDelay` seconds after the last holder lets go, and the registered\n * type's loader `unload` runs then if one exists. Because the address names no file, serializing\n * a component that references it writes `null` and reports the loss.\n *\n * @typeParam T - The value type.\n * @param value - The already-built value.\n * @param options - The asset type it is registered under, and an explicit address to publish it\n * at instead of the generated one.\n * @returns The handle, with one holder.\n *\n * @example\n * ```ts\n * using box = app.assets.register(mesh, { type: \"mesh\" });\n * ```\n */\n register<T>(value: T, options: RegisterAssetOptions): AssetHandle<T>;\n /** The address-to-URL table, empty until a build supplies one. */\n readonly manifest: AssetManifest;\n /** Emitted at delivery whenever the aggregate progress of the loads in flight changed. */\n readonly onProgress: SignalLike<AssetProgress>;\n}\n\n/**\n * Options accepted by {@link AssetLoadError}.\n *\n * @public\n */\nexport interface AssetLoadErrorOptions extends IgnifxErrorOptions {\n /** The address that failed. */\n readonly address: string;\n /** The URL it resolved to. */\n readonly url: string;\n}\n\n/**\n * The failure an {@link AssetHandle.promise} rejects with\n * (`docs/architecture/05-assets-and-loading.md` §9). Its `code` is one of `IGX-0502` (aborted),\n * `IGX-0503` (the app was disposed), `IGX-0504` (no loader), or `IGX-0505` (the load failed after\n * every retry, with the last failure as `cause`).\n *\n * @example\n * ```ts\n * try {\n * await app.assets.loadAsync(\"levels/1.scene.json\");\n * } catch (error) {\n * if (error instanceof AssetLoadError) {\n * app.log.error(\"{address} failed from {url}\", error.address, error.url);\n * }\n * }\n * ```\n *\n * @public\n */\nexport class AssetLoadError extends IgnifxError {\n /** The address that failed. */\n readonly address: string;\n\n /** The URL it resolved to. */\n readonly url: string;\n\n /**\n * Creates an asset failure.\n *\n * @param code - The `IGX-05xx` code.\n * @param message - The actionable development sentence.\n * @param options - The address and URL, plus the standard `context`, `hint`, and `cause`.\n */\n constructor(code: ErrorCode, message: string, options: AssetLoadErrorOptions) {\n super(code, message, options);\n this.name = \"AssetLoadError\";\n this.address = options.address;\n this.url = options.url;\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { clamp01 } from \"../math/math-utils.js\";\nimport { Signal } from \"../signal/signal.js\";\nimport { AssetLoadError } from \"./types.js\";\nimport type { AssetHandle, AssetLoader, AssetState } from \"./types.js\";\n\n/**\n * The reference-counted handle and the load bookkeeping that hangs off it\n * (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * The class is deliberately **not** generic. `T` on the public `AssetHandle<T>` is the caller's\n * declaration of what a loader produces — the loader itself returns `unknown` — and `Signal<T>`\n * carries private state, which makes it invariant in `T`. Keeping the implementation on `unknown`\n * puts the single unavoidable assertion at the service's public boundary instead of scattering\n * variance workarounds through the cache.\n *\n * Everything a load needs while it is in flight lives here too: the abort controller, the retry\n * countdown, the collector countdown, the byte counters, and the dependency list. One object per\n * address means the cache is a plain `Map` and no per-frame lookup allocates (coding standards §7).\n */\n\n/**\n * What a handle needs from the service that owns it.\n *\n * @internal\n */\nexport interface AssetHandleHost {\n /**\n * Reports that a handle lost its last holder and may be collected.\n *\n * @param handle - The handle now at zero references.\n */\n onZeroReferences(handle: AssetHandleImpl): void;\n /**\n * Reports that a handle gained a holder, so a pending collection is called off.\n *\n * @param handle - The handle that was retained.\n */\n onRetained(handle: AssetHandleImpl): void;\n}\n\n/**\n * The countdown value meaning \"no timer is running\".\n *\n * @internal\n */\nexport const NO_TIMER = -1;\n\n/**\n * One cached asset: its public handle surface and its private load state.\n *\n * @internal\n */\nexport class AssetHandleImpl implements AssetHandle {\n /** The address as it was requested, fragment included. */\n readonly address: string;\n\n /** The fragment-free part of the address. */\n readonly path: string;\n\n /** The text after `#`, or `null`. */\n readonly fragment: string | null;\n\n /** The asset type the loader is registered under. */\n readonly type: string;\n\n /** The cache key, `address` and `type` joined. */\n readonly key: string;\n\n /** The URL {@link AssetHandleImpl.path} resolved to. */\n readonly url: string;\n\n /** The loader that produces and releases the value. */\n readonly loader: AssetLoader;\n\n /** Emitted at delivery when hot reload replaced the value. */\n readonly onReplaced: Signal<unknown>;\n\n /** Resolves with the value at delivery, or rejects with an {@link AssetLoadError}. */\n readonly promise: Promise<unknown>;\n\n /** Aborts the fetches of the load in flight, or `null` when nothing is running. */\n controller: AbortController | null = null;\n\n /** How many attempts have already failed; the exponent of the retry backoff. */\n attempt = 0;\n\n /** Seconds of unscaled time until the next retry, or {@link NO_TIMER}. */\n retryRemaining: number = NO_TIMER;\n\n /** Seconds of engine time until the asset is unloaded, or {@link NO_TIMER}. */\n gcRemaining: number = NO_TIMER;\n\n /** How many requests still want this load; the last one to abort cancels the fetch. */\n interested = 0;\n\n /** `true` while the loader is running. */\n isRunning = false;\n\n /** Bytes received so far. */\n bytesLoaded = 0;\n\n /** Bytes expected, from the manifest entry or the response's `Content-Length`; `0` when unknown. */\n bytesTotal = 0;\n\n /** What the loader last reported, used when the byte total is unknown. */\n reportedFraction = 0;\n\n /** Dependencies this asset retains; released when it is unloaded. */\n readonly dependencies: AssetHandleImpl[] = [];\n\n /** The highest priority any request for this address asked for; the fetches inherit it. */\n priority = 0;\n\n /** `true` while the handle sits in the service's progress watch list. */\n isWatched = false;\n\n /** `true` while the handle counts towards the aggregate progress of the current run. */\n isInSession = false;\n\n /** Per-request progress callbacks, invoked at delivery when the value changed. */\n readonly progressListeners: ((fraction: number) => void)[] = [];\n\n /** Abort-listener detach functions, one per request that supplied a signal. */\n readonly tickets: (() => void)[] = [];\n\n /** The progress last handed to {@link AssetHandleImpl.progressListeners}. */\n lastDeliveredProgress = -1;\n\n readonly #host: AssetHandleHost;\n\n readonly #resolve: (value: unknown) => void;\n\n readonly #reject: (reason: unknown) => void;\n\n #state: AssetState = \"loading\";\n\n #value: unknown = null;\n\n #error: AssetLoadError | null = null;\n\n #refCount = 0;\n\n /**\n * Creates a handle for one cached address.\n *\n * @param init - The address, its resolved URL, the loader, and the owning service.\n */\n constructor(init: AssetHandleInit) {\n this.address = init.address;\n this.path = init.path;\n this.fragment = init.fragment;\n this.type = init.type;\n this.key = init.key;\n this.url = init.url;\n this.loader = init.loader;\n this.#host = init.host;\n this.onReplaced = new Signal<unknown>();\n // The executor runs synchronously, so both functions are captured before the constructor ends.\n let resolveFn: (value: unknown) => void = passThrough;\n let rejectFn: (reason: unknown) => void = passThrough;\n this.promise = new Promise<unknown>((resolve, reject) => {\n resolveFn = resolve;\n rejectFn = reject;\n });\n this.#resolve = resolveFn;\n this.#reject = rejectFn;\n // A handle reports failure through `state` and `error` as well, so a caller that never touched\n // `promise` must not turn a handled failure into an unhandled rejection (coding standards §8).\n void this.promise.catch(passThrough);\n }\n\n /**\n * Where the handle is in its life.\n *\n * @returns The current state.\n */\n get state(): AssetState {\n return this.#state;\n }\n\n /**\n * The loaded value.\n *\n * @returns The value the loader produced.\n * @throws IgnifxError with code `IGX-0501` unless the state is `\"loaded\"`.\n */\n get value(): unknown {\n if (this.#state !== \"loaded\") {\n throw new AssetLoadError(\n CoreErrorCode.assetNotLoaded,\n `The asset ${this.address} has no value yet because it is ${this.#state}.`,\n {\n address: this.address,\n url: this.url,\n context: { asset: this.address, state: this.#state },\n hint: \"Await handle.promise, or check handle.state before reading handle.value.\",\n },\n );\n }\n return this.#value;\n }\n\n /**\n * Why the load failed.\n *\n * @returns The failure, or `null` when there was none.\n */\n get error(): AssetLoadError | null {\n return this.#error;\n }\n\n /**\n * How many holders the handle has.\n *\n * @returns The reference count.\n */\n get refCount(): number {\n return this.#refCount;\n }\n\n /**\n * How far along the load is, counting dependencies as equal shares of the whole.\n *\n * @returns A fraction in `[0, 1]`.\n */\n get progress(): number {\n if (this.#state === \"loaded\") {\n return 1;\n }\n const own = this.bytesTotal > 0 ? clamp01(this.bytesLoaded / this.bytesTotal) : clamp01(this.reportedFraction);\n const dependencies = this.dependencies;\n if (dependencies.length === 0) {\n return own;\n }\n let sum = own;\n for (let index = 0; index < dependencies.length; index += 1) {\n sum += dependencies[index]?.progress ?? 0;\n }\n return clamp01(sum / (dependencies.length + 1));\n }\n\n /**\n * Adds a holder.\n *\n * @returns This handle.\n */\n retain(): this {\n this.#refCount += 1;\n this.#host.onRetained(this);\n return this;\n }\n\n /**\n * Removes a holder. Releasing a handle that has none is a no-op: teardown order between two\n * objects that both held the asset is not something game code should have to reason about.\n */\n release(): void {\n if (this.#refCount === 0) {\n return;\n }\n this.#refCount -= 1;\n if (this.#refCount === 0) {\n this.#host.onZeroReferences(this);\n }\n }\n\n /**\n * Releases one holder at the end of a `using` block. Identical to\n * {@link AssetHandleImpl.release}, including the \"releasing a handle with no holders is a no-op\"\n * rule, so a handle that was released by hand inside the block does not go negative.\n */\n [Symbol.dispose](): void {\n this.release();\n }\n\n /**\n * Delivers a successful load: the state flips and the promise resolves, at the one point in the\n * frame §4 allows.\n *\n * @param value - What the loader produced.\n */\n settleLoaded(value: unknown): void {\n this.#state = \"loaded\";\n this.#value = value;\n this.#error = null;\n this.reportedFraction = 1;\n if (this.bytesTotal > 0) {\n this.bytesLoaded = this.bytesTotal;\n }\n this.interested = 0;\n this.retryRemaining = NO_TIMER;\n this.#resolve(value);\n }\n\n /**\n * Delivers a failed load.\n *\n * @param error - Why it failed.\n */\n settleFailed(error: AssetLoadError): void {\n this.#state = \"failed\";\n this.#error = error;\n this.interested = 0;\n this.retryRemaining = NO_TIMER;\n this.#reject(error);\n }\n\n /**\n * Delivers a hot-reload swap: the value is replaced in place and {@link AssetHandle.onReplaced}\n * fires. The promise keeps whatever it already settled with — it settles once, by contract.\n *\n * @param value - The new value.\n */\n settleReplaced(value: unknown): void {\n this.#state = \"loaded\";\n this.#value = value;\n this.#error = null;\n this.reportedFraction = 1;\n this.onReplaced.emit(value);\n }\n\n /** Marks the handle collected. Reading `value` afterwards throws `IGX-0501`. */\n markReleased(): void {\n this.#state = \"released\";\n this.#value = null;\n this.gcRemaining = NO_TIMER;\n this.detachTickets();\n this.progressListeners.length = 0;\n this.onReplaced.clear();\n }\n\n /** Aborts the fetches of the load in flight. Delivery still happens in `PreUpdate`. */\n abort(): void {\n this.controller?.abort();\n }\n\n /** Detaches every abort listener a request installed. */\n detachTickets(): void {\n const tickets = this.tickets;\n for (let index = 0; index < tickets.length; index += 1) {\n tickets[index]?.();\n }\n tickets.length = 0;\n }\n}\n\n/**\n * What {@link AssetHandleImpl} is constructed from.\n *\n * @internal\n */\nexport interface AssetHandleInit {\n /** The address as requested, fragment included. */\n readonly address: string;\n /** The fragment-free part of the address. */\n readonly path: string;\n /** The text after `#`, or `null`. */\n readonly fragment: string | null;\n /** The asset type. */\n readonly type: string;\n /** The cache key. */\n readonly key: string;\n /** The URL the path resolved to. */\n readonly url: string;\n /** The loader that produces the value. */\n readonly loader: AssetLoader;\n /** The service that owns the cache. */\n readonly host: AssetHandleHost;\n}\n\n/**\n * The no-op used as the initial value of the captured promise callbacks and as the silent rejection\n * handler.\n *\n * @param value - Ignored.\n */\nfunction passThrough(value: unknown): void {\n // Deliberately empty: the real callbacks replace it synchronously, and the rejection handler only\n // exists to keep an unobserved failure from becoming an unhandled rejection.\n void value;\n}\n","import type { AssetRef } from \"./types.js\";\n\n/**\n * The two helpers that build and recognise an {@link AssetRef}\n * (`docs/architecture/05-assets-and-loading.md` §2).\n *\n * A reference deliberately has no `.load()` sugar: §2 calls it \"the serializable form used in\n * schemas and files\", and a method would not survive `JSON.stringify`, the schema codec, or a\n * structured clone into a worker. The way to turn one into a handle is `app.assets.load(ref)`.\n */\n\n/**\n * Builds an asset reference.\n *\n * @typeParam T - The loaded value type the reference points at; a compile-time marker only.\n * @param address - The address, fragment included.\n * @param type - The asset type, when the extension does not identify it.\n * @returns A frozen reference, safe to hold as a module constant.\n *\n * @example\n * ```ts\n * const hero = assetRef<ModelAsset>(\"models/hero.glb\");\n * const run = assetRef<AnimationClip>(\"models/hero.glb#animation:Run\");\n * const handle = app.assets.load(hero);\n * ```\n *\n * @public\n */\nexport function assetRef<T = unknown>(address: string, type?: string): AssetRef<T> {\n return Object.freeze(type === undefined ? { address } : { address, type });\n}\n\n/**\n * Reports whether a value is an asset reference rather than a plain address.\n *\n * @param value - The candidate.\n * @returns `true` when the value is an object with a string `address`.\n *\n * @example\n * ```ts\n * const address = isAssetRef(input) ? input.address : input;\n * ```\n *\n * @public\n */\nexport function isAssetRef(value: unknown): value is AssetRef {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate: { address?: unknown } = value;\n return typeof candidate.address === \"string\";\n}\n\n/**\n * Reads the address out of whichever form a caller passed.\n *\n * @param ref - An address or a reference.\n * @returns The address.\n *\n * @internal\n */\nexport function addressOf(ref: AssetRef | string): string {\n return typeof ref === \"string\" ? ref : ref.address;\n}\n\n/**\n * Reads the declared type out of whichever form a caller passed.\n *\n * @param ref - An address or a reference.\n * @returns The type the reference declares, or `null` when it declares none.\n *\n * @internal\n */\nexport function declaredTypeOf(ref: AssetRef | string): string | null {\n return typeof ref === \"string\" ? null : (ref.type ?? null);\n}\n","import type { AssetHandleImpl } from \"./asset-handle.js\";\nimport type { FetchLike } from \"./types.js\";\n\n/**\n * The one place the asset service touches the network\n * (`docs/architecture/05-assets-and-loading.md` §5, §8).\n *\n * Decision the documents leave open: **`fetch` is the only I/O.** §8 says headless runs use \"fetch\n * for URLs and Node file reads for paths\", but a second code path would mean loaders behaving\n * differently per host, which §8's own last sentence forbids (\"so loaders do not branch on\n * platform\"). A Node app that needs files therefore passes a `fetch` that maps them onto `fs`\n * (Phase 9 ships one); tests pass a fake. Nothing here imports `node:fs`.\n *\n * Progress is bytes-weighted whenever a size is known — from the manifest entry, else from\n * `Content-Length` — and the body is read chunk by chunk so the counter moves during the download\n * rather than jumping at the end.\n */\n\n/** The header carrying the response size. */\nconst CONTENT_LENGTH = \"content-length\";\n\n/** The decoder used for {@link fetchAssetText}; created per call, which is not a per-frame path. */\nconst UTF8 = \"utf-8\";\n\n/**\n * Fetches an address as bytes, counting progress into the handle and honouring the abort signal.\n *\n * @param fetchImpl - The injected `fetch`.\n * @param url - The URL to read.\n * @param signal - Aborted when the request is cancelled or the app is disposed.\n * @param handle - The handle whose byte counters this read feeds.\n * @returns The whole body.\n * @throws Error when the response status is not in the 2xx range; the service wraps it in\n * `IGX-0505` with the original as `cause`.\n *\n * @internal\n */\nexport async function fetchAssetBytes(\n fetchImpl: FetchLike,\n url: string,\n signal: AbortSignal,\n handle: AssetHandleImpl,\n): Promise<ArrayBuffer> {\n const response = await fetchImpl(url, { signal });\n if (!response.ok) {\n throw new Error(`The request for ${url} failed with HTTP ${String(response.status)}.`);\n }\n readDeclaredSize(response, handle);\n const body = response.body;\n if (body === null) {\n const buffer = await response.arrayBuffer();\n handle.bytesLoaded = buffer.byteLength;\n if (handle.bytesTotal <= 0) {\n handle.bytesTotal = buffer.byteLength;\n }\n return buffer;\n }\n return readStream(body, handle);\n}\n\n/**\n * Fetches an address and decodes it as UTF-8 text.\n *\n * @param fetchImpl - The injected `fetch`.\n * @param url - The URL to read.\n * @param signal - The abort signal.\n * @param handle - The handle whose byte counters this read feeds.\n * @returns The decoded body.\n *\n * @internal\n */\nexport async function fetchAssetText(\n fetchImpl: FetchLike,\n url: string,\n signal: AbortSignal,\n handle: AssetHandleImpl,\n): Promise<string> {\n const bytes = await fetchAssetBytes(fetchImpl, url, signal, handle);\n return new TextDecoder(UTF8).decode(bytes);\n}\n\n/**\n * Fetches an address and parses it as JSON.\n *\n * @typeParam J - The parsed shape, as the loader declares it.\n * @param fetchImpl - The injected `fetch`.\n * @param url - The URL to read.\n * @param signal - The abort signal.\n * @param handle - The handle whose byte counters this read feeds.\n * @returns The parsed body.\n *\n * @internal\n */\nexport async function fetchAssetJson<J = unknown>(\n fetchImpl: FetchLike,\n url: string,\n signal: AbortSignal,\n handle: AssetHandleImpl,\n): Promise<J> {\n const text = await fetchAssetText(fetchImpl, url, signal, handle);\n // Boundary assertion (coding standards §5.2): `JSON.parse` returns `any`, and `J` is the loader's\n // own declaration of what the file holds. Loaders that need certainty validate with a schema.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return JSON.parse(text) as J;\n}\n\n/**\n * Records the response's declared size, unless the manifest already supplied a better one.\n *\n * @param response - The response whose headers to read.\n * @param handle - The handle to record the total on.\n */\nfunction readDeclaredSize(response: Response, handle: AssetHandleImpl): void {\n if (handle.bytesTotal > 0) {\n return;\n }\n const header = response.headers.get(CONTENT_LENGTH);\n if (header === null) {\n return;\n }\n const declared = Math.trunc(Number(header));\n if (Number.isFinite(declared) && declared > 0) {\n handle.bytesTotal = declared;\n }\n}\n\n/**\n * Drains a response body chunk by chunk so progress moves during the download.\n *\n * @param body - The response stream.\n * @param handle - The handle whose byte counters to advance.\n * @returns The concatenated body.\n */\nasync function readStream(body: ReadableStream<Uint8Array>, handle: AssetHandleImpl): Promise<ArrayBuffer> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let received = 0;\n for (;;) {\n // Sequential by nature: each chunk has to arrive before the next can be asked for.\n // oxlint-disable-next-line no-await-in-loop\n const result = await reader.read();\n if (result.done) {\n break;\n }\n const chunk = result.value;\n chunks.push(chunk);\n received += chunk.byteLength;\n handle.bytesLoaded = received;\n }\n if (handle.bytesTotal <= 0) {\n handle.bytesTotal = received;\n }\n const out = new Uint8Array(received);\n let offset = 0;\n for (let index = 0; index < chunks.length; index += 1) {\n const chunk = chunks[index];\n if (chunk === undefined) {\n continue;\n }\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out.buffer;\n}\n","import { clamp01 } from \"../math/math-utils.js\";\nimport type { AssetHandleImpl } from \"./asset-handle.js\";\nimport type { AssetHandle, AssetRef, LoadOptions, LoaderContext } from \"./types.js\";\nimport type { App } from \"../app/types.js\";\nimport type { LiteEngine } from \"../lite/scene.js\";\nimport type { JsonObject } from \"../schema/json.js\";\n\n/**\n * The object a loader is handed (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * It owns no policy: every method delegates to the service, which is what keeps the priority queue,\n * the byte counters, the retry logic, and the dependency reference counting in one place. The\n * context exists so a loader never needs a reference to the service itself.\n */\n\n/**\n * What a {@link LoaderContextImpl} needs from the service that created it.\n *\n * @internal\n */\nexport interface LoaderContextHost {\n /** The app the load belongs to. */\n readonly app: App;\n /** The Lite engine the GPU loaders upload through; the null engine in headless mode. */\n readonly engine: LiteEngine;\n /**\n * The `.meta.json` sidecar the manifest recorded for an address.\n *\n * @param path - The fragment-free address.\n * @returns The sidecar, or `null` when the manifest lists none.\n */\n manifestMeta(path: string): JsonObject | null;\n /**\n * Reads an address as bytes through the priority queue.\n *\n * @param handle - The handle whose byte counters the read feeds.\n * @param priority - The request priority.\n * @param signal - The abort signal.\n * @returns The body.\n */\n fetchBytes(handle: AssetHandleImpl, priority: number, signal: AbortSignal): Promise<ArrayBuffer>;\n /**\n * Reads an address as UTF-8 text through the priority queue.\n *\n * @param handle - The handle whose byte counters the read feeds.\n * @param priority - The request priority.\n * @param signal - The abort signal.\n * @returns The decoded body.\n */\n fetchText(handle: AssetHandleImpl, priority: number, signal: AbortSignal): Promise<string>;\n /**\n * Reads an address as JSON through the priority queue.\n *\n * @typeParam J - The parsed shape.\n * @param handle - The handle whose byte counters the read feeds.\n * @param priority - The request priority.\n * @param signal - The abort signal.\n * @returns The parsed body.\n */\n fetchJson<J>(handle: AssetHandleImpl, priority: number, signal: AbortSignal): Promise<J>;\n /**\n * Requests a dependency of a load: it is retained on the parent's behalf and its progress counts\n * into the parent's.\n *\n * @param ref - The dependency's address or reference.\n * @param options - Priority, type, progress, and cancellation.\n * @param parent - The handle that depends on it.\n * @returns The dependency's handle.\n */\n requestDependency(ref: AssetRef | string, options: LoadOptions | undefined, parent: AssetHandleImpl): AssetHandleImpl;\n}\n\n/**\n * One load's context.\n *\n * @internal\n */\nexport class LoaderContextImpl implements LoaderContext {\n /** The address being loaded, fragment included. */\n readonly address: string;\n\n /** The URL the address resolved to. */\n readonly url: string;\n\n /** The text after `#`, or `null`. */\n readonly fragment: string | null;\n\n /** The asset type the loader is registered under. */\n readonly type: string;\n\n /** Aborted when the request is cancelled or the app is disposed. */\n readonly signal: AbortSignal;\n\n /** The `.meta.json` sidecar the build recorded for this address, or `null`. */\n readonly meta: JsonObject | null;\n\n readonly #host: LoaderContextHost;\n\n readonly #handle: AssetHandleImpl;\n\n readonly #priority: number;\n\n /**\n * Creates a context for one load.\n *\n * @param host - The service behind every method.\n * @param handle - The handle being loaded.\n * @param signal - The abort signal for this attempt.\n * @param priority - The request priority the fetches inherit.\n */\n constructor(host: LoaderContextHost, handle: AssetHandleImpl, signal: AbortSignal, priority: number) {\n this.#host = host;\n this.#handle = handle;\n this.#priority = priority;\n this.address = handle.address;\n this.url = handle.url;\n this.fragment = handle.fragment;\n this.type = handle.type;\n this.signal = signal;\n this.meta = host.manifestMeta(handle.path);\n }\n\n /**\n * The app the load belongs to.\n *\n * @returns The app.\n */\n get app(): App {\n return this.#host.app;\n }\n\n /**\n * The unstable Babylon Lite escape hatch GPU loaders upload through.\n *\n * @returns The engine handle.\n */\n get lite(): { readonly engine: LiteEngine } {\n return { engine: this.#host.engine };\n }\n\n /**\n * Fetches the address as bytes.\n *\n * @returns The body.\n */\n fetchBytes(): Promise<ArrayBuffer> {\n return this.#host.fetchBytes(this.#handle, this.#priority, this.signal);\n }\n\n /**\n * Fetches the address as UTF-8 text.\n *\n * @returns The decoded body.\n */\n fetchText(): Promise<string> {\n return this.#host.fetchText(this.#handle, this.#priority, this.signal);\n }\n\n /**\n * Fetches the address and parses it as JSON.\n *\n * @typeParam J - The parsed shape, as the loader declares it.\n * @returns The parsed body.\n */\n fetchJson<J = unknown>(): Promise<J> {\n return this.#host.fetchJson<J>(this.#handle, this.#priority, this.signal);\n }\n\n /**\n * Loads another asset as a dependency of this one.\n *\n * @typeParam D - The dependency's loaded value type.\n * @param ref - The dependency's address or reference.\n * @param options - Priority, type, progress, and cancellation.\n * @returns The dependency's handle, once it has been delivered.\n */\n async loadDependency<D>(ref: AssetRef<D> | string, options?: LoadOptions): Promise<AssetHandle<D>> {\n const dependency = this.#host.requestDependency(ref, options, this.#handle);\n await dependency.promise;\n // Boundary assertion (coding standards §5.2): the cache is untyped because loaders return\n // `unknown`; `D` is the caller's declaration of what this address holds.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return dependency as unknown as AssetHandle<D>;\n }\n\n /**\n * Reports progress for loaders that cannot express it in bytes. Ignored once bytes are known,\n * because a byte count is the better signal.\n *\n * @param fraction - How far along the load is, in `[0, 1]`.\n */\n reportProgress(fraction: number): void {\n this.#handle.reportedFraction = clamp01(fraction);\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { AssetManifest, AssetManifestEntry } from \"./types.js\";\n\n/**\n * The manifest (`docs/architecture/05-assets-and-loading.md` §7): the address-to-URL table\n * `@ignifx/vite-plugin` generates, plus the index the service reads it through.\n *\n * The default is an empty manifest rooted at `assets`, which is what makes a project with no build\n * step work: every address resolves to `assets/<address>` and nothing knows its byte size, so\n * progress falls back to whatever the loader reports.\n */\n\n/**\n * The manifest format discriminator, written into `assets.manifest.json`.\n *\n * @public\n */\nexport const ASSET_MANIFEST_FORMAT = \"ignifx.manifest\";\n\n/**\n * The only manifest format version this build reads.\n *\n * @public\n */\nexport const ASSET_MANIFEST_VERSION = 1;\n\n/**\n * The asset root a project gets when it configures none (§2).\n *\n * @public\n */\nexport const DEFAULT_ASSET_ROOT = \"assets\";\n\n/** No entries, rooted at `assets`. */\nconst EMPTY_ENTRIES: readonly AssetManifestEntry[] = Object.freeze([]);\n\n/** Shared empty result so an unknown group allocates nothing. */\nconst EMPTY_GROUP: readonly string[] = Object.freeze([]);\n\n/**\n * The manifest an app uses until a build supplies one.\n *\n * @public\n */\nexport const EMPTY_ASSET_MANIFEST: AssetManifest = Object.freeze({\n format: ASSET_MANIFEST_FORMAT,\n formatVersion: ASSET_MANIFEST_VERSION,\n root: DEFAULT_ASSET_ROOT,\n entries: EMPTY_ENTRIES,\n});\n\n/**\n * Builds a manifest from a list of entries — what a test, a tool, or a hand-written config uses in\n * place of the generated file.\n *\n * @param entries - The addressed files.\n * @param root - The asset root relative addresses resolve against. Defaults to `\"assets\"`.\n * @returns The manifest.\n *\n * @example\n * ```ts\n * const manifest = createAssetManifest([{ address: \"data/x.json\", url: \"assets/data/x.abc123.json\" }]);\n * const app = await createApp({ headless: true, assets: { manifest } });\n * ```\n *\n * @public\n */\nexport function createAssetManifest(\n entries: readonly AssetManifestEntry[],\n root: string = DEFAULT_ASSET_ROOT,\n): AssetManifest {\n return Object.freeze({\n format: ASSET_MANIFEST_FORMAT,\n formatVersion: ASSET_MANIFEST_VERSION,\n root,\n entries: Object.freeze(entries.slice()),\n });\n}\n\n/**\n * Checks a manifest's discriminator and version.\n *\n * @param manifest - The manifest a project or a build supplied.\n * @returns The same manifest, so the check reads inline.\n * @throws IgnifxError with code `IGX-0603` when the format version is not\n * {@link ASSET_MANIFEST_VERSION}.\n *\n * @internal\n */\nexport function assertSupportedManifest(manifest: AssetManifest): AssetManifest {\n // The declared type pins `formatVersion` to the one version this build reads, but a manifest is\n // JSON that arrived from a build tool: the value has to be re-checked at the boundary, so it is\n // widened to `number` before the comparison (coding standards §5.2).\n const version: number = manifest.formatVersion;\n if (version !== ASSET_MANIFEST_VERSION) {\n throw new IgnifxError(\n CoreErrorCode.unsupportedFormatVersion,\n `The asset manifest declares format version ${String(version)}, which this build cannot read.`,\n {\n context: { file: \"assets.manifest.json\", version: String(version) },\n hint: `This build reads version ${String(ASSET_MANIFEST_VERSION)}; regenerate the manifest with a matching @ignifx/vite-plugin.`,\n },\n );\n }\n return manifest;\n}\n\n/**\n * The manifest indexed for lookup: address to entry, and group label to addresses.\n *\n * @internal\n */\nexport class ManifestIndex {\n /** The manifest this index was built from. */\n readonly manifest: AssetManifest;\n\n readonly #byAddress = new Map<string, AssetManifestEntry>();\n\n readonly #byGroup = new Map<string, string[]>();\n\n /**\n * Indexes a manifest.\n *\n * @param manifest - The table to index. A later entry for the same address replaces an earlier\n * one, which is what makes a hand-written override list work.\n */\n constructor(manifest: AssetManifest) {\n this.manifest = manifest;\n const entries = manifest.entries;\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry === undefined) {\n continue;\n }\n this.#byAddress.set(entry.address, entry);\n const groups = entry.groups;\n if (groups === undefined) {\n continue;\n }\n for (let at = 0; at < groups.length; at += 1) {\n const group = groups[at];\n if (group === undefined) {\n continue;\n }\n const members = this.#byGroup.get(group);\n if (members === undefined) {\n this.#byGroup.set(group, [entry.address]);\n } else {\n members.push(entry.address);\n }\n }\n }\n }\n\n /**\n * Looks an address up.\n *\n * @param address - A fragment-free address.\n * @returns The entry, or `null` when the manifest does not list it.\n */\n entry(address: string): AssetManifestEntry | null {\n return this.#byAddress.get(address) ?? null;\n }\n\n /**\n * Lists the addresses carrying a group label.\n *\n * @param group - The label, such as `\"boot\"`.\n * @returns The addresses in manifest order; empty when no entry carries the label.\n */\n group(group: string): readonly string[] {\n return this.#byGroup.get(group) ?? EMPTY_GROUP;\n }\n}\n","/**\n * The priority queue in front of the network\n * (`docs/architecture/05-assets-and-loading.md` §4: \"Requests are scheduled through a priority\n * queue with a concurrency limit (default 6 concurrent fetches)\").\n *\n * Decision the documents leave open: **the limit gates fetches, not whole loader runs.** §4 counts\n * \"concurrent fetches\", and gating loader runs instead would deadlock the moment a loader used\n * `loadDependency`: the parent would hold a slot while waiting for a child that cannot get one.\n * With the limit on `ctx.fetchBytes`/`fetchText`/`fetchJson`, a loader waiting on a dependency\n * holds nothing, and the number of sockets in flight is still exactly what §4 promises.\n *\n * Ordering: higher `priority` first, and first-come first-served within one priority.\n */\n\n/** One request waiting for a slot. */\ninterface QueuedTask {\n /** Higher runs first. */\n readonly priority: number;\n /** Enqueue serial; the tie-breaker that makes one priority band first-come first-served. */\n readonly serial: number;\n /** Takes a slot and runs the task. */\n start(): void;\n /**\n * Fails the task without ever running it.\n *\n * @param reason - What to reject the caller's promise with.\n */\n reject(reason: unknown): void;\n}\n\n/**\n * The concurrency limit an unconfigured queue uses (§4).\n *\n * @public\n */\nexport const DEFAULT_ASSET_CONCURRENCY = 6;\n\n/**\n * A bounded, priority-ordered runner for asynchronous work.\n *\n * @internal\n */\nexport class RequestQueue {\n /** How many tasks may run at once. Changing it takes effect at the next completion. */\n concurrency: number;\n\n readonly #pending: QueuedTask[] = [];\n\n #active = 0;\n\n #serial = 0;\n\n /**\n * Creates a queue.\n *\n * @param concurrency - How many tasks may run at once. Defaults to\n * {@link DEFAULT_ASSET_CONCURRENCY}.\n */\n constructor(concurrency: number = DEFAULT_ASSET_CONCURRENCY) {\n this.concurrency = concurrency;\n }\n\n /**\n * How many tasks are waiting for a slot.\n *\n * @returns The pending count, which diagnostics reports as `queued`.\n */\n get pendingCount(): number {\n return this.#pending.length;\n }\n\n /**\n * How many tasks are running.\n *\n * @returns The active count, which diagnostics reports as `inFlight`.\n */\n get activeCount(): number {\n return this.#active;\n }\n\n /**\n * Schedules work and returns its result.\n *\n * @typeParam T - What the task produces.\n * @param priority - Higher runs first; ties break in enqueue order.\n * @param task - The work. It is not started until a slot is free.\n * @returns What the task produced.\n */\n run<T>(priority: number, task: () => Promise<T>): Promise<T> {\n this.#serial += 1;\n const serial = this.#serial;\n return new Promise<T>((resolve, reject) => {\n this.#pending.push({\n priority,\n serial,\n start: (): void => {\n this.#active += 1;\n // Bookkeeping, not control flow: the caller's promise is what carries the outcome\n // (coding standards §8).\n void task().then(\n (value: T): void => {\n this.#finish();\n resolve(value);\n },\n (error: unknown): void => {\n this.#finish();\n reject(error);\n },\n );\n },\n reject,\n });\n this.#pump();\n });\n }\n\n /**\n * Fails every task that has not started yet — what disposal does so no loader waits forever.\n *\n * @param reason - What to reject the waiting callers with.\n */\n clear(reason: unknown): void {\n const pending = this.#pending.slice();\n this.#pending.length = 0;\n for (let index = 0; index < pending.length; index += 1) {\n pending[index]?.reject(reason);\n }\n }\n\n /** Frees a slot and starts whatever was waiting for it. */\n #finish(): void {\n this.#active -= 1;\n this.#pump();\n }\n\n /** Starts waiting tasks while there are slots for them. */\n #pump(): void {\n while (this.#active < this.concurrency) {\n const index = this.#bestIndex();\n if (index < 0) {\n return;\n }\n const task = this.#pending[index];\n this.#pending.splice(index, 1);\n // `start` takes the slot synchronously, so the loop always terminates.\n task?.start();\n }\n }\n\n /**\n * Finds the task that should run next.\n *\n * @returns Its index, or `-1` when nothing is waiting.\n */\n #bestIndex(): number {\n const pending = this.#pending;\n let best = -1;\n let bestPriority = 0;\n let bestSerial = 0;\n for (let index = 0; index < pending.length; index += 1) {\n const task = pending[index];\n if (task === undefined) {\n continue;\n }\n if (best < 0 || task.priority > bestPriority || (task.priority === bestPriority && task.serial < bestSerial)) {\n best = index;\n bestPriority = task.priority;\n bestSerial = task.serial;\n }\n }\n return best;\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport { Signal } from \"../signal/signal.js\";\nimport {\n isAbsoluteAddress,\n joinRoot,\n matchExtension,\n MEMORY_ADDRESS_PREFIX,\n normalizeExtension,\n splitFragment,\n} from \"./address.js\";\nimport { AssetHandleImpl, NO_TIMER } from \"./asset-handle.js\";\nimport { addressOf, declaredTypeOf } from \"./asset-ref.js\";\nimport { fetchAssetBytes, fetchAssetJson, fetchAssetText } from \"./fetcher.js\";\nimport { LoaderContextImpl } from \"./loader-context.js\";\nimport { assertSupportedManifest, EMPTY_ASSET_MANIFEST, ManifestIndex } from \"./manifest.js\";\nimport { RequestQueue } from \"./request-queue.js\";\nimport { AssetLoadError } from \"./types.js\";\nimport type { AssetHandleHost } from \"./asset-handle.js\";\nimport type { LoaderContextHost } from \"./loader-context.js\";\nimport type {\n AssetHandle,\n AssetLoader,\n AssetManifest,\n AssetProgress,\n AssetRef,\n AssetTypeDefinition,\n Assets,\n AssetsSettings,\n BatchHandle,\n FetchLike,\n LoadOptions,\n RegisterAssetOptions,\n} from \"./types.js\";\nimport type { App } from \"../app/types.js\";\nimport type { DiagnosticsGroup } from \"../diagnostics/diagnostics-group.js\";\nimport type { Diagnostics } from \"../diagnostics/diagnostics.js\";\nimport type { LiteEngine } from \"../lite/scene.js\";\nimport type { JsonObject } from \"../schema/json.js\";\n\n/**\n * `app.assets` (`docs/architecture/05-assets-and-loading.md` §3–§5, §9): one cache, one loader per\n * type, reference-counted handles, a priority queue in front of the network, and a single delivery\n * point in `PreUpdate` (`01-lifecycle-and-time.md` §3 step 2).\n *\n * Decisions the documents leave open:\n *\n * - **Delivery is the only place state changes.** §4 says completed loads are delivered in\n * `PreUpdate` \"never mid-phase\". So a loader that resolves during a `fetch` continuation does not\n * flip `state` or settle `promise`: it pushes onto a queue that `AssetDeliverySystem` drains. The\n * same queue carries failures and hot-reload swaps, so all three are observable at one point.\n * - **`progress` is live, `onProgress` is delivered.** The delivery rule exists so that two scripts\n * in one frame never disagree about whether an asset is *ready*. A progress bar has no such\n * requirement, so the getter reads the byte counters directly and only the callbacks are batched.\n * - **Aborting one request of several does not cancel the shared load.** An `options.signal` abort\n * drops that request's hold; the fetch is aborted only when no request is interested any more.\n * The aborting caller shares the handle, so a load two scripts asked for still resolves for both\n * when one of them cancels. An aborted request has already released its own hold — do not release\n * it again.\n * - **Releasing to zero while a load is in flight does not abort it.** §3 pairs `release` with the\n * collector, not with cancellation; the load finishes and the asset becomes a collector candidate.\n * Cancellation is what an `AbortSignal` is for.\n * - **A failed handle stays cached until it is collected.** Retrying immediately would turn a\n * permanent 404 into a loop; once the last holder releases it the entry is dropped and the next\n * `load` starts fresh. `reload(address)` forces an attempt in development.\n * - **Retry backoff counts unscaled time.** §9 asks for exponential backoff without naming a clock.\n * The collector uses `time.deltaTime` (§3 calls it a cache lifetime, which is game time), but a\n * network retry must not stop because the game paused or set `timeScale` to zero, so it counts\n * `time.unscaledDeltaTime`. Neither reads a wall clock: tests drive both with `app.step`.\n * - **Hot reload loads before it unloads.** §5 says the default reload is \"unload + load\"; doing it\n * in that order would destroy a working value when the new one fails to parse, and the brief for\n * this module requires that \"failures leave the old value\". The previous value is released only\n * once the replacement exists.\n */\n\n/**\n * The first retry waits this many seconds; each further attempt doubles it (§9).\n *\n * @internal\n */\nexport const ASSET_RETRY_BASE_SECONDS = 0.1;\n\n/**\n * The diagnostics group name (`docs/architecture/15-devtools-and-diagnostics.md` §3).\n *\n * @public\n */\nexport const ASSET_DIAGNOSTICS_GROUP = \"assets\";\n\n/**\n * The counters the `assets` diagnostics group publishes, in index order.\n *\n * @public\n */\nexport const ASSET_DIAGNOSTICS_COUNTERS: readonly string[] = Object.freeze([\n \"loaded\",\n \"inFlight\",\n \"queued\",\n \"bytesLoaded\",\n \"failed\",\n \"zeroRefCandidates\",\n]);\n\n/** Separates the type from the address in a cache key. A type name never contains it. */\nconst KEY_SEPARATOR = \"::\";\n/** Wall-clock unit for the idle retry timer. */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/** What the delivery queue carries from a settled load to the next `PreUpdate`. */\ntype DeliveryItem =\n | { readonly kind: \"loaded\"; readonly handle: AssetHandleImpl; readonly value: unknown }\n | { readonly kind: \"failed\"; readonly handle: AssetHandleImpl; readonly error: AssetLoadError }\n | { readonly kind: \"replaced\"; readonly handle: AssetHandleImpl; readonly value: unknown };\n\n/**\n * What {@link AssetsImpl} is constructed with.\n *\n * @internal\n */\nexport interface AssetsOptions {\n /** The app the service belongs to. */\n readonly app: App;\n /** Where the `assets` counter group is registered. */\n readonly diagnostics: Diagnostics;\n /** The `fetch` every read goes through. Defaults to `globalThis.fetch`. */\n readonly fetch?: FetchLike;\n /** The address-to-URL table. Defaults to {@link EMPTY_ASSET_MANIFEST}. */\n readonly manifest?: AssetManifest;\n}\n\n/**\n * A group of loads requested together.\n *\n * @internal\n */\nclass BatchHandleImpl implements BatchHandle {\n /** The handles the batch retains. */\n readonly handles: readonly AssetHandle[];\n\n /** Settles once every member has settled. */\n readonly promise: Promise<void>;\n\n readonly #members: readonly AssetHandleImpl[];\n\n readonly #controller: AbortController;\n\n #isReleased = false;\n\n /**\n * Creates a batch.\n *\n * @param members - The handles, each already retained once on the batch's behalf.\n * @param controller - The controller {@link BatchHandleImpl.cancel} aborts.\n */\n constructor(members: readonly AssetHandleImpl[], controller: AbortController) {\n this.#members = members;\n this.#controller = controller;\n this.handles = members;\n const promises: Promise<unknown>[] = [];\n for (const member of members) {\n promises.push(member.promise);\n }\n this.promise = Promise.all(promises).then(toVoid);\n // Same reasoning as `AssetHandleImpl`: a batch nobody awaited must not raise an unhandled\n // rejection (coding standards §8).\n void this.promise.catch(ignoreRejection);\n }\n\n /**\n * The mean progress of the batch's members.\n *\n * @returns A fraction in `[0, 1]`; `1` for an empty batch, which has nothing left to do.\n */\n get progress(): number {\n const members = this.#members;\n if (members.length === 0) {\n return 1;\n }\n let sum = 0;\n for (const member of members) {\n sum += member.progress;\n }\n return sum / members.length;\n }\n\n /** Releases every handle the batch retains. Calling it twice is a no-op. */\n release(): void {\n if (this.#isReleased) {\n return;\n }\n this.#isReleased = true;\n for (const member of this.#members) {\n member.release();\n }\n }\n\n /**\n * Aborts every load the batch started. The abort tickets release the batch's holds, so this does\n * not also call {@link BatchHandleImpl.release}.\n */\n cancel(): void {\n if (this.#isReleased) {\n return;\n }\n this.#isReleased = true;\n this.#controller.abort();\n }\n}\n\n/**\n * The asset service of one app.\n *\n * @internal\n */\nexport class AssetsImpl implements Assets, AssetHandleHost, LoaderContextHost {\n /** Emitted at delivery whenever the aggregate progress of the loads in flight changed. */\n readonly onProgress: Signal<AssetProgress>;\n\n /** How many seconds a zero-reference asset stays cached. */\n gcDelay = 5;\n\n readonly #app: App;\n\n readonly #fetch: FetchLike;\n\n readonly #queue = new RequestQueue();\n\n readonly #loaders = new Map<string, AssetLoader>();\n\n readonly #typeByExtension = new Map<string, string>();\n\n readonly #entries = new Map<string, AssetHandleImpl>();\n\n readonly #byAddress = new Map<string, AssetHandleImpl>();\n\n readonly #delivery: DeliveryItem[] = [];\n\n readonly #retrying: AssetHandleImpl[] = [];\n\n readonly #collecting: AssetHandleImpl[] = [];\n\n readonly #watching: AssetHandleImpl[] = [];\n\n readonly #session: AssetHandleImpl[] = [];\n\n readonly #counters: DiagnosticsGroup;\n\n readonly #countersLoaded: number;\n\n readonly #countersInFlight: number;\n\n readonly #countersQueued: number;\n\n readonly #countersBytes: number;\n\n readonly #countersFailed: number;\n\n readonly #countersCandidates: number;\n\n #index: ManifestIndex;\n\n #root: string;\n\n #hasExplicitManifest: boolean;\n\n #engine: LiteEngine | null = null;\n\n #retries = 2;\n\n #preload: readonly string[] = [];\n\n #memorySerial = 0;\n\n #sessionSettled = 0;\n\n #loadedCount = 0;\n\n #failedCount = 0;\n\n #inFlightCount = 0;\n\n #bytesLoadedTotal = 0;\n\n #lastLoaded = -1;\n\n #lastTotal = -1;\n\n #lastBytesLoaded = -1;\n\n #lastBytesTotal = -1;\n\n #isDisposed = false;\n\n /**\n * Creates the asset service of one app.\n *\n * @param options - The app, the diagnostics table, the injected `fetch`, and the manifest.\n * @throws IgnifxError with code `IGX-0603` when the manifest declares an unreadable format\n * version.\n */\n constructor(options: AssetsOptions) {\n this.#app = options.app;\n this.#fetch = options.fetch ?? defaultFetch();\n const manifest = options.manifest;\n this.#hasExplicitManifest = manifest !== undefined;\n this.#index = new ManifestIndex(manifest === undefined ? EMPTY_ASSET_MANIFEST : assertSupportedManifest(manifest));\n this.#root = this.#index.manifest.root;\n this.onProgress = new Signal<AssetProgress>();\n const counters = options.diagnostics.registerGroup(ASSET_DIAGNOSTICS_GROUP, ASSET_DIAGNOSTICS_COUNTERS);\n this.#counters = counters;\n this.#countersLoaded = counters.index(\"loaded\");\n this.#countersInFlight = counters.index(\"inFlight\");\n this.#countersQueued = counters.index(\"queued\");\n this.#countersBytes = counters.index(\"bytesLoaded\");\n this.#countersFailed = counters.index(\"failed\");\n this.#countersCandidates = counters.index(\"zeroRefCandidates\");\n }\n\n /**\n * The address-to-URL table.\n *\n * @returns The manifest the service resolves addresses through.\n */\n get manifest(): AssetManifest {\n return this.#index.manifest;\n }\n\n /**\n * The app the service belongs to.\n *\n * @returns The app.\n */\n get app(): App {\n return this.#app;\n }\n\n /**\n * The Lite engine GPU loaders upload through.\n *\n * @returns The engine handle.\n * @throws IgnifxError with code `IGX-0107` before `createApp()` has attached one.\n */\n get engine(): LiteEngine {\n const engine = this.#engine;\n if (engine === null) {\n throw new IgnifxError(CoreErrorCode.appNotReady, \"ctx.lite.engine is not available until createApp() resolves.\", {\n context: { member: \"ctx.lite.engine\" },\n });\n }\n return engine;\n }\n\n /**\n * The `.meta.json` sidecar the manifest recorded for an address.\n *\n * @param path - The fragment-free address.\n * @returns The sidecar, or `null` when the manifest lists none.\n */\n manifestMeta(path: string): JsonObject | null {\n return this.#index.entry(path)?.meta ?? null;\n }\n\n /**\n * The manifest group labels the `assets` settings section asked to preload.\n *\n * @returns The labels, in configuration order.\n */\n get preloadGroups(): readonly string[] {\n return this.#preload;\n }\n\n /**\n * Requests an asset and returns its shared handle immediately.\n *\n * @typeParam T - The loaded value type.\n * @param ref - The address, or a reference carrying one.\n * @param options - Priority, type, progress, and cancellation.\n * @returns The handle, with one more holder.\n * @throws IgnifxError with code `IGX-0504` when no loader claims the address.\n */\n load<T>(ref: AssetRef<T> | string, options?: LoadOptions): AssetHandle<T> {\n return toTyped<T>(this.#request(ref, options, null));\n }\n\n /**\n * Requests an asset and waits for the delivery point its state flips at.\n *\n * @typeParam T - The loaded value type.\n * @param ref - The address, or a reference carrying one.\n * @param options - Priority, type, progress, and cancellation.\n * @returns The handle, once it has loaded.\n */\n async loadAsync<T>(ref: AssetRef<T> | string, options?: LoadOptions): Promise<AssetHandle<T>> {\n const handle = this.#request(ref, options, null);\n await handle.promise;\n return toTyped<T>(handle);\n }\n\n /**\n * Requests several assets as one batch.\n *\n * @param refs - The addresses or references.\n * @param options - Priority, type, progress, and cancellation, applied to every member.\n * @returns The batch.\n */\n loadAll(refs: readonly (AssetRef | string)[], options?: LoadOptions): BatchHandle {\n return this.#batch(refs, options);\n }\n\n /**\n * Loads every manifest entry carrying a group label.\n *\n * @param group - The label, such as `\"boot\"`.\n * @param options - Priority, progress, and cancellation.\n * @returns The batch; empty when the manifest knows no such group.\n */\n preloadGroup(group: string, options?: LoadOptions): BatchHandle {\n return this.#batch(this.#index.group(group), options);\n }\n\n /**\n * Looks a cached handle up without changing its reference count.\n *\n * @typeParam T - The loaded value type.\n * @param address - The address, fragment included.\n * @returns The handle, or `null` when the address is not cached.\n */\n get<T>(address: string): AssetHandle<T> | null {\n const handle = this.#byAddress.get(address);\n return handle === undefined ? null : toTyped<T>(handle);\n }\n\n /**\n * Removes one holder from a handle, by object or by address.\n *\n * @param handleOrAddress - The handle, or the address it was requested under.\n */\n release(handleOrAddress: AssetHandle | string): void {\n if (typeof handleOrAddress === \"string\") {\n this.#byAddress.get(handleOrAddress)?.release();\n return;\n }\n handleOrAddress.release();\n }\n\n /** Unloads every zero-reference asset that has finished loading, now. */\n gc(): void {\n // Every entry of the candidate list is at zero references with a running countdown: `retain`\n // calls `onRetained`, which takes it back out again. So the only question left here is whether\n // the load has settled — an asset still in flight has nothing to unload yet.\n const candidates = this.#collecting.slice();\n this.#collecting.length = 0;\n for (const handle of candidates) {\n if (handle.state === \"loading\") {\n this.#collecting.push(handle);\n continue;\n }\n this.#unload(handle);\n }\n }\n\n /**\n * Resolves an address to the URL the service fetches.\n *\n * @param address - The address; the fragment is stripped.\n * @returns The manifest's URL for the address, or `<root>/<address>`.\n */\n resolveUrl(address: string): string {\n const path = splitFragment(address).path;\n if (isAbsoluteAddress(path)) {\n return path;\n }\n const entry = this.#index.entry(path);\n return entry === null ? joinRoot(this.#root, path) : entry.url;\n }\n\n /**\n * Registers a loader and the extensions that select it.\n *\n * @param loader - The loader.\n * @throws IgnifxError with code `IGX-0506` when the type is already registered.\n */\n registerLoader(loader: AssetLoader): void {\n if (this.#loaders.has(loader.type)) {\n throw new IgnifxError(\n CoreErrorCode.duplicateAssetLoader,\n `A loader for the asset type ${loader.type} is already registered.`,\n {\n context: { type: loader.type },\n hint: \"One loader owns one type; give the new loader its own type name.\",\n },\n );\n }\n this.#loaders.set(loader.type, loader);\n this.#mapExtensions(loader.type, loader.extensions);\n }\n\n /**\n * Declares an asset type that has no loader yet, so addresses resolve to a type before the\n * extension that reads them is registered.\n *\n * @param type - The type name and the extensions that select it.\n */\n registerType(type: AssetTypeDefinition): void {\n this.#mapExtensions(type.type, type.extensions);\n }\n\n /**\n * Publishes a value built in code as an asset (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * @remarks\n * The entry is a normal cache entry from the moment it exists: it is shared by address, it is\n * reference counted, and the collector unloads it — running the registered type's `unload` — once\n * the last holder lets go. What it never does is fetch, because a `memory:` address names no\n * file. Registering twice at the same explicit address replaces the first entry, which is\n * released immediately rather than after `gcDelay`: the caller has just said the old value is\n * gone.\n *\n * @typeParam T - The value type.\n * @param value - The already-built value.\n * @param options - The asset type, and an explicit address instead of the generated one.\n * @returns The handle, already `loaded`, with one holder.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed.\n */\n register<T>(value: T, options: RegisterAssetOptions): AssetHandle<T> {\n if (this.#isDisposed) {\n throw new IgnifxError(\n CoreErrorCode.appDisposed,\n \"The app has been disposed; app.assets is no longer available.\",\n { context: { member: \"app.assets.register()\" } },\n );\n }\n const type = options.type;\n this.#memorySerial += 1;\n const address = options.address ?? `${MEMORY_ADDRESS_PREFIX}${type}/${String(this.#memorySerial)}`;\n const key = `${type}${KEY_SEPARATOR}${address}`;\n const existing = this.#entries.get(key);\n if (existing !== undefined) {\n this.#unload(existing);\n removeFrom(this.#collecting, existing);\n }\n const handle = new AssetHandleImpl({\n address,\n path: address,\n fragment: null,\n type,\n key,\n url: address,\n loader: this.#loaders.get(type) ?? memoryLoader(type),\n host: this,\n });\n this.#entries.set(key, handle);\n if (!this.#byAddress.has(address)) {\n this.#byAddress.set(address, handle);\n }\n handle.settleLoaded(value);\n this.#loadedCount += 1;\n handle.retain();\n return toTyped<T>(handle);\n }\n\n /**\n * Reports that a handle lost its last holder.\n *\n * @param handle - The handle now at zero references.\n */\n onZeroReferences(handle: AssetHandleImpl): void {\n if (handle.gcRemaining !== NO_TIMER || handle.state === \"released\") {\n return;\n }\n handle.gcRemaining = this.gcDelay;\n this.#collecting.push(handle);\n }\n\n /**\n * Reports that a handle gained a holder, calling off a pending collection.\n *\n * @param handle - The handle that was retained.\n */\n onRetained(handle: AssetHandleImpl): void {\n if (handle.gcRemaining === NO_TIMER) {\n return;\n }\n handle.gcRemaining = NO_TIMER;\n removeFrom(this.#collecting, handle);\n }\n\n /**\n * Reads an address as bytes through the priority queue.\n *\n * @param handle - The handle whose byte counters the read feeds.\n * @param priority - The request priority.\n * @param signal - The abort signal.\n * @returns The body.\n */\n fetchBytes(handle: AssetHandleImpl, priority: number, signal: AbortSignal): Promise<ArrayBuffer> {\n return this.#queue.run(priority, () => fetchAssetBytes(this.#fetch, handle.url, signal, handle));\n }\n\n /**\n * Reads an address as UTF-8 text through the priority queue.\n *\n * @param handle - The handle whose byte counters the read feeds.\n * @param priority - The request priority.\n * @param signal - The abort signal.\n * @returns The decoded body.\n */\n fetchText(handle: AssetHandleImpl, priority: number, signal: AbortSignal): Promise<string> {\n return this.#queue.run(priority, () => fetchAssetText(this.#fetch, handle.url, signal, handle));\n }\n\n /**\n * Reads an address as JSON through the priority queue.\n *\n * @typeParam J - The parsed shape.\n * @param handle - The handle whose byte counters the read feeds.\n * @param priority - The request priority.\n * @param signal - The abort signal.\n * @returns The parsed body.\n */\n fetchJson<J>(handle: AssetHandleImpl, priority: number, signal: AbortSignal): Promise<J> {\n return this.#queue.run(priority, () => fetchAssetJson<J>(this.#fetch, handle.url, signal, handle));\n }\n\n /**\n * Requests a dependency of a load.\n *\n * @param ref - The dependency's address or reference.\n * @param options - Priority, type, progress, and cancellation.\n * @param parent - The handle that depends on it.\n * @returns The dependency's handle.\n */\n requestDependency(\n ref: AssetRef | string,\n options: LoadOptions | undefined,\n parent: AssetHandleImpl,\n ): AssetHandleImpl {\n return this.#request(ref, options, parent);\n }\n\n /**\n * Binds the Lite engine `LoaderContext.lite` exposes. `createApp` calls it once the engine exists.\n *\n * @param engine - The app's engine, or the null engine in headless mode.\n */\n attachEngine(engine: LiteEngine): void {\n this.#engine = engine;\n }\n\n /**\n * Applies the resolved `assets` settings section. `createApp` calls it once the extensions have\n * registered and the settings are frozen.\n *\n * @param settings - The resolved section.\n */\n applySettings(settings: AssetsSettings): void {\n if (!this.#hasExplicitManifest) {\n this.#root = settings.root;\n }\n this.#queue.concurrency = Math.max(1, Math.floor(settings.concurrency));\n this.gcDelay = Math.max(0, settings.gcDelay);\n this.#retries = Math.max(0, Math.floor(settings.retries));\n this.#preload = settings.preload;\n }\n\n /**\n * Replaces the manifest after construction — what `@ignifx/vite-plugin` does once it has resolved\n * the virtual development manifest.\n *\n * @param manifest - The new table.\n * @throws IgnifxError with code `IGX-0603` when the manifest declares an unreadable format\n * version.\n */\n setManifest(manifest: AssetManifest): void {\n this.#index = new ManifestIndex(assertSupportedManifest(manifest));\n this.#root = manifest.root;\n this.#hasExplicitManifest = true;\n }\n\n /**\n * Runs the loader again for every cached handle of an address and swaps the value in at delivery\n * — the hot-reload entry point the Vite plugin's HMR channel calls (§7).\n *\n * @remarks\n * A `#fragment` handle carved out of a base address by `parseFragment` is *not* reloaded on its\n * own: it is re-derived from the base's new value when that base is delivered, which is the only\n * order that cannot show a fragment of the old file next to a fragment of the new one.\n *\n * @param address - The address that changed on disk, with or without a fragment.\n */\n reload(address: string): void {\n const path = splitFragment(address).path;\n for (const handle of this.#entries.values()) {\n if (handle.address !== address && handle.path !== path) {\n continue;\n }\n if (handle.state !== \"loaded\" || handle.isRunning) {\n continue;\n }\n if (handle.fragment !== null && handle.loader.parseFragment !== undefined) {\n continue;\n }\n void this.#runReload(handle);\n }\n }\n\n /**\n * Drains the delivery queue, advances the retry and collector timers, and publishes progress and\n * counters. `AssetDeliverySystem` calls it once per frame in `PreUpdate`; while the app is not\n * running, `#enqueueDelivery` delivers as loads finish instead.\n *\n * @param deltaSeconds - Scaled seconds since the previous frame; the collector's clock.\n * @param unscaledDeltaSeconds - Unscaled seconds since the previous frame; the retry clock.\n */\n deliver(deltaSeconds: number, unscaledDeltaSeconds: number): void {\n if (this.#isDisposed) {\n return;\n }\n this.#drainDelivery();\n this.#tickRetries(unscaledDeltaSeconds);\n this.#tickCollector(deltaSeconds);\n this.#publishProgress();\n this.#publishCounters();\n }\n\n /**\n * Cancels every load in flight, rejects the promises that were still pending with `IGX-0503`, and\n * unloads every value. `createApp` registers it as the core extension's disposer.\n */\n dispose(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#isDisposed = true;\n const handles: AssetHandleImpl[] = [];\n for (const handle of this.#entries.values()) {\n handles.push(handle);\n handle.abort();\n }\n this.#entries.clear();\n this.#byAddress.clear();\n this.#queue.clear(\n new IgnifxError(CoreErrorCode.assetAppDisposed, \"The app was disposed before the asset request ran.\", {\n context: { asset: \"pending\" },\n }),\n );\n for (const handle of handles) {\n if (handle.state === \"loading\") {\n handle.settleFailed(\n new AssetLoadError(\n CoreErrorCode.assetAppDisposed,\n `The app that owned the asset ${handle.address} was disposed before loading finished.`,\n { address: handle.address, url: handle.url, context: { asset: handle.address } },\n ),\n );\n }\n this.#releaseValue(handle);\n }\n this.#delivery.length = 0;\n this.#retrying.length = 0;\n this.#collecting.length = 0;\n this.#watching.length = 0;\n this.#session.length = 0;\n this.onProgress.clear();\n }\n\n /**\n * Maps a type's extensions onto it.\n *\n * @param type - The type name.\n * @param extensions - The extensions, with or without their leading dot.\n */\n #mapExtensions(type: string, extensions: readonly string[]): void {\n for (const extension of extensions) {\n this.#typeByExtension.set(normalizeExtension(extension), type);\n }\n }\n\n /**\n * The one entry point every load goes through.\n *\n * @param ref - The address or reference.\n * @param options - Priority, type, progress, and cancellation.\n * @param parent - The handle this load is a dependency of, or `null`.\n * @returns The shared handle, with one more holder.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed, or `IGX-0504` when no\n * loader claims the address.\n */\n #request(ref: AssetRef | string, options: LoadOptions | undefined, parent: AssetHandleImpl | null): AssetHandleImpl {\n if (this.#isDisposed) {\n throw new IgnifxError(\n CoreErrorCode.appDisposed,\n \"The app has been disposed; app.assets is no longer available.\",\n {\n context: { member: \"app.assets\" },\n },\n );\n }\n const address = addressOf(ref);\n const split = splitFragment(address);\n const declared = options?.type ?? declaredTypeOf(ref);\n const type = this.#resolveType(split.path, declared);\n const loader = type === null ? undefined : this.#loaders.get(type);\n if (type === null || loader === undefined) {\n throw new AssetLoadError(CoreErrorCode.assetNoLoader, `No loader is registered for ${address}.`, {\n address,\n url: this.resolveUrl(address),\n context: { asset: address, type: type ?? \"unknown\" },\n hint: \"Register the extension that owns the type, or pass { type } to load().\",\n });\n }\n const key = `${type}${KEY_SEPARATOR}${address}`;\n const priority = options?.priority ?? 0;\n let handle = this.#entries.get(key);\n if (handle === undefined) {\n handle = this.#createHandle(address, split.path, split.fragment, type, key, loader, priority);\n }\n handle.priority = Math.max(handle.priority, priority);\n handle.retain();\n if (handle.state === \"loading\") {\n handle.interested += 1;\n }\n const onProgress = options?.onProgress;\n if (onProgress !== undefined) {\n handle.progressListeners.push(onProgress);\n this.#watch(handle);\n }\n if (parent !== null) {\n this.#linkDependency(parent, handle);\n }\n const signal = options?.signal;\n if (signal !== undefined) {\n this.#attachTicket(handle, signal);\n }\n return handle;\n }\n\n /**\n * Creates a cache entry and starts its load.\n *\n * @param address - The address as requested.\n * @param path - The fragment-free address.\n * @param fragment - The text after `#`, or `null`.\n * @param type - The resolved asset type.\n * @param key - The cache key.\n * @param loader - The loader that owns the type.\n * @param priority - The priority of the request that created it; the fetches inherit it.\n * @returns The new handle, already loading.\n */\n #createHandle(\n address: string,\n path: string,\n fragment: string | null,\n type: string,\n key: string,\n loader: AssetLoader,\n priority: number,\n ): AssetHandleImpl {\n const handle = new AssetHandleImpl({\n address,\n path,\n fragment,\n type,\n key,\n url: this.resolveUrl(path),\n loader,\n host: this,\n });\n const entry = this.#index.entry(path);\n const bytes = entry?.bytes;\n if (bytes !== undefined && bytes > 0) {\n handle.bytesTotal = bytes;\n }\n this.#entries.set(key, handle);\n if (!this.#byAddress.has(address)) {\n this.#byAddress.set(address, handle);\n }\n this.#beginSession(handle);\n this.#watch(handle);\n handle.attempt = 0;\n // Set before the load starts: the fetch reads it when it enters the priority queue.\n handle.priority = priority;\n void this.#runLoad(handle);\n return handle;\n }\n\n /**\n * Works out which asset type an address is.\n *\n * @param path - The fragment-free address.\n * @param declared - The type the caller or the reference declared, or `null`.\n * @returns The type name, or `null` when nothing identifies it.\n */\n #resolveType(path: string, declared: string | null): string | null {\n if (declared !== null) {\n return declared;\n }\n const entry = this.#index.entry(path);\n const fromManifest = entry?.type;\n if (fromManifest !== undefined) {\n return fromManifest;\n }\n const extension = matchExtension(path, this.#typeByExtension.keys());\n return extension === null ? null : (this.#typeByExtension.get(extension) ?? null);\n }\n\n /**\n * Records a dependency once, undoing the extra retain when a retry asks for the same one again.\n *\n * @param parent - The dependent asset.\n * @param dependency - The asset it depends on.\n */\n #linkDependency(parent: AssetHandleImpl, dependency: AssetHandleImpl): void {\n const dependencies = parent.dependencies;\n if (dependencies.includes(dependency)) {\n dependency.release();\n return;\n }\n dependencies.push(dependency);\n }\n\n /**\n * Attaches one request's abort listener.\n *\n * @param handle - The handle the request holds.\n * @param signal - The caller's signal.\n */\n #attachTicket(handle: AssetHandleImpl, signal: AbortSignal): void {\n if (signal.aborted) {\n this.#abortRequest(handle);\n return;\n }\n const onAbort = (): void => {\n this.#abortRequest(handle);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n handle.tickets.push((): void => {\n signal.removeEventListener(\"abort\", onAbort);\n });\n }\n\n /**\n * Drops one request's hold and, when nothing is interested any more, aborts the fetch.\n *\n * @param handle - The handle the request held.\n */\n #abortRequest(handle: AssetHandleImpl): void {\n if (handle.state !== \"loading\") {\n handle.release();\n return;\n }\n handle.interested -= 1;\n handle.release();\n if (handle.interested > 0) {\n return;\n }\n if (handle.retryRemaining !== NO_TIMER) {\n // Aborted while waiting out a retry backoff: no attempt is in flight to observe the abort, so\n // the retry is cancelled here and the handle fails as aborted (`IGX-0502`).\n handle.retryRemaining = NO_TIMER;\n const index = this.#retrying.indexOf(handle);\n if (index !== -1) {\n this.#retrying.splice(index, 1);\n }\n this.#enqueueDelivery({ kind: \"failed\", handle, error: this.#abortError(handle) });\n return;\n }\n handle.abort();\n }\n\n /**\n * Runs one load attempt.\n *\n * @param handle - The handle to load.\n */\n async #runLoad(handle: AssetHandleImpl): Promise<void> {\n const controller = new AbortController();\n handle.controller = controller;\n handle.isRunning = true;\n this.#inFlightCount += 1;\n try {\n const value = await this.#invokeLoader(handle, controller.signal, false, null);\n if (this.#isDisposed) {\n return;\n }\n if (controller.signal.aborted) {\n this.#enqueueDelivery({ kind: \"failed\", handle, error: this.#abortError(handle) });\n return;\n }\n this.#enqueueDelivery({ kind: \"loaded\", handle, value });\n } catch (error) {\n if (!this.#isDisposed) {\n this.#onAttemptFailed(handle, controller, error);\n }\n } finally {\n handle.isRunning = false;\n this.#inFlightCount -= 1;\n }\n }\n\n /**\n * Runs one hot-reload attempt.\n *\n * @param handle - The loaded handle to refresh.\n */\n async #runReload(handle: AssetHandleImpl): Promise<void> {\n const controller = new AbortController();\n const previous = handle.value;\n handle.isRunning = true;\n try {\n const value = await this.#invokeLoader(handle, controller.signal, true, previous);\n if (this.#isDisposed) {\n return;\n }\n if (handle.loader.reload === undefined) {\n // The default reload is \"unload + load\" (§5) done in the safe order: the old value is only\n // released once the new one exists, so a failed reload leaves the asset working.\n this.#runUnload(handle, previous);\n }\n this.#enqueueDelivery({ kind: \"replaced\", handle, value });\n } catch (error) {\n this.#report(error);\n } finally {\n handle.isRunning = false;\n }\n }\n\n /**\n * Calls the loader, resolving a `#fragment` address through the base address first.\n *\n * @param handle - The handle being loaded.\n * @param signal - The abort signal of this attempt.\n * @param isReload - Whether this is a hot-reload attempt.\n * @param previous - The value being replaced, for a reload.\n * @returns What the loader produced.\n */\n async #invokeLoader(\n handle: AssetHandleImpl,\n signal: AbortSignal,\n isReload: boolean,\n previous: unknown,\n ): Promise<unknown> {\n const loader = handle.loader;\n const fragment = handle.fragment;\n if (fragment !== null && loader.parseFragment !== undefined) {\n // The base address is loaded as an ordinary dependency: one fetch is shared by every fragment\n // of the same file, and the base is released when the last fragment handle is unloaded.\n const base = this.#request(handle.path, { type: handle.type, priority: handle.priority }, handle);\n await base.promise;\n return loader.parseFragment(fragment, base.value);\n }\n const context = new LoaderContextImpl(this, handle, signal, handle.priority);\n if (isReload && loader.reload !== undefined) {\n return loader.reload(context, previous);\n }\n return loader.load(context);\n }\n\n /**\n * Decides between a retry and a permanent failure.\n *\n * @param handle - The handle that failed.\n * @param controller - The attempt's controller, which says whether it was aborted.\n * @param error - What the loader threw.\n */\n #onAttemptFailed(handle: AssetHandleImpl, controller: AbortController, error: unknown): void {\n if (controller.signal.aborted) {\n this.#enqueueDelivery({ kind: \"failed\", handle, error: this.#abortError(handle) });\n return;\n }\n if (handle.attempt < this.#retries) {\n handle.attempt += 1;\n handle.retryRemaining = ASSET_RETRY_BASE_SECONDS * 2 ** (handle.attempt - 1);\n this.#retrying.push(handle);\n if (!this.#app.isRunning) {\n this.#armIdleRetry(handle);\n }\n return;\n }\n this.#enqueueDelivery({\n kind: \"failed\",\n handle,\n error: new AssetLoadError(\n CoreErrorCode.assetLoadFailed,\n `Loading ${handle.address} from ${handle.url} failed after ${String(handle.attempt + 1)} attempts.`,\n {\n address: handle.address,\n url: handle.url,\n cause: error,\n context: { asset: handle.address, url: handle.url, attempts: handle.attempt + 1 },\n hint: \"Check the address against the manifest and the network response.\",\n },\n ),\n });\n }\n\n /**\n * Builds the failure an aborted request settles with.\n *\n * @param handle - The handle that was aborted.\n * @returns The `IGX-0502` failure.\n */\n #abortError(handle: AssetHandleImpl): AssetLoadError {\n return new AssetLoadError(CoreErrorCode.assetLoadAborted, `Loading ${handle.address} was aborted.`, {\n address: handle.address,\n url: handle.url,\n context: { asset: handle.address },\n });\n }\n\n /**\n * Queues a completed load, a failure, or a reload for delivery. While the loop is running the\n * queue drains once per frame in `PreUpdate`. Before `app.start()` and after `app.stop()` there is\n * no frame to wait for, so the item is delivered at once — a game can `await` its preloads and\n * then start, and a headless test can `await` a handle without stepping\n * (`05-assets-and-loading.md` §4).\n *\n * @param item - What to deliver.\n */\n #enqueueDelivery(item: DeliveryItem): void {\n this.#delivery.push(item);\n if (!this.#app.isRunning) {\n this.#drainDelivery();\n this.#publishProgress();\n this.#publishCounters();\n }\n }\n\n /**\n * Runs a retry's backoff on the wall clock, because before `app.start()` no frame advances the\n * retry timer. The frame ticker (`#tickRetries`) and this timer guard each other through\n * `retryRemaining`: whichever fires first sets it to `NO_TIMER`, and the other stands down; an\n * abort during the backoff resets it too (`#abortRequest`), so the timer then does nothing.\n *\n * @param handle - The handle whose backoff is counting down.\n */\n #armIdleRetry(handle: AssetHandleImpl): void {\n setTimeout(() => {\n if (this.#isDisposed || handle.retryRemaining === NO_TIMER) {\n return;\n }\n handle.retryRemaining = NO_TIMER;\n const index = this.#retrying.indexOf(handle);\n if (index !== -1) {\n this.#retrying.splice(index, 1);\n }\n void this.#runLoad(handle);\n }, handle.retryRemaining * MILLISECONDS_PER_SECOND);\n }\n\n /** Applies every settled load of the last frame, at the one point §4 allows. */\n #drainDelivery(): void {\n const queue = this.#delivery;\n if (queue.length === 0) {\n return;\n }\n const batch = queue.slice();\n queue.length = 0;\n for (let index = 0; index < batch.length; index += 1) {\n const item = batch[index];\n if (item === undefined) {\n continue;\n }\n const handle = item.handle;\n if (handle.state === \"released\") {\n continue;\n }\n switch (item.kind) {\n case \"loaded\": {\n handle.settleLoaded(item.value);\n this.#loadedCount += 1;\n this.#bytesLoadedTotal += handle.bytesLoaded;\n this.#settleSession(handle);\n break;\n }\n case \"failed\": {\n handle.settleFailed(item.error);\n this.#failedCount += 1;\n this.#settleSession(handle);\n break;\n }\n case \"replaced\": {\n handle.settleReplaced(item.value);\n this.#refreshFragments(handle);\n break;\n }\n default: {\n assertNever(item, \"asset delivery item\");\n }\n }\n if (handle.refCount === 0) {\n this.onZeroReferences(handle);\n }\n }\n }\n\n /**\n * Re-derives every cached `#fragment` handle carved out of a base address that hot reload just\n * replaced, in the same delivery tick, so no two fragments of one file ever disagree.\n *\n * @param base - The base handle whose value changed.\n */\n #refreshFragments(base: AssetHandleImpl): void {\n if (base.fragment !== null) {\n return;\n }\n for (const handle of this.#entries.values()) {\n const fragment = handle.fragment;\n if (fragment === null || handle.loader.parseFragment === undefined || handle.state !== \"loaded\") {\n continue;\n }\n if (!handle.dependencies.includes(base)) {\n continue;\n }\n try {\n handle.settleReplaced(handle.loader.parseFragment(fragment, base.value));\n } catch (error) {\n this.#report(error);\n }\n }\n }\n\n /**\n * Advances the retry countdowns and restarts the attempts that came due.\n *\n * @param deltaSeconds - Unscaled seconds since the previous frame.\n */\n #tickRetries(deltaSeconds: number): void {\n const list = this.#retrying;\n for (let index = list.length - 1; index >= 0; index -= 1) {\n const handle = list[index];\n if (handle === undefined || handle.retryRemaining === NO_TIMER) {\n list.splice(index, 1);\n continue;\n }\n handle.retryRemaining -= deltaSeconds;\n if (handle.retryRemaining <= 0) {\n handle.retryRemaining = NO_TIMER;\n list.splice(index, 1);\n void this.#runLoad(handle);\n }\n }\n }\n\n /**\n * Advances the collector countdowns and unloads what came due.\n *\n * @param deltaSeconds - Scaled seconds since the previous frame.\n */\n #tickCollector(deltaSeconds: number): void {\n const list = this.#collecting;\n for (let index = list.length - 1; index >= 0; index -= 1) {\n const handle = list[index];\n if (handle === undefined) {\n list.splice(index, 1);\n continue;\n }\n if (handle.state === \"loading\") {\n continue;\n }\n handle.gcRemaining -= deltaSeconds;\n if (handle.gcRemaining <= 0) {\n list.splice(index, 1);\n this.#unload(handle);\n }\n }\n }\n\n /** Hands each watched handle's progress to its request callbacks, once per frame. */\n #publishProgress(): void {\n const watching = this.#watching;\n for (let index = watching.length - 1; index >= 0; index -= 1) {\n const handle = watching[index];\n if (handle === undefined) {\n watching.splice(index, 1);\n continue;\n }\n const progress = handle.progress;\n if (progress !== handle.lastDeliveredProgress) {\n handle.lastDeliveredProgress = progress;\n const listeners = handle.progressListeners;\n for (let at = 0; at < listeners.length; at += 1) {\n this.#invokeProgress(listeners[at], progress);\n }\n }\n if (handle.state !== \"loading\") {\n watching.splice(index, 1);\n handle.isWatched = false;\n handle.progressListeners.length = 0;\n }\n }\n this.#publishAggregate();\n }\n\n /**\n * Calls one progress listener, reporting a throw rather than letting it stop delivery.\n *\n * @param listener - The callback, or `undefined` for a hole the index checks produced.\n * @param progress - The fraction to report.\n */\n #invokeProgress(listener: ((fraction: number) => void) | undefined, progress: number): void {\n if (listener === undefined) {\n return;\n }\n try {\n listener(progress);\n } catch (error) {\n this.#report(error);\n }\n }\n\n /** Emits {@link AssetsImpl.onProgress} when the aggregate of the current run changed. */\n #publishAggregate(): void {\n const session = this.#session;\n let bytesLoaded = 0;\n let bytesTotal = 0;\n for (let index = 0; index < session.length; index += 1) {\n const handle = session[index];\n if (handle === undefined) {\n continue;\n }\n bytesLoaded += handle.bytesLoaded;\n bytesTotal += handle.bytesTotal;\n }\n const loaded = this.#sessionSettled;\n const total = session.length;\n if (\n loaded === this.#lastLoaded &&\n total === this.#lastTotal &&\n bytesLoaded === this.#lastBytesLoaded &&\n bytesTotal === this.#lastBytesTotal\n ) {\n return;\n }\n this.#lastLoaded = loaded;\n this.#lastTotal = total;\n this.#lastBytesLoaded = bytesLoaded;\n this.#lastBytesTotal = bytesTotal;\n this.onProgress.emit({ loaded, total, bytesLoaded, bytesTotal });\n }\n\n /** Writes the `assets` diagnostics counters (`15-devtools-and-diagnostics.md` §3). */\n #publishCounters(): void {\n const counters = this.#counters;\n counters.set(this.#countersLoaded, this.#loadedCount);\n counters.set(this.#countersInFlight, this.#inFlightCount);\n counters.set(this.#countersQueued, this.#queue.pendingCount);\n counters.set(this.#countersBytes, this.#bytesLoadedTotal);\n counters.set(this.#countersFailed, this.#failedCount);\n counters.set(this.#countersCandidates, this.#collecting.length);\n }\n\n /**\n * Adds a handle to the progress watch list once.\n *\n * @param handle - The handle to watch.\n */\n #watch(handle: AssetHandleImpl): void {\n if (handle.isWatched) {\n return;\n }\n handle.isWatched = true;\n this.#watching.push(handle);\n }\n\n /**\n * Starts a new aggregate-progress run when the previous one finished, and counts the handle into\n * it.\n *\n * @param handle - The handle whose load just started.\n */\n #beginSession(handle: AssetHandleImpl): void {\n if (this.#sessionSettled >= this.#session.length) {\n for (let index = 0; index < this.#session.length; index += 1) {\n const member = this.#session[index];\n if (member !== undefined) {\n member.isInSession = false;\n }\n }\n this.#session.length = 0;\n this.#sessionSettled = 0;\n }\n handle.isInSession = true;\n this.#session.push(handle);\n }\n\n /**\n * Counts a settled handle into the aggregate-progress run.\n *\n * @param handle - The handle that just settled.\n */\n #settleSession(handle: AssetHandleImpl): void {\n if (!handle.isInSession) {\n return;\n }\n handle.isInSession = false;\n this.#sessionSettled += 1;\n }\n\n /**\n * Builds one batch of requests behind a controller {@link BatchHandleImpl.cancel} can abort.\n *\n * @param refs - The addresses or references.\n * @param options - The options every member inherits, with the batch's own signal substituted.\n * @returns The batch.\n */\n #batch(refs: readonly (AssetRef | string)[], options: LoadOptions | undefined): BatchHandle {\n const controller = new AbortController();\n const outer = options?.signal;\n if (outer !== undefined) {\n if (outer.aborted) {\n controller.abort();\n } else {\n outer.addEventListener(\n \"abort\",\n (): void => {\n controller.abort();\n },\n { once: true },\n );\n }\n }\n const memberOptions: LoadOptions = { ...options, signal: controller.signal };\n const members: AssetHandleImpl[] = [];\n for (const ref of refs) {\n members.push(this.#request(ref, memberOptions, null));\n }\n return new BatchHandleImpl(members, controller);\n }\n\n /**\n * Drops a handle from the cache and releases everything it owns.\n *\n * @param handle - The handle to collect.\n */\n #unload(handle: AssetHandleImpl): void {\n this.#entries.delete(handle.key);\n if (this.#byAddress.get(handle.address) === handle) {\n this.#byAddress.delete(handle.address);\n }\n this.#releaseValue(handle);\n }\n\n /**\n * Releases a handle's value and its dependencies, and marks it released.\n *\n * @param handle - The handle to tear down.\n */\n #releaseValue(handle: AssetHandleImpl): void {\n if (handle.state === \"loaded\") {\n this.#loadedCount -= 1;\n this.#runUnload(handle, handle.value);\n }\n const dependencies = handle.dependencies;\n for (const dependency of dependencies) {\n dependency.release();\n }\n dependencies.length = 0;\n handle.isWatched = false;\n removeFrom(this.#watching, handle);\n handle.markReleased();\n }\n\n /**\n * Runs a loader's `unload`, reporting a throw rather than letting teardown fail.\n *\n * @param handle - The handle the value belonged to.\n * @param value - The value to release.\n */\n #runUnload(handle: AssetHandleImpl, value: unknown): void {\n if (handle.loader.unload === undefined) {\n return;\n }\n try {\n handle.loader.unload(value, new LoaderContextImpl(this, handle, new AbortController().signal, handle.priority));\n } catch (error) {\n this.#report(error);\n }\n }\n\n /**\n * Reports a failure the service caught at its boundary\n * (`docs/architecture/01-lifecycle-and-time.md` §5: `source: \"asset\"`).\n *\n * @param error - What was thrown.\n */\n #report(error: unknown): void {\n this.#app.onError.emit({ error, source: \"asset\", phase: null, entity: null, component: null });\n }\n}\n\n/**\n * Reads the host's `fetch`.\n *\n * @returns The global `fetch`, bound to `globalThis` so it keeps working when it is called as a\n * bare function.\n */\nfunction defaultFetch(): FetchLike {\n return globalThis.fetch.bind(globalThis);\n}\n\n/**\n * The loader a {@link AssetsImpl.register} entry gets when no extension owns its type: it never\n * loads, because the value already exists, and it releases nothing, because an in-code value that\n * owns a resource is expected to be registered under a type whose loader knows how to free it.\n *\n * @param type - The asset type name.\n * @returns A loader that claims no extension.\n */\nfunction memoryLoader(type: string): AssetLoader {\n return {\n type,\n extensions: [],\n load: (): Promise<never> =>\n Promise.reject(\n new IgnifxError(CoreErrorCode.assetNoLoader, `The in-memory asset type ${type} has no loader.`, {\n context: { type },\n hint: \"Register a loader for the type, or keep using app.assets.register() to publish values.\",\n }),\n ),\n };\n}\n\n/**\n * Narrows the untyped cache handle to what the caller declared.\n *\n * @typeParam T - The loaded value type the caller declared.\n * @param handle - The cache entry.\n * @returns The same object, typed.\n */\nfunction toTyped<T>(handle: AssetHandleImpl): AssetHandle<T> {\n // Boundary assertion (coding standards §5.2): a loader returns `unknown`, so `T` is the caller's\n // declaration of what this address holds — the same escape hatch `JSON.parse` callers take.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return handle as unknown as AssetHandle<T>;\n}\n\n/**\n * Removes the first occurrence of a handle from a list, by swapping the last entry into its slot.\n *\n * @param list - The list to edit.\n * @param handle - The handle to remove.\n */\nfunction removeFrom(list: AssetHandleImpl[], handle: AssetHandleImpl): void {\n const index = list.indexOf(handle);\n if (index >= 0) {\n list.splice(index, 1);\n }\n}\n\n/**\n * Discards the array `Promise.all` resolves with, so a batch promise is a `Promise<void>`.\n */\nfunction toVoid(): void {\n // Deliberately empty: the batch reports completion, not values.\n}\n\n/**\n * Swallows a rejection that has already been reported through `state`, `error`, and the handle's own\n * promise.\n */\nfunction ignoreRejection(): void {\n // Deliberately empty: see the comment at the call site.\n}\n\n/**\n * Reaches the engine-owned half of `app.assets` — delivery, hot reload, settings, and disposal —\n * from the kernel and the core extension, which only ever see the public {@link Assets} interface.\n *\n * @param assets - The service, normally `app.assets`.\n * @returns The same object, typed as its implementation.\n * @throws IgnifxError with code `IGX-0702` when the object was not created by ignifx.\n *\n * @internal\n */\nexport function assetsInternals(assets: Assets): AssetsImpl {\n if (assets instanceof AssetsImpl) {\n return assets;\n }\n throw new IgnifxError(CoreErrorCode.invalidRuntime, \"app.assets was not created by this copy of @ignifx/core.\", {\n context: { member: \"app.assets\" },\n hint: \"Reach the service through the app that created it.\",\n });\n}\n","/**\n * The script callbacks the engine dispatches, as ordinals\n * (`docs/architecture/01-lifecycle-and-time.md` §4). Numbering them lets the registry record which\n * callbacks a class implements as one bit mask, and lets the world keep one sorted dispatch list\n * per callback — so a frame never inspects a prototype and never looks a callback up by name\n * (coding standards §7).\n */\n\n/**\n * Every script callback, numbered. The first five are driven by the lifecycle flushes; the rest are\n * dispatched from a phase and therefore get a sorted dispatch list.\n *\n * @public\n */\nexport const ScriptCallbackKind = {\n /** `awake()` — once, when the script first becomes effectively enabled. */\n awake: 0,\n /** `onEnable()` — on every transition to effectively enabled. */\n onEnable: 1,\n /** `start()` — once, in flush B of the first frame the script is effectively enabled. */\n start: 2,\n /** `onDisable()` — on every transition off, including just before destruction. */\n onDisable: 3,\n /** `onDestroy()` — once, in the destroy flush. */\n onDestroy: 4,\n /** `fixedUpdate(dt)` — once per fixed step. */\n fixedUpdate: 5,\n /** `update(dt)` — once per frame. */\n update: 6,\n /** `lateUpdate(dt)` — once per frame, after animation. */\n lateUpdate: 7,\n /** `onCollisionEnter(collision)`. */\n onCollisionEnter: 8,\n /** `onCollisionStay(collision)`. */\n onCollisionStay: 9,\n /** `onCollisionExit(collision)`. */\n onCollisionExit: 10,\n /** `onTriggerEnter(trigger)`. */\n onTriggerEnter: 11,\n /** `onTriggerExit(trigger)`. */\n onTriggerExit: 12,\n /** `onApplicationPause(paused)`. */\n onApplicationPause: 13,\n /** `onApplicationFocus(focused)`. */\n onApplicationFocus: 14,\n} as const;\n\n/**\n * The union of script callback ordinals.\n *\n * @public\n */\nexport type ScriptCallbackKind = (typeof ScriptCallbackKind)[keyof typeof ScriptCallbackKind];\n\n/**\n * How many callbacks `ScriptCallbackKind` declares.\n *\n * @public\n */\nexport const SCRIPT_CALLBACK_COUNT = 15;\n\n/**\n * The first callback that is dispatched from a phase rather than from a lifecycle flush. Only these\n * get a sorted dispatch list on the world.\n *\n * @public\n */\nexport const FIRST_DISPATCHED_CALLBACK: ScriptCallbackKind = ScriptCallbackKind.fixedUpdate;\n\n/**\n * The method name of each callback, indexed by its ordinal. The engine reads a callback off a\n * script's prototype exactly once, at registration; this table is what makes that possible without\n * hard-coding fifteen `if` branches.\n *\n * @public\n */\nexport const SCRIPT_CALLBACK_NAMES: readonly string[] = Object.freeze([\n \"awake\",\n \"onEnable\",\n \"start\",\n \"onDisable\",\n \"onDestroy\",\n \"fixedUpdate\",\n \"update\",\n \"lateUpdate\",\n \"onCollisionEnter\",\n \"onCollisionStay\",\n \"onCollisionExit\",\n \"onTriggerEnter\",\n \"onTriggerExit\",\n \"onApplicationPause\",\n \"onApplicationFocus\",\n]);\n\n/**\n * A lifecycle callback as the engine calls it. Every script callback takes at most one argument —\n * `dt`, a collision, a trigger, or a boolean — so one optional `unknown` covers all fifteen, and\n * the single call site that knows which callback it is supplies the right value.\n *\n * @internal\n */\nexport type CallbackFunction = (argument?: unknown) => void;\n\n/**\n * Reads a callback off an object, if it implements one.\n *\n * @remarks\n * A script's callbacks are ordinary optional methods that the `Script` class deliberately does not\n * declare (see `ScriptCallbacks`), so the type system has nothing to index. This is the single\n * boundary where the engine looks a callback up by name, and it happens once per class at\n * registration — never per entity per frame (coding standards §7).\n *\n * @param target - The instance or prototype to read.\n * @param name - The callback name from {@link SCRIPT_CALLBACK_NAMES}.\n * @returns The function, or `null` when the object does not implement that callback.\n *\n * @internal\n */\nexport function readCallback(target: object, name: string): CallbackFunction | null {\n // Boundary assertion (coding standards §5.2): the invariant is that a JavaScript object can be\n // read as a string-keyed bag; the `typeof` check below is what makes the result safe.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const bag = target as Record<string, unknown>;\n const value = bag[name];\n if (typeof value !== \"function\") {\n return null;\n }\n // Boundary assertion (coding standards §5.2): the value is known to be callable; its parameters\n // are supplied by the single call site that knows which callback this is.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as CallbackFunction;\n}\n\n/**\n * The physics callbacks an extension may deliver through `ExtensionContext.dispatchScriptCallback`,\n * named rather than numbered (`docs/architecture/09-physics.md` §4). The ordinals in\n * `ScriptCallbackKind` are engine plumbing and may be renumbered; these five names are the\n * contract `@ignifx/physics` is written against.\n *\n * @example\n * ```ts\n * ctx.dispatchScriptCallback(entity, PhysicsCallbackName.onTriggerEnter, event);\n * ```\n *\n * @beta\n */\nexport const PhysicsCallbackName = {\n /** `onCollisionEnter(collision)`. */\n onCollisionEnter: \"onCollisionEnter\",\n /** `onCollisionStay(collision)`. */\n onCollisionStay: \"onCollisionStay\",\n /** `onCollisionExit(collision)`. */\n onCollisionExit: \"onCollisionExit\",\n /** `onTriggerEnter(trigger)`. */\n onTriggerEnter: \"onTriggerEnter\",\n /** `onTriggerExit(trigger)`. */\n onTriggerExit: \"onTriggerExit\",\n} as const;\n\n/**\n * The union of the physics callback names.\n *\n * @beta\n */\nexport type PhysicsCallbackName = (typeof PhysicsCallbackName)[keyof typeof PhysicsCallbackName];\n\n/**\n * The ordinal each physics callback name stands for, resolved from a frozen table so that a\n * dispatch never looks a callback up by string on a per-script path (coding standards §7).\n */\nconst PHYSICS_CALLBACK_KINDS: Readonly<Record<PhysicsCallbackName, ScriptCallbackKind>> = Object.freeze({\n onCollisionEnter: ScriptCallbackKind.onCollisionEnter,\n onCollisionStay: ScriptCallbackKind.onCollisionStay,\n onCollisionExit: ScriptCallbackKind.onCollisionExit,\n onTriggerEnter: ScriptCallbackKind.onTriggerEnter,\n onTriggerExit: ScriptCallbackKind.onTriggerExit,\n});\n\n/**\n * Resolves a physics callback name to its `ScriptCallbackKind` ordinal, once per dispatch.\n *\n * @param name - The callback name an extension asked for.\n * @returns The ordinal, which is also the bit index in `ScriptClassInfo.callbacks`.\n *\n * @internal\n */\nexport function physicsCallbackKind(name: PhysicsCallbackName): ScriptCallbackKind {\n return PHYSICS_CALLBACK_KINDS[name];\n}\n","import { IgnifxError } from \"../errors/ignifx-error.js\";\n\n/**\n * Diagnostic codes this module reports. They live in the `06xx` serialization range registered in\n * `docs/architecture/15-devtools-and-diagnostics.md` §1. Codes `IGX-0601` to `IGX-0604` are already\n * spoken for by the scene loader (`docs/architecture/06-serialization-and-scene-format.md`), so the\n * schema-level checks continue from `IGX-0605`.\n *\n * @public\n */\nexport const SchemaIssueCode = {\n /** A number was `NaN`, `Infinity`, or `-Infinity` and therefore cannot be written to JSON. */\n nonFiniteNumber: \"IGX-0601\",\n /** An entity or component reference could not be resolved to a uid. */\n unresolvedReference: \"IGX-0602\",\n /** A value had the wrong JavaScript or JSON type for the field kind. */\n typeMismatch: \"IGX-0605\",\n /** A value had the right type but fell outside the field's declared value domain. */\n outOfRange: \"IGX-0606\",\n /** A property was supplied that the schema does not declare. */\n unknownField: \"IGX-0607\",\n} as const;\n\n/**\n * The union of diagnostic codes this module reports.\n *\n * @public\n */\nexport type SchemaIssueCode = (typeof SchemaIssueCode)[keyof typeof SchemaIssueCode];\n\n/**\n * One problem found while validating, encoding, or decoding a schema value. Issues are plain data:\n * this module never throws for bad *values*, it reports them, and the caller decides whether that\n * is a development-time throw or a logged diagnostic (`CONSTITUTION.md` §3.9).\n *\n * @public\n */\nexport interface SchemaIssue {\n /** Where the problem is, in dotted/bracketed property notation, for example `waypoints[2].x`. */\n readonly path: string;\n /** An actionable description of what went wrong. */\n readonly message: string;\n /** The stable `IGX-####` code for the problem. */\n readonly code: SchemaIssueCode;\n}\n\n/**\n * Builds an issue record.\n *\n * @param code - The diagnostic code.\n * @param path - The property path the problem was found at.\n * @param message - An actionable description.\n * @returns The issue.\n *\n * @internal\n */\nexport function issue(code: SchemaIssueCode, path: string, message: string): SchemaIssue {\n return { path, message, code };\n}\n\n/**\n * Throws for a mistake in a *schema declaration* — as opposed to a bad value, which is reported as\n * a {@link SchemaIssue}. Declarations are authored by hand, so a mistake there is API misuse and\n * must be loud (`CONSTITUTION.md` §3.9).\n *\n * @param code - The diagnostic code carried by the thrown error.\n * @param message - An actionable description of the mistake.\n * @throws IgnifxError carrying `code`. The `06xx` serialization range is registered in\n * `docs/architecture/15-devtools-and-diagnostics.md` section 1.\n *\n * @internal\n */\nexport function throwSchemaError(code: SchemaIssueCode, message: string): never {\n throw new IgnifxError(code, message, {\n hint: \"Schema declarations are authored by hand; fix the declaration rather than the value.\",\n });\n}\n","import { SchemaIssueCode, throwSchemaError } from \"./issues.js\";\nimport type { FieldsOf, PartialFieldsOf, Schema } from \"./types.js\";\n\n/**\n * Property names a schema may not use, because `Component`/`Script` already define them\n * (`docs/architecture/03-scripting-and-components.md` §1 and §2). A schema field becomes a property\n * on the generated base class, so reusing one of these would shadow engine state and break the\n * lifecycle silently.\n *\n * @internal\n */\n// A module-scope `new Set(...)` allocates at import time, which `ignifx/no-module-side-effects` and\n// `CONSTITUTION.md` §3.5 forbid; schemas are declared once per class, so a linear scan is not hot.\n// oxlint-disable-next-line unicorn/prefer-set-has\nconst RESERVED_FIELD_NAMES: readonly string[] = [\n \"uid\",\n \"entity\",\n \"transform\",\n \"world\",\n \"app\",\n \"enabled\",\n \"isDestroyed\",\n \"isEnabledInHierarchy\",\n \"destroy\",\n \"getComponent\",\n \"requireComponent\",\n \"awake\",\n \"onEnable\",\n \"start\",\n \"fixedUpdate\",\n \"update\",\n \"lateUpdate\",\n \"onDisable\",\n \"onDestroy\",\n \"startCoroutine\",\n \"stopCoroutine\",\n \"stopAllCoroutines\",\n];\n\n/**\n * A field name must read like a plain JavaScript identifier so that `this.<name>` works without\n * bracket syntax, and must not start with `_`, which the standards reserve for adapter-internal\n * mirrors (coding standards §5.1).\n *\n * @internal\n */\nconst FIELD_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;\n\n/**\n * Rewrites a JavaScript value into a mutable string-keyed view. Schema-shaped objects are always\n * plain records built by this module, so the assertion holds by construction; it exists because a\n * mapped type such as `FieldsOf<S>` cannot be indexed generically (coding standards §5.2 permits\n * assertions at boundaries like this one, with the invariant stated).\n *\n * @param value - The object to view.\n * @returns The same object, typed as a mutable record.\n *\n * @internal\n */\nfunction mutableView(value: unknown): Record<string, unknown> {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- invariant stated above.\n return value as Record<string, unknown>;\n}\n\n/**\n * Rewrites a plain record into the field object a schema describes. Safe because `createDefaults`\n * fills exactly the schema's keys with values built by that key's own field definition.\n *\n * @param value - The record to view.\n * @returns The same object, typed as the schema's field object.\n *\n * @internal\n */\nfunction fieldsView<S extends Schema>(value: Record<string, unknown>): FieldsOf<S> {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- invariant stated above.\n return value as FieldsOf<S>;\n}\n\n/**\n * Declares a component's serialized fields. The helper is an identity function at runtime — it\n * returns the object it was given — but it checks every field name and, because it is generic,\n * preserves the exact literal type of the schema so `FieldsOf` can project it.\n *\n * `Script.define` and `Component.define` call this before they build a base class.\n *\n * @param fields - The field definitions, keyed by the property name they become.\n * @returns The same object, with its precise type preserved.\n * @throws A `TypeError` when a field name is not identifier-like, starts with `_`, or collides with\n * a `Component`/`Script` member such as `enabled` or `update`.\n *\n * @example\n * ```ts\n * const moverSchema = defineSchema({\n * speed: f32(5, { min: 0, max: 50 }),\n * waypoints: array(vec3()),\n * });\n * ```\n *\n * @public\n */\nexport function defineSchema<S extends Schema>(fields: S): S {\n for (const name of Object.keys(fields)) {\n if (!FIELD_NAME_PATTERN.test(name)) {\n throwSchemaError(\n SchemaIssueCode.unknownField,\n `schema field \"${name}\" is not a valid field name: use a letter followed by letters or digits, and do not start with \"_\".`,\n );\n }\n if (RESERVED_FIELD_NAMES.includes(name)) {\n throwSchemaError(\n SchemaIssueCode.unknownField,\n `schema field \"${name}\" collides with a Component or Script member; rename the field.`,\n );\n }\n }\n return fields;\n}\n\n/**\n * Builds the initial field object for a schema. Every value is freshly allocated by its field's\n * own `createDefault`, so two components declared from the same schema never share a mutable\n * default such as a `vec3` or an `array`.\n *\n * @param schema - The schema to instantiate.\n * @returns A new object holding one default per declared field.\n *\n * @example\n * ```ts\n * const a = createDefaults(moverSchema);\n * const b = createDefaults(moverSchema);\n * a.offset === b.offset; // false — each call allocates\n * ```\n *\n * @public\n */\nexport function createDefaults<S extends Schema>(schema: S): FieldsOf<S> {\n const defaults: Record<string, unknown> = {};\n for (const [name, field] of Object.entries(schema)) {\n defaults[name] = field.createDefault();\n }\n return fieldsView<S>(defaults);\n}\n\n/**\n * Overwrites defaults with caller-supplied values. Only names the schema declares are copied, and\n * a value of `undefined` leaves the default in place — matching the loader's rule that omitted\n * props take schema defaults (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @param target - The field object to write into, normally the result of `createDefaults`.\n * @param schema - The schema that says which names are legal.\n * @param init - The values to apply.\n * @returns The same `target` object, for chaining.\n *\n * @example\n * ```ts\n * const fields = applyInit(createDefaults(moverSchema), moverSchema, { speed: 12 });\n * ```\n *\n * @public\n */\nexport function applyInit<S extends Schema>(target: FieldsOf<S>, schema: S, init: PartialFieldsOf<S>): FieldsOf<S> {\n const writable = mutableView(target);\n const supplied = mutableView(init);\n for (const name of Object.keys(schema)) {\n const value = supplied[name];\n if (value !== undefined) {\n writable[name] = value;\n }\n }\n return target;\n}\n","/**\n * Dense runtime identity (`docs/architecture/00-overview.md` §5). A handle is a plain number so it\n * costs nothing to store, pass, or put in a typed array, and it is branded so that an entity handle\n * and a component handle can never be confused at compile time.\n */\n\n/**\n * The dense runtime id of an entity. Valid until the entity is destroyed; a handle that outlives\n * its entity resolves to `null` through `world.getEntityByHandle` rather than to whatever object\n * recycled the slot.\n *\n * @remarks\n * The `__brand` property exists only in the type system — a handle is a `number` at runtime — so a\n * handle can be stored in a `Float64Array` or written into Lite's node metadata unchanged.\n *\n * @example\n * ```ts\n * const handle: EntityHandle = entity.handle;\n * world.getEntityByHandle(handle)?.destroy();\n * ```\n *\n * @public\n */\nexport type EntityHandle = number & { readonly __brand: \"EntityHandle\" };\n\n/**\n * The dense runtime id of a component, with the same lifetime rules as {@link EntityHandle}.\n *\n * @public\n */\nexport type ComponentHandle = number & { readonly __brand: \"ComponentHandle\" };\n\n/**\n * The handle value that never resolves. Allocated handles always carry a generation of at least\n * one, so zero is unreachable and doubles as \"no handle\".\n *\n * @public\n */\nexport const INVALID_HANDLE = 0;\n\n/**\n * Brands a raw allocator handle as an entity handle.\n *\n * @param value - The number {@link HandleAllocator.allocate} returned.\n * @returns The same number, typed as an entity handle.\n *\n * @internal\n */\nexport function toEntityHandle(value: number): EntityHandle {\n // Boundary assertion (coding standards §5.2): the brand is a compile-time marker with no runtime\n // representation, so branding is the identity function and this is the one place it happens.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as EntityHandle;\n}\n\n/**\n * Brands a raw allocator handle as a component handle.\n *\n * @param value - The number {@link HandleAllocator.allocate} returned.\n * @returns The same number, typed as a component handle.\n *\n * @internal\n */\nexport function toComponentHandle(value: number): ComponentHandle {\n // Boundary assertion (coding standards §5.2); see `toEntityHandle`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as ComponentHandle;\n}\n","import { toComponentHandle, type ComponentHandle } from \"../handles/handle.js\";\nimport type { ComponentClassInfo } from \"./component-registry.js\";\nimport type { Component } from \"./component.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { Signal } from \"../signal/signal.js\";\n\n/**\n * The engine-owned state of a component, kept off the public type.\n *\n * @remarks\n * Components are constructed with `new Type()` and only *then* handed their entity, uid, and\n * handle, so the state cannot live in constructor parameters. It lives behind a module symbol\n * instead: the property is unreachable by name, invisible to `Object.keys`, and impossible to\n * collide with a schema field — while staying fully typed, with no `any` and no assertion\n * (coding standards §5.2).\n */\n\n/**\n * The key the engine state hangs off. Exported so that `Entity`, the lifecycle queue, and the world\n * can reach it; unreachable from game code, which has no way to name the symbol.\n *\n * @internal\n */\nexport const COMPONENT_INTERNALS: unique symbol = Symbol(\"ignifx.component.internals\");\n\n/**\n * The engine-owned state of one component.\n *\n * @internal\n */\nexport interface ComponentInternals {\n /** The owning entity, or `null` between construction and attachment. */\n entity: Entity | null;\n /** The stable ULID, assigned at attachment. */\n uid: string;\n /** The dense runtime handle, assigned at attachment. */\n handle: ComponentHandle;\n /** What the registry worked out about this component's class, assigned at attachment. */\n info: ComponentClassInfo | null;\n /** Monotonic creation serial; the tie-breaker for `start` and dispatch ordering. */\n serial: number;\n /** The component's own enabled flag. */\n enabled: boolean;\n /** `true` between the `onEnable` that ran and the `onDisable` that has not yet. */\n isEnabledNow: boolean;\n /** `true` while an enable transition is waiting for lifecycle flush A. */\n isEnableQueued: boolean;\n /** `true` while a `start` is waiting for lifecycle flush B. */\n isStartQueued: boolean;\n /** `true` once `awake` has run. Never runs twice. */\n hasAwoken: boolean;\n /** `true` once `start` has run. Never runs twice, across any number of enable cycles. */\n hasStarted: boolean;\n /** `true` from the moment `destroy()` is called, long before the destroy flush. */\n isDestroyed: boolean;\n /** `true` once the destroy flush has finished with this component. */\n isReleased: boolean;\n /** `true` while the component sits in the destroy queue, so it is queued at most once. */\n isDestroyQueued: boolean;\n /** Index of this component in each of its class's per-type registry buckets. */\n storeSlots: number[];\n /** Lazily created; `null` until something connects to it. */\n onDestroyed: Signal<Component> | null;\n}\n\n/**\n * Reads a component's engine-owned state.\n *\n * @param component - The component.\n * @returns Its internal state.\n *\n * @internal\n */\nexport function componentInternals(component: Component): ComponentInternals {\n return component[COMPONENT_INTERNALS];\n}\n\n/**\n * Builds the initial engine state of a freshly constructed, not yet attached component.\n *\n * @returns The state, with no entity and no identity yet.\n *\n * @internal\n */\nexport function createComponentInternals(): ComponentInternals {\n return {\n entity: null,\n uid: \"\",\n handle: toComponentHandle(0),\n info: null,\n serial: 0,\n enabled: true,\n isEnabledNow: false,\n isEnableQueued: false,\n isStartQueued: false,\n hasAwoken: false,\n hasStarted: false,\n isDestroyed: false,\n isReleased: false,\n isDestroyQueued: false,\n storeSlots: [],\n onDestroyed: null,\n };\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport { Signal } from \"../signal/signal.js\";\nimport { COMPONENT_INTERNALS, componentInternals, createComponentInternals } from \"./internals.js\";\nimport type { ComponentType } from \"./component-type.js\";\nimport type { ComponentInternals } from \"./internals.js\";\nimport type { App } from \"../app/types.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { ComponentHandle } from \"../handles/handle.js\";\nimport type { FieldsOf, Schema } from \"../schema/types.js\";\nimport type { SignalOwner } from \"../signal/signal.js\";\nimport type { Transform } from \"../transform/transform.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * Typed data and behaviour attached to an entity\n * (`docs/architecture/03-scripting-and-components.md` §1). Engine-owned components\n * (`MeshRenderer`, `Rigidbody`, `AudioSource`) are plain `Component`s driven by systems; game\n * behaviour extends `Script`, which adds the frame lifecycle.\n *\n * @remarks\n * A component class must have a no-argument constructor: the engine constructs it, then assigns\n * `entity`, `uid`, and `handle`, then applies schema defaults and the `init` object, then calls\n * `onAttach`. Reading `this.entity` from a constructor therefore throws `IGX-0206`; cache lookups\n * in `onAttach` or `awake` instead.\n *\n * **Where the statics are declared.** `typeId`, `schema`, `requires`, and `allowMultiple` are not\n * members of this class. Declaring them here would make every `static typeId = \"mygame/Mover\"` an\n * override and force the `override` keyword on it under `noImplicitOverride` (coding standards §3)\n * — the same reasoning that keeps the callbacks on {@link ComponentHooks}. The shape lives on\n * {@link ComponentStatics} instead, and `ComponentRegistry` reads it once per class and supplies\n * the defaults (`allowMultiple` is `true` when the class declares nothing).\n *\n * @example\n * ```ts\n * class Health extends Component.define({ maximum: f32(100) }) {\n * static typeId = \"mygame/Health\";\n * current = 0;\n * onAttach(): void {\n * this.current = this.maximum;\n * }\n * }\n * ```\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- the merged interface below declares one engine-owned property that the constructor always assigns.\nexport abstract class Component implements SignalOwner {\n /** Creates a component. The engine constructs components; game code never calls `new`. */\n constructor() {\n this[COMPONENT_INTERNALS] = createComponentInternals();\n }\n\n /**\n * Declares a component's serialized fields and returns the base class to extend (ADR-0004,\n * `docs/architecture/03-scripting-and-components.md` §3). The returned class exposes every field\n * as a typed instance property, applies the defaults in its constructor, and carries the schema\n * for the serializer, the inspector, and the docs harness.\n *\n * @typeParam S - The schema being declared.\n * @param schema - The field definitions, keyed by the property name they become.\n * @returns An abstract class to extend.\n * @throws IgnifxError with code `IGX-0607` when a field name is not identifier-like or collides\n * with a `Component`/`Script` member.\n *\n * @example\n * ```ts\n * class Spinner extends Component.define({\n * degreesPerSecond: f32(90, { min: -360, max: 360 }),\n * axis: vec3({ x: 0, y: 1, z: 0 }),\n * }) {\n * static typeId = \"mygame/Spinner\";\n * }\n * ```\n */\n static define<const S extends Schema>(schema: S): ComponentDefinition<S> {\n const fields = defineSchema(schema);\n abstract class Defined extends Component {\n static schema: Schema = fields;\n\n constructor() {\n super();\n Object.assign(this, createDefaults(fields));\n }\n }\n // Boundary assertion (coding standards §5.2). The invariant: `Defined`'s constructor assigns\n // exactly the schema's keys with values built by each field's own `createDefault`, so an\n // instance really does have `FieldsOf<S>`. TypeScript cannot express \"this class gains the\n // properties of a value known only at run time\", so the shape is asserted once, here.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return Defined as unknown as ComponentDefinition<S>;\n }\n\n /**\n * The stable ULID; the key files use to reference this component.\n *\n * @returns The identifier.\n */\n get uid(): string {\n return this.#attached().uid;\n }\n\n /**\n * The dense runtime handle; invalid after destruction.\n *\n * @returns The handle.\n */\n get handle(): ComponentHandle {\n return this.#attached().handle;\n }\n\n /**\n * The entity this component is attached to.\n *\n * @returns The owning entity.\n */\n get entity(): Entity {\n const entity = this.#attached().entity;\n if (entity === null) {\n throw notAttached(this);\n }\n return entity;\n }\n\n /**\n * The entity's transform — sugar for `this.entity.transform`, the most-used lookup there is.\n *\n * @returns The entity's transform.\n */\n get transform(): Transform {\n return this.entity.transform;\n }\n\n /**\n * The world the entity belongs to.\n *\n * @returns The world.\n */\n get world(): World {\n return this.entity.world;\n }\n\n /**\n * The app that owns the world.\n *\n * @returns The app.\n */\n get app(): App {\n return this.entity.world.app;\n }\n\n /**\n * The component's own enabled flag; `true` by default. Setting it runs the enable or disable\n * transition (`docs/architecture/01-lifecycle-and-time.md` §6): `onDisable` runs immediately,\n * `awake`/`onEnable` run in the next lifecycle flush — or immediately and nested when the change\n * happens inside a callback.\n *\n * @returns `true` when the component's own flag is set.\n */\n get enabled(): boolean {\n return componentInternals(this).enabled;\n }\n\n set enabled(value: boolean) {\n const internals = componentInternals(this);\n if (internals.enabled === value) {\n return;\n }\n if (internals.isDestroyed) {\n throw new IgnifxError(CoreErrorCode.mutationAfterDestroy, \"This component has been destroyed.\", {\n context: { target: \"component\", uid: internals.uid, operation: \"enabled\" },\n });\n }\n internals.enabled = value;\n const entity = internals.entity;\n if (entity !== null) {\n entity.world.lifecycle.refreshEnabled(this);\n }\n }\n\n /**\n * `true` when the component's own flag is set **and** its entity is active in the hierarchy.\n *\n * @returns `true` when the component is effectively enabled.\n */\n get isEnabledInHierarchy(): boolean {\n const internals = componentInternals(this);\n const entity = internals.entity;\n return internals.enabled && !internals.isDestroyed && entity !== null && entity.activeInHierarchy;\n }\n\n /**\n * `true` from the moment `destroy()` is called, long before the destroy flush runs.\n *\n * @returns `true` once the component has been queued for destruction.\n */\n get isDestroyed(): boolean {\n return componentInternals(this).isDestroyed;\n }\n\n /**\n * Emitted once when the component is destroyed, in the destroy flush. Connecting with\n * `{ owner: this }` elsewhere uses it to detach handlers automatically\n * (`docs/architecture/02-scene-graph.md` §8).\n *\n * @returns The signal. It is created on first access, so a component nobody listens to allocates\n * nothing.\n */\n get onDestroyed(): Signal<Component> {\n const internals = componentInternals(this);\n internals.onDestroyed ??= new Signal<Component>();\n return internals.onDestroyed;\n }\n\n /**\n * Queues this component for destruction. It stays usable until the destroy flush of the current\n * frame, but reports `isDestroyed === true` immediately\n * (`docs/architecture/01-lifecycle-and-time.md` §6). Calling it twice is a no-op.\n */\n destroy(): void {\n const internals = componentInternals(this);\n const entity = internals.entity;\n if (entity === null) {\n internals.isDestroyed = true;\n return;\n }\n entity.removeComponent(this);\n }\n\n /**\n * Finds another component on the same entity — sugar for `this.entity.getComponent`.\n *\n * @typeParam T - The component type to look for.\n * @param type - The component class; matching is by class identity **and** inheritance.\n * @returns The first match in attach order, or `null`.\n */\n getComponent<T extends Component>(type: ComponentType<T>): T | null {\n return this.entity.getComponent(type);\n }\n\n /**\n * Finds another component on the same entity, requiring it to be there — the supported way to\n * link components (`docs/architecture/03-scripting-and-components.md` §8).\n *\n * @typeParam T - The component type to look for.\n * @param type - The component class.\n * @returns The first match in attach order.\n * @throws IgnifxError with code `IGX-0201` when the entity has no such component.\n */\n requireComponent<T extends Component>(type: ComponentType<T>): T {\n return this.entity.requireComponent(type);\n }\n\n /**\n * The engine state, with the \"attached\" invariant checked once.\n *\n * @returns The internals.\n */\n #attached(): ComponentInternals {\n const internals = componentInternals(this);\n if (internals.entity === null) {\n throw notAttached(this);\n }\n return internals;\n }\n}\n\n/**\n * The engine-owned state of a component, declared through interface merging.\n *\n * @remarks\n * A symbol-keyed *class field* is rejected by `isolatedDeclarations` (coding standards §3), which\n * cannot infer a computed property name; declaring it on the merged interface states the type\n * explicitly and emits cleanly. The property is unreachable from game code, which has no way to\n * name the symbol, and cannot collide with a schema field.\n *\n * @public\n */\n// Merging is deliberate and safe here: the class constructor assigns the one property the\n// interface declares, so it is always initialised. A symbol-keyed class field would be cleaner\n// still, but `isolatedDeclarations` rejects computed property names on classes.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- see the note above\nexport interface Component {\n /**\n * The engine-owned state.\n *\n * @internal\n */\n [COMPONENT_INTERNALS]: ComponentInternals;\n}\n\n/**\n * The optional hooks every component may implement\n * (`docs/architecture/03-scripting-and-components.md` §1).\n *\n * @remarks\n * They are declared here rather than on `Component` for the reason spelled out on\n * `ScriptCallbacks`: a member declared on the base class would force every implementation to carry\n * an `override` modifier under `noImplicitOverride` (coding standards §3). Write\n * `implements ComponentHooks` to have the signatures checked.\n *\n * @public\n */\nexport interface ComponentHooks {\n /**\n * Runs after the component's fields are assigned and before `awake`. It may run while the entity\n * is inactive, so it must not assume the component is enabled.\n */\n onAttach?(): void;\n /** Runs just before the component is removed, after `onDestroy`. */\n onDetach?(): void;\n}\n\n/**\n * The abstract base class `Component.define` returns: a `Component` that also carries every\n * field the schema declares, typed.\n *\n * @typeParam S - The schema the class was defined from.\n *\n * @public\n */\nexport type ComponentDefinition<S extends Schema> = (abstract new () => Component & FieldsOf<S>) & {\n /** The instance shape, so the class satisfies `ComponentType`. */\n readonly prototype: Component & FieldsOf<S>;\n /**\n * The schema the class was defined from, carried as a value on the returned class. The other\n * statics ({@link ComponentStatics}) are deliberately *not* declared here: a subclass must be\n * able to write a plain `static typeId` without the `override` keyword.\n */\n readonly schema: S;\n};\n\n/**\n * Builds the \"used before the engine attached it\" error.\n *\n * @param component - The component that was read too early.\n * @returns The error to throw.\n */\nfunction notAttached(component: Component): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.componentNotAttached,\n `${component.constructor.name} is not attached to an entity yet.`,\n {\n context: { component: component.constructor.name },\n hint: \"The engine assigns entity, uid, and handle after construction; read them in onAttach or awake.\",\n },\n );\n}\n","import { Component } from \"../component/component.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport type { Coroutine, CoroutineHandle } from \"../app/types.js\";\nimport type { FieldsOf, Schema } from \"../schema/types.js\";\n\n/**\n * A component that receives the engine lifecycle (`docs/architecture/03-scripting-and-components.md`\n * §2). This is the Unity `MonoBehaviour` role and the primary way game code is written.\n *\n * @remarks\n * **Where the callbacks are declared.** `awake`, `update`, `onCollisionEnter` and the rest are\n * not* members of this class. Declaring them here would make every implementation an override, and\n * `noImplicitOverride` (coding standards §3) would then demand an `override` modifier on every\n * `update` in every game — which the documented examples do not carry, and which would be a tax on\n * the most-written method in the engine. They live in {@link ScriptCallbacks} instead; write\n * `implements ScriptCallbacks` to have their signatures checked. The engine detects which callbacks\n * a class implements once, by inspecting the prototype at registration, so an empty `update() {}`\n * costs a call per frame and not defining it costs nothing.\n *\n * **The statics work the same way.** `typeId`, `schema`, `requires`, `allowMultiple`,\n * `executionOrder`, and `updateWhenPaused` are not members of `Component` or `Script` either: a\n * static declared on the base class is an override too, so `static typeId = \"mygame/Mover\"` would\n * have needed an `override` modifier. Their shape lives on {@link ComponentStatics} and\n * {@link ScriptStatics}, which the class-token types intersect, so a plain `static` on a subclass\n * satisfies them structurally; `ComponentRegistry` reads each one once per class and applies the\n * defaults (`executionOrder` `0`, `updateWhenPaused` `false`).\n *\n * @example\n * ```ts\n * class Mover extends Script.define({ speed: f32(5) }) implements ScriptCallbacks {\n * static typeId = \"mygame/Mover\";\n * static executionOrder = -10;\n *\n * update(dt: number): void {\n * this.transform.translate({ x: 0, y: 0, z: this.speed * dt });\n * }\n * }\n * ```\n *\n * @public\n */\nexport abstract class Script extends Component {\n /**\n * Declares a script's serialized fields and returns the base class to extend — the `Script`\n * counterpart of `Component.define`.\n *\n * @typeParam S - The schema being declared.\n * @param schema - The field definitions, keyed by the property name they become.\n * @returns An abstract class to extend.\n * @throws IgnifxError with code `IGX-0607` when a field name is not identifier-like or collides\n * with a `Component`/`Script` member.\n *\n * @example\n * ```ts\n * class Patrol extends Script.define({ waypoints: array(vec3()), speed: f32(3) }) {\n * static typeId = \"mygame/Patrol\";\n * }\n * ```\n */\n static override define<const S extends Schema>(schema: S): ScriptDefinition<S> {\n const fields = defineSchema(schema);\n abstract class Defined extends Script {\n static schema: Schema = fields;\n\n constructor() {\n super();\n Object.assign(this, createDefaults(fields));\n }\n }\n // Boundary assertion (coding standards §5.2); the invariant is the one stated on\n // `Component.define`: the constructor assigns exactly the schema's keys.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return Defined as unknown as ScriptDefinition<S>;\n }\n\n /**\n * Starts a coroutine owned by this script (`docs/architecture/01-lifecycle-and-time.md` §5). The\n * coroutine is paused while the script is not effectively enabled and cancelled when it is\n * destroyed.\n *\n * @param routine - The generator to drive. Call the generator function: `this.spawnLoop()`.\n * @returns A handle for stopping it or waiting on it.\n *\n * @example\n * ```ts\n * blink() {\n * while (true) {\n * this.renderer.enabled = !this.renderer.enabled;\n * yield waitSeconds(0.2);\n * }\n * }\n * onEnable(): void {\n * this.startCoroutine(this.blink());\n * }\n * ```\n */\n startCoroutine(routine: Coroutine): CoroutineHandle {\n return this.app.coroutines.start(this, routine);\n }\n\n /**\n * Stops one coroutine this script started. Stopping a finished coroutine is a no-op.\n *\n * @param handle - The handle {@link Script.startCoroutine} returned.\n */\n stopCoroutine(handle: CoroutineHandle): void {\n this.app.coroutines.stop(handle);\n }\n\n /** Stops every coroutine this script started. */\n stopAllCoroutines(): void {\n this.app.coroutines.stopAll(this);\n }\n}\n\n/**\n * Every callback a script may implement, with the signature the engine calls it with\n * (`docs/architecture/01-lifecycle-and-time.md` §4). All of them are optional; implement only the\n * ones the script needs.\n *\n * @remarks\n * The interface is deliberately not merged into {@link Script} — see the note there. Adding\n * `implements ScriptCallbacks` to a script is free at run time and checks that every callback the\n * class does implement has the right name and signature.\n *\n * @example\n * ```ts\n * class Door extends Script implements ScriptCallbacks {\n * awake(): void {\n * this.body = this.requireComponent(Rigidbody);\n * }\n * fixedUpdate(dt: number): void {\n * this.body.move(dt);\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface ScriptCallbacks {\n /**\n * Runs once, the first time the script becomes effectively enabled inside a loaded world. During\n * a scene load it runs after every entity and component of that scene instance exists, in tree\n * order, with `entityRef`/`componentRef` fields already resolved.\n */\n awake?(): void;\n /** Runs after `awake`, and on every later transition to effectively enabled. */\n onEnable?(): void;\n /** Runs once, in the first frame the script is effectively enabled, after the fixed loop. */\n start?(): void;\n /**\n * Runs once per fixed step, before physics.\n *\n * @param dt - The fixed step in seconds; always `time.fixedDeltaTime`.\n */\n fixedUpdate?(dt: number): void;\n /**\n * Runs once per frame.\n *\n * @param dt - Scaled seconds since the previous frame.\n */\n update?(dt: number): void;\n /**\n * Runs once per frame, after animation has posed the scene.\n *\n * @param dt - Scaled seconds since the previous frame.\n */\n lateUpdate?(dt: number): void;\n /** Runs on every transition off effectively enabled, including just before destruction. */\n onDisable?(): void;\n /** Runs once, in the destroy flush of the frame `destroy()` was called in. */\n onDestroy?(): void;\n /**\n * Runs when a contact begins, inside the fixed loop after the physics step.\n *\n * @param collision - The contact, supplied by the physics extension.\n */\n onCollisionEnter?(collision: unknown): void;\n /**\n * Runs while a contact persists.\n *\n * @param collision - The contact.\n */\n onCollisionStay?(collision: unknown): void;\n /**\n * Runs when a contact ends.\n *\n * @param collision - The contact.\n */\n onCollisionExit?(collision: unknown): void;\n /**\n * Runs when an overlap with a trigger shape begins.\n *\n * @param trigger - The overlap, supplied by the physics extension.\n */\n onTriggerEnter?(trigger: unknown): void;\n /**\n * Runs when an overlap with a trigger shape ends.\n *\n * @param trigger - The overlap.\n */\n onTriggerExit?(trigger: unknown): void;\n /**\n * Runs when the document is hidden or shown, or the Electron window is minimized or restored.\n *\n * @param paused - `true` when the app just became hidden.\n */\n onApplicationPause?(paused: boolean): void;\n /**\n * Runs on window focus changes.\n *\n * @param focused - `true` when the window just gained focus.\n */\n onApplicationFocus?(focused: boolean): void;\n}\n\n/**\n * The abstract base class {@link Script.define} returns: a `Script` that also carries every field\n * the schema declares, typed.\n *\n * @typeParam S - The schema the class was defined from.\n *\n * @public\n */\nexport type ScriptDefinition<S extends Schema> = (abstract new () => Script & FieldsOf<S>) & {\n /** The instance shape, so the class satisfies `ComponentType`. */\n readonly prototype: Script & FieldsOf<S>;\n /**\n * The schema the class was defined from, carried as a value on the returned class. The other\n * statics ({@link ScriptStatics}) are deliberately *not* declared here: a subclass must be able\n * to write a plain `static typeId` or `static executionOrder` without the `override` keyword.\n */\n readonly schema: S;\n};\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n SCRIPT_CALLBACK_COUNT,\n SCRIPT_CALLBACK_NAMES,\n readCallback,\n type ScriptCallbackKind,\n} from \"../lifecycle/callbacks.js\";\nimport { Script } from \"../script/script.js\";\nimport { Component } from \"./component.js\";\nimport type { ComponentType, ConcreteComponentType, ScriptStatics } from \"./component-type.js\";\nimport type { FieldDefinition, Schema } from \"../schema/types.js\";\n\n/**\n * The per-app table of component classes\n * (`docs/architecture/03-scripting-and-components.md` §4). It does three jobs: it maps `typeId`s to\n * classes for the serializer, it works out once per class which callbacks the class implements and\n * which of its fields are tracked references, and it precomputes each class's ancestor chain so\n * that `world.components(Type)` never walks a prototype at run time (coding standards §7).\n */\n\n/** `<namespace>/<Name>`: one or more path-safe segments, a slash, then a PascalCase-ish name. */\nconst TYPE_ID_PATTERN = /^[a-z0-9][a-z0-9\\-.@/]*\\/[A-Za-z][A-Za-z0-9]*$/u;\n\n/**\n * What the registry worked out about a script class by inspecting its prototype exactly once.\n *\n * @public\n */\nexport interface ScriptClassInfo {\n /** `static executionOrder`, resolved at registration. */\n readonly executionOrder: number;\n /** `static updateWhenPaused`, resolved at registration. */\n readonly updateWhenPaused: boolean;\n /** One bit per `ScriptCallbackKind`: set when the class implements that callback. */\n readonly callbacks: number;\n}\n\n/**\n * Everything the engine needs to know about a component class, computed once and cached.\n *\n * @public\n */\nexport interface ComponentClassInfo {\n /** The class itself. */\n readonly type: ComponentType;\n /** The namespaced registration id, or `null` when the class declares none. */\n readonly typeId: string | null;\n /** The declared serialized fields, or `null` when the class was not built with `define`. */\n readonly schema: Schema | null;\n /** Component types auto-added to, and validated on, the entity. */\n readonly requires: readonly ComponentType[];\n /** `false` when at most one instance may live on an entity. */\n readonly allowMultiple: boolean;\n /**\n * The class and every component class it derives from, nearest first, ending at `Component`.\n * `world.components(Type)` and `getComponent(Type)` match against this list, which is why they\n * are inheritance-aware without touching a prototype chain per frame.\n */\n readonly ancestors: readonly ComponentType[];\n /**\n * The names of the `entityRef`/`componentRef` fields the schema declares. The world's reference\n * tracker nulls exactly these when their target is destroyed\n * (`docs/architecture/02-scene-graph.md` §4).\n */\n readonly trackedFields: readonly string[];\n /** `true` when the class derives from `Script`. */\n readonly isScript: boolean;\n /** Callback and ordering data, or `null` for a plain component. */\n readonly script: ScriptClassInfo | null;\n /** A dense index assigned in registration order, for array-indexed per-class bookkeeping. */\n readonly classIndex: number;\n}\n\n/**\n * The component-class table of one app. There is one per {@link App}, never a module-level one\n * (`CONSTITUTION.md` §3.5, §3.6): two apps in one test process must not see each other's types.\n *\n * @example\n * ```ts\n * const registry = new ComponentRegistry();\n * registry.register(Mover);\n * registry.get(\"mygame/Mover\"); // Mover\n * ```\n *\n * @public\n */\nexport class ComponentRegistry {\n readonly #byTypeId = new Map<string, ComponentType>();\n\n readonly #info = new Map<ComponentType, ComponentClassInfo>();\n\n #nextClassIndex = 0;\n\n /**\n * How many classes the registry has described, registered explicitly or not.\n *\n * @returns The class count.\n */\n get size(): number {\n return this.#info.size;\n }\n\n /**\n * Registers a component class so that scenes using it can be loaded and saved.\n *\n * @param type - The component class.\n * @param typeId - An explicit id, when the class does not declare one.\n * @returns What the registry worked out about the class.\n * @throws IgnifxError with code `IGX-0203` when the id is already registered by another class, or\n * when the id is not `<namespace>/<Name>`.\n */\n register(type: ConcreteComponentType, typeId?: string): ComponentClassInfo {\n const id = typeId ?? readStatics(type).typeId ?? null;\n if (id !== null) {\n if (!TYPE_ID_PATTERN.test(id)) {\n throw new IgnifxError(CoreErrorCode.duplicateComponentTypeId, `The component type id ${id} is malformed.`, {\n context: { typeId: id, owner: type.prototype.constructor.name },\n hint: 'Type ids are \"<package-or-game>/<Name>\", for example \"mygame/Mover\".',\n });\n }\n const existing = this.#byTypeId.get(id);\n if (existing !== undefined && existing !== type) {\n throw new IgnifxError(\n CoreErrorCode.duplicateComponentTypeId,\n `The component type id ${id} is already registered.`,\n { context: { typeId: id, owner: existing.prototype.constructor.name } },\n );\n }\n this.#byTypeId.set(id, type);\n }\n return this.describe(type);\n }\n\n /**\n * Registers several component classes.\n *\n * @param types - The component classes.\n */\n registerAll(types: readonly ConcreteComponentType[]): void {\n for (let index = 0; index < types.length; index += 1) {\n const type = types[index];\n if (type !== undefined) {\n this.register(type);\n }\n }\n }\n\n /**\n * Describes a class, computing and caching its info on first sight. Explicit registration is only\n * needed for *serializable* components; a script added from code is described the first time it\n * is attached (`docs/architecture/03-scripting-and-components.md` §4).\n *\n * @param type - The component class.\n * @returns The cached class info.\n */\n describe(type: ComponentType): ComponentClassInfo {\n const cached = this.#info.get(type);\n if (cached !== undefined) {\n return cached;\n }\n const info = this.#build(type);\n this.#info.set(type, info);\n return info;\n }\n\n /**\n * Looks a class up by its registered id.\n *\n * @param typeId - The namespaced id.\n * @returns The class, or `null` when nothing is registered under the id.\n */\n get(typeId: string): ComponentType | null {\n return this.#byTypeId.get(typeId) ?? null;\n }\n\n /**\n * Every class registered under a type id, paired with that id, in registration order.\n *\n * @remarks\n * The scene-file JSON Schema generator\n * (`docs/architecture/06-serialization-and-scene-format.md` §8) walks it to narrow\n * `components[].props` per `typeId`. Classes described but never registered are not listed:\n * only a registered class can appear in a file.\n *\n * @returns A freshly allocated array of `[typeId, class]` pairs.\n */\n registrations(): readonly (readonly [typeId: string, type: ComponentType])[] {\n const pairs: (readonly [string, ComponentType])[] = [];\n for (const [typeId, type] of this.#byTypeId) {\n pairs.push([typeId, type]);\n }\n return pairs;\n }\n\n /**\n * Reports whether a class was registered explicitly.\n *\n * @param type - The component class.\n * @returns `true` when the class was registered under a type id.\n */\n isRegistered(type: ComponentType): boolean {\n const id = readStatics(type).typeId;\n return id !== undefined && this.#byTypeId.get(id) === type;\n }\n\n /**\n * Reports whether a component class implements a script callback, from the bit mask the registry\n * computed when it first described the class. Extension authors use it to decide once per class\n * what a per-frame path would otherwise have to rediscover\n * (`docs/architecture/04-extensions.md` §3).\n *\n * @param type - The component class. A plain (non-`Script`) class always answers `false`.\n * @param kind - The callback ordinal.\n * @returns `true` when the class implements the callback.\n *\n * @example\n * ```ts\n * registry.implementsCallback(Explode, ScriptCallbackKind.onCollisionEnter); // true\n * ```\n */\n implementsCallback(type: ComponentType, kind: ScriptCallbackKind): boolean {\n return implementsCallback(this.describe(type).script, kind);\n }\n\n /**\n * The id a component must carry to be written to a file.\n *\n * @param type - The component class.\n * @returns The registered id.\n * @throws IgnifxError with code `IGX-0204` when the class declares no `typeId`.\n */\n requireTypeId(type: ComponentType): string {\n const id = readStatics(type).typeId;\n if (id === undefined || id === \"\") {\n throw new IgnifxError(\n CoreErrorCode.componentTypeIdMissing,\n `${type.prototype.constructor.name} cannot be serialized because it has no typeId.`,\n {\n context: { component: type.prototype.constructor.name },\n hint: 'Add `static typeId = \"<package-or-game>/<Name>\"` and register the class.',\n },\n );\n }\n return id;\n }\n\n /**\n * Computes a class's info.\n *\n * @param type - The component class.\n * @returns The freshly built info.\n */\n #build(type: ComponentType): ComponentClassInfo {\n const statics = readStatics(type);\n const ancestors = collectAncestors(type);\n const schema = statics.schema ?? null;\n const isScript = ancestors.includes(Script);\n const classIndex = this.#nextClassIndex;\n this.#nextClassIndex += 1;\n return {\n type,\n typeId: statics.typeId ?? null,\n schema,\n requires: statics.requires ?? EMPTY_TYPES,\n allowMultiple: statics.allowMultiple ?? true,\n ancestors,\n trackedFields: schema === null ? EMPTY_NAMES : collectTrackedFields(schema),\n isScript,\n script: isScript ? buildScriptInfo(type) : null,\n classIndex,\n };\n }\n}\n\n/** Shared empty lists so the common case allocates nothing. */\nconst EMPTY_TYPES: readonly ComponentType[] = Object.freeze([]);\n\n/** Shared empty name list. */\nconst EMPTY_NAMES: readonly string[] = Object.freeze([]);\n\n/**\n * Walks a class's prototype chain once, collecting every component class it derives from.\n *\n * @param type - The component class.\n * @returns The class itself first, then each ancestor, ending at `Component`.\n */\nfunction collectAncestors(type: ComponentType): readonly ComponentType[] {\n const ancestors: ComponentType[] = [];\n let current: ComponentType | null = type;\n while (current !== null) {\n ancestors.push(current);\n if (current === Component) {\n break;\n }\n // The invariant is that every constructor on a component class's prototype chain is itself a\n // component class; the chain starts at one and the loop stops at `Component`.\n const parent: unknown = Object.getPrototypeOf(current);\n current = typeof parent === \"function\" ? parent : null;\n }\n return ancestors;\n}\n\n/**\n * Finds the schema fields the reference tracker has to watch.\n *\n * @param schema - The class's declared fields.\n * @returns The names of the `entityRef` and `componentRef` fields, in declaration order.\n */\nfunction collectTrackedFields(schema: Schema): readonly string[] {\n const names: string[] = [];\n for (const entry of Object.entries(schema)) {\n const field: FieldDefinition<unknown> = entry[1];\n if (field.kind === \"entityRef\" || field.kind === \"componentRef\") {\n names.push(entry[0]);\n }\n }\n return names.length === 0 ? EMPTY_NAMES : names;\n}\n\n/**\n * Inspects a script class's prototype once, recording which callbacks it implements.\n *\n * @param type - The script class.\n * @returns The ordering values and the callback bit mask.\n */\nfunction buildScriptInfo(type: ComponentType): ScriptClassInfo {\n const statics = readStatics(type);\n let callbacks = 0;\n const prototype = type.prototype;\n for (let kind = 0; kind < SCRIPT_CALLBACK_COUNT; kind += 1) {\n const name = SCRIPT_CALLBACK_NAMES[kind];\n if (name !== undefined && readCallback(prototype, name) !== null) {\n callbacks |= 1 << kind;\n }\n }\n return {\n executionOrder: statics.executionOrder ?? 0,\n updateWhenPaused: statics.updateWhenPaused ?? false,\n callbacks,\n };\n}\n\n/**\n * Widens a class token to the structural statics a component or script class may declare\n * (`ComponentStatics` / `ScriptStatics`). Every one of them is optional, so the widening is a plain\n * assignment, not an assertion. This is the **only** place the engine reads a static off a class:\n * everything else goes through the {@link ComponentClassInfo} this registry caches.\n *\n * @param type - The component class.\n * @returns The same class, seen as its declarable statics.\n */\nfunction readStatics(type: ComponentType): ScriptStatics {\n return type;\n}\n\n/**\n * Reports whether a class implements a callback, from its cached bit mask.\n *\n * @param info - The class info, or `null` for a plain component.\n * @param kind - The callback ordinal.\n * @returns `true` when the class implements the callback.\n *\n * @internal\n */\nexport function implementsCallback(info: ScriptClassInfo | null, kind: number): boolean {\n return info !== null && (info.callbacks & (1 << kind)) !== 0;\n}\n","import { assertNever } from \"../errors/ignifx-error.js\";\nimport type { Coroutine, CoroutineHandle, CoroutineHost, CoroutineYield, WaitInstruction } from \"../app/types.js\";\nimport type { FrameStateController } from \"../lifecycle/frame-state.js\";\nimport type { Script } from \"../script/script.js\";\n\n/**\n * The generator-coroutine scheduler (`docs/architecture/01-lifecycle-and-time.md` §5, ADR-0010).\n * Coroutines are resumed **synchronously**, by the frame function, at two points: after every\n * script's `update` (the `Update` resume point) and immediately after each fixed step. Nothing here\n * ever resumes a coroutine from a microtask — a promise continuation only records the outcome and\n * raises a flag the next `Update` reads, which is what keeps ordering deterministic relative to\n * other scripts.\n *\n * Decisions the documents leave open, and how this implementation settles them:\n *\n * - **A coroutine runs up to its first `yield` immediately.** §5's example calls\n * `this.audio.play(\"creak\")` before the first `yield waitSeconds(0.5)` and reads as if the sound\n * plays when `startCoroutine` is called, which is also Unity's behaviour. The first segment\n * therefore runs inside `startCoroutine`, unless the owning script is not effectively enabled, in\n * which case the coroutine starts paused and its first segment runs at the first `Update` after\n * it is enabled.\n * - **`waitSeconds(s)` is inclusive.** The wait ends on the first `Update` at which the accumulated\n * scaled time is greater than or equal to `s`, so `waitSeconds(1 / 60)` resumes one frame later\n * at a steady 60 fps rather than two.\n * - **`stopCoroutine` detaches promises too.** §5 distinguishes stopping from cancelling only by\n * intent; both leave a coroutine that can never run again, so both detach pending promise\n * continuations. A settlement that arrives afterwards does nothing.\n */\n\n/** What a suspended coroutine is waiting for. */\nconst WaitState = {\n /** `yield`, `yield null`, or `yield undefined`: the next `Update` resume point. */\n nextUpdate: 0,\n /** `waitSeconds(s)`: scaled time. */\n seconds: 1,\n /** `waitSecondsRealtime(s)`: unscaled time. */\n secondsRealtime: 2,\n /** `waitFixedUpdate()`: the point just after the next fixed step. */\n fixedUpdate: 3,\n /** `waitUntil(pred)`. */\n until: 4,\n /** `waitWhile(pred)`. */\n whileTrue: 5,\n /** `yield handle`: another coroutine finishing. */\n handle: 6,\n /** `yield promise`: the first `Update` after the promise settles. */\n promise: 7,\n} as const;\n\n/** The union of {@link WaitState} ordinals. */\ntype WaitState = (typeof WaitState)[keyof typeof WaitState];\n\n/**\n * Relative slack applied to a timed wait, mirroring the fixed-step accumulator's snapping rule\n * (`docs/architecture/01-lifecycle-and-time.md` §3 notes).\n */\nconst WAIT_TOLERANCE = 1e-6;\n\n/**\n * The handle `Script.startCoroutine` returns. It carries a back-reference to its record so that\n * `stopCoroutine(handle)` is O(1) and so that a handle from another app is rejected by identity.\n */\nclass CoroutineHandleImpl implements CoroutineHandle {\n /** `true` while the coroutine is still scheduled, including while it is paused. */\n isRunning = true;\n\n /** `true` once the coroutine finished, was stopped, or was cancelled. */\n isDone = false;\n\n /** The record this handle addresses, or `null` once the coroutine has finished. */\n record: CoroutineRecord | null = null;\n}\n\n/** One scheduled coroutine. Every field is mutated in place; the record itself is never copied. */\nclass CoroutineRecord {\n /** The script whose enabled state gates the coroutine. */\n readonly owner: Script;\n\n /** The generator, or `null` once the coroutine has finished. */\n routine: Coroutine | null;\n\n /** The handle handed to game code. */\n readonly handle: CoroutineHandleImpl;\n\n /** What the coroutine is waiting for. */\n wait: WaitState = WaitState.nextUpdate;\n\n /** Seconds still to wait, for the two timed waits. */\n remaining = 0;\n\n /**\n * How close to zero {@link CoroutineRecord.remaining} has to get before the wait counts as\n * elapsed. Repeated subtraction of a scaled delta rarely cancels exactly in binary floating\n * point, so the same relative `1e-6` slack the fixed-step accumulator uses\n * (`01-lifecycle-and-time.md` §3 notes) is applied here.\n */\n tolerance = 0;\n\n /** The condition, for the two predicate waits. */\n predicate: (() => boolean) | null = null;\n\n /** The coroutine being waited on, for `yield handle`. */\n awaited: CoroutineHandle | null = null;\n\n /** Whether the awaited promise has settled since the wait began. */\n isSettled = false;\n\n /** Whether the settled promise rejected, in which case the reason is thrown into the generator. */\n isRejected = false;\n\n /** The settled value or the rejection reason. */\n settled: unknown = null;\n\n /** The value handed to the next `routine.next(...)`. */\n resumeValue: unknown = undefined;\n\n /** `true` while the owning script is not effectively enabled. */\n isPaused = false;\n\n /**\n * Bumped whenever the coroutine finishes, so a promise continuation captured before that point\n * recognises itself as stale and does nothing (§5, \"any promise it was waiting on is detached\").\n */\n generation = 0;\n\n /**\n * Creates a record.\n *\n * @param owner - The owning script.\n * @param routine - The generator to drive.\n */\n constructor(owner: Script, routine: Coroutine) {\n this.owner = owner;\n this.routine = routine;\n this.handle = new CoroutineHandleImpl();\n this.handle.record = this;\n }\n}\n\n/**\n * What the host needs from the app.\n *\n * @internal\n */\nexport interface CoroutineHostOptions {\n /** The frame state, so a coroutine body counts as \"inside a callback\". */\n readonly frameState: FrameStateController;\n /**\n * Reports an exception a coroutine threw.\n *\n * @param error - Whatever was thrown.\n * @param owner - The script that owns the coroutine.\n */\n report(error: unknown, owner: Script): void;\n}\n\n/**\n * The coroutine scheduler of one app.\n *\n * @internal\n */\nexport class CoroutineHostImpl implements CoroutineHost {\n readonly #frameState: FrameStateController;\n\n readonly #report: (error: unknown, owner: Script) => void;\n\n readonly #records: CoroutineRecord[] = [];\n\n readonly #byOwner = new Map<Script, CoroutineRecord[]>();\n\n #deadCount = 0;\n\n #walkDepth = 0;\n\n /**\n * Creates the scheduler of one app.\n *\n * @param options - The frame state and the error reporter.\n */\n constructor(options: CoroutineHostOptions) {\n this.#frameState = options.frameState;\n this.#report = (error: unknown, owner: Script): void => {\n options.report(error, owner);\n };\n }\n\n /**\n * How many coroutines are scheduled, paused ones included.\n *\n * @returns The live coroutine count.\n */\n get count(): number {\n return this.#records.length - this.#deadCount;\n }\n\n /**\n * Schedules a coroutine owned by a script and runs its first segment when the script is\n * effectively enabled.\n *\n * @param owner - The script whose enabled state gates the coroutine.\n * @param routine - The generator to drive.\n * @returns A handle for stopping it or waiting on it.\n */\n start(owner: Script, routine: Coroutine): CoroutineHandle {\n const record = new CoroutineRecord(owner, routine);\n this.#records.push(record);\n let owned = this.#byOwner.get(owner);\n if (owned === undefined) {\n owned = [];\n this.#byOwner.set(owner, owned);\n }\n owned.push(record);\n if (owner.isDestroyed || !owner.isEnabledInHierarchy) {\n record.isPaused = true;\n return record.handle;\n }\n this.#advance(record);\n return record.handle;\n }\n\n /**\n * Stops one coroutine. Stopping a finished coroutine, or a handle from another app, is a no-op.\n *\n * @param handle - The handle {@link CoroutineHostImpl.start} returned.\n */\n stop(handle: CoroutineHandle): void {\n if (!(handle instanceof CoroutineHandleImpl)) {\n return;\n }\n const record = handle.record;\n if (record !== null) {\n this.#finish(record);\n }\n }\n\n /**\n * Stops every coroutine a script started.\n *\n * @param owner - The owning script.\n */\n stopAll(owner: Script): void {\n this.#finishOwned(owner);\n }\n\n /**\n * Pauses or resumes every coroutine a script started.\n *\n * @param owner - The owning script.\n * @param paused - `true` to pause, `false` to resume.\n */\n setPaused(owner: Script, paused: boolean): void {\n const owned = this.#byOwner.get(owner);\n if (owned === undefined) {\n return;\n }\n for (let index = 0; index < owned.length; index += 1) {\n const record = owned[index];\n if (record !== undefined) {\n record.isPaused = paused;\n }\n }\n }\n\n /**\n * Cancels every coroutine a script started and detaches any promise they were waiting on.\n *\n * @param owner - The owning script.\n */\n cancelAll(owner: Script): void {\n this.#finishOwned(owner);\n }\n\n /**\n * The `Update` resume point (`01-lifecycle-and-time.md` §3 step 6), run after every script's\n * `update`.\n *\n * @param deltaTime - Scaled seconds this frame, for `waitSeconds`.\n * @param unscaledDeltaTime - Unscaled seconds this frame, for `waitSecondsRealtime`.\n * @returns How many coroutines were resumed.\n */\n resumeUpdate(deltaTime: number, unscaledDeltaTime: number): number {\n let resumed = this.#walk(WaitState.nextUpdate, deltaTime, unscaledDeltaTime);\n // A coroutine waiting on another's handle must not care whether it was started before or after\n // the one it waits for: extra passes over the handle waits alone make the outcome the same\n // either way, and they terminate because a coroutine can only finish once.\n for (;;) {\n const again = this.#walkHandleWaiters();\n if (again === 0) {\n break;\n }\n resumed += again;\n }\n return resumed;\n }\n\n /**\n * The fixed-step resume point (§3 step 4), run after each fixed step.\n *\n * @returns How many coroutines were resumed.\n */\n resumeFixedUpdate(): number {\n return this.#walk(WaitState.fixedUpdate, 0, 0);\n }\n\n /** Cancels every coroutine and detaches every pending promise continuation, for app disposal. */\n dispose(): void {\n const records = this.#records;\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (record !== undefined && record.routine !== null) {\n this.#finish(record);\n }\n }\n records.length = 0;\n this.#byOwner.clear();\n this.#deadCount = 0;\n }\n\n /**\n * Resumes every coroutine whose awaited handle has finished, in one pass.\n *\n * @returns How many coroutines were resumed.\n */\n #walkHandleWaiters(): number {\n const records = this.#records;\n const count = records.length;\n let resumed = 0;\n this.#walkDepth += 1;\n for (let index = 0; index < count; index += 1) {\n const record = records[index];\n if (record === undefined || record.routine === null || record.isPaused || record.owner.isDestroyed) {\n continue;\n }\n if (record.wait !== WaitState.handle || record.awaited?.isDone !== true) {\n continue;\n }\n resumed += 1;\n this.#advance(record);\n }\n this.#walkDepth -= 1;\n if (this.#walkDepth === 0 && this.#deadCount > 0) {\n this.#compact();\n }\n return resumed;\n }\n\n /**\n * Walks the scheduled coroutines once, resuming those whose wait has elapsed.\n *\n * @param resumePoint - {@link WaitState.nextUpdate} for the `Update` point (which also serves the\n * timed, predicate, handle, and promise waits) or {@link WaitState.fixedUpdate} for the\n * post-fixed-step point.\n * @param deltaTime - Scaled seconds this frame.\n * @param unscaledDeltaTime - Unscaled seconds this frame.\n * @returns How many coroutines were resumed.\n */\n #walk(resumePoint: WaitState, deltaTime: number, unscaledDeltaTime: number): number {\n const records = this.#records;\n // The length is snapshotted, not the array: a coroutine started by another coroutine's\n // resumption first runs at the next resume point, and nothing is allocated to arrange that.\n const count = records.length;\n let resumed = 0;\n const isFixedPoint = resumePoint === WaitState.fixedUpdate;\n this.#walkDepth += 1;\n for (let index = 0; index < count; index += 1) {\n const record = records[index];\n if (record === undefined || record.routine === null || record.isPaused || record.owner.isDestroyed) {\n continue;\n }\n if (isFixedPoint !== (record.wait === WaitState.fixedUpdate)) {\n continue;\n }\n if (isFixedPoint || this.#isElapsed(record, deltaTime, unscaledDeltaTime)) {\n resumed += 1;\n this.#advance(record);\n }\n }\n this.#walkDepth -= 1;\n if (this.#walkDepth === 0 && this.#deadCount > 0) {\n this.#compact();\n }\n return resumed;\n }\n\n /**\n * Decides whether a coroutine's wait has elapsed at the `Update` resume point, advancing the\n * timed waits as a side effect.\n *\n * @param record - The suspended coroutine.\n * @param deltaTime - Scaled seconds this frame.\n * @param unscaledDeltaTime - Unscaled seconds this frame.\n * @returns `true` when the coroutine should be resumed now.\n */\n #isElapsed(record: CoroutineRecord, deltaTime: number, unscaledDeltaTime: number): boolean {\n switch (record.wait) {\n case WaitState.nextUpdate: {\n return true;\n }\n case WaitState.seconds: {\n record.remaining -= deltaTime;\n return record.remaining <= record.tolerance;\n }\n case WaitState.secondsRealtime: {\n record.remaining -= unscaledDeltaTime;\n return record.remaining <= record.tolerance;\n }\n case WaitState.until: {\n return this.#test(record) === true;\n }\n case WaitState.whileTrue: {\n return this.#test(record) === false;\n }\n case WaitState.handle: {\n return record.awaited?.isDone === true;\n }\n case WaitState.promise: {\n if (!record.isSettled) {\n return false;\n }\n record.isSettled = false;\n if (!record.isRejected) {\n record.resumeValue = record.settled;\n record.settled = null;\n }\n return true;\n }\n case WaitState.fixedUpdate: {\n return false;\n }\n default: {\n return assertNever(record.wait, \"coroutine wait state\");\n }\n }\n }\n\n /**\n * Evaluates a `waitUntil`/`waitWhile` predicate, guarded.\n *\n * @param record - The suspended coroutine.\n * @returns The predicate's result, or `null` when it threw — in which case the coroutine has\n * already been reported and cancelled.\n */\n #test(record: CoroutineRecord): boolean | null {\n const predicate = record.predicate;\n if (predicate === null) {\n return true;\n }\n const frameState = this.#frameState;\n frameState.beginCallback();\n try {\n return predicate();\n } catch (error) {\n this.#report(error, record.owner);\n this.#finish(record);\n return null;\n } finally {\n frameState.endCallback();\n }\n }\n\n /**\n * Drives one coroutine forward by one segment and records what it yielded.\n *\n * @param record - The coroutine to advance.\n */\n #advance(record: CoroutineRecord): void {\n const routine = record.routine;\n if (routine === null) {\n return;\n }\n const frameState = this.#frameState;\n frameState.beginCallback();\n let result: IteratorResult<CoroutineYield, void>;\n try {\n if (record.isRejected) {\n record.isRejected = false;\n const reason = record.settled;\n record.settled = null;\n result = routine.throw(reason);\n } else {\n const value = record.resumeValue;\n record.resumeValue = undefined;\n result = routine.next(value);\n }\n } catch (error) {\n this.#report(error, record.owner);\n this.#finish(record);\n return;\n } finally {\n frameState.endCallback();\n }\n if (result.done === true) {\n this.#finish(record);\n return;\n }\n this.#applyYield(record, result.value);\n }\n\n /**\n * Interprets what a coroutine yielded and files the matching wait.\n *\n * @param record - The coroutine that yielded.\n * @param yielded - The yielded value.\n */\n #applyYield(record: CoroutineRecord, yielded: CoroutineYield): void {\n record.predicate = null;\n record.awaited = null;\n if (yielded === null || yielded === undefined) {\n record.wait = WaitState.nextUpdate;\n return;\n }\n if (\"kind\" in yielded) {\n this.#applyWait(record, yielded);\n return;\n }\n if (\"then\" in yielded) {\n this.#awaitPromise(record, yielded);\n return;\n }\n record.wait = WaitState.handle;\n record.awaited = yielded;\n }\n\n /**\n * Files a {@link WaitInstruction}.\n *\n * @param record - The coroutine that yielded it.\n * @param instruction - The instruction built by `waitSeconds` and friends.\n */\n #applyWait(record: CoroutineRecord, instruction: WaitInstruction): void {\n switch (instruction.kind) {\n case \"seconds\": {\n record.wait = WaitState.seconds;\n record.remaining = instruction.seconds ?? 0;\n record.tolerance = Math.abs(record.remaining) * WAIT_TOLERANCE;\n return;\n }\n case \"secondsRealtime\": {\n record.wait = WaitState.secondsRealtime;\n record.remaining = instruction.seconds ?? 0;\n record.tolerance = Math.abs(record.remaining) * WAIT_TOLERANCE;\n return;\n }\n case \"fixedUpdate\": {\n record.wait = WaitState.fixedUpdate;\n return;\n }\n case \"until\": {\n record.wait = WaitState.until;\n record.predicate = instruction.predicate ?? null;\n return;\n }\n case \"while\": {\n record.wait = WaitState.whileTrue;\n record.predicate = instruction.predicate ?? null;\n return;\n }\n default: {\n assertNever(instruction.kind, \"coroutine wait instruction\");\n }\n }\n }\n\n /**\n * Bridges a promise into the frame (ADR-0010): the continuation records the outcome and the\n * scheduler resumes the coroutine at the first `Update` after that.\n *\n * @param record - The coroutine that yielded the promise.\n * @param promise - The promise it yielded.\n */\n #awaitPromise(record: CoroutineRecord, promise: PromiseLike<unknown>): void {\n record.wait = WaitState.promise;\n record.isSettled = false;\n record.isRejected = false;\n record.settled = null;\n const generation = record.generation;\n // Deliberately not awaited (coding standards §8): this is bookkeeping, not control flow. The\n // generation check is what makes a settlement that arrives after the coroutine was cancelled —\n // by `stop`, by destruction, or by app disposal — do nothing at all (§5).\n void Promise.resolve(promise).then(\n (value: unknown): void => {\n if (record.generation === generation) {\n record.isSettled = true;\n record.settled = value;\n }\n },\n (reason: unknown): void => {\n if (record.generation === generation) {\n record.isSettled = true;\n record.isRejected = true;\n record.settled = reason;\n }\n },\n );\n }\n\n /**\n * Finishes every coroutine one script owns.\n *\n * @param owner - The owning script.\n */\n #finishOwned(owner: Script): void {\n const owned = this.#byOwner.get(owner);\n if (owned === undefined) {\n return;\n }\n // A copy of the length only: `#finish` tombstones rather than splicing, so the list is stable.\n for (let index = 0; index < owned.length; index += 1) {\n const record = owned[index];\n if (record !== undefined && record.routine !== null) {\n this.#finish(record);\n }\n }\n }\n\n /**\n * Retires a coroutine: its generator is dropped, its handle reports `isDone`, and any promise it\n * was waiting on is detached.\n *\n * @param record - The coroutine to retire.\n */\n #finish(record: CoroutineRecord): void {\n if (record.routine === null) {\n return;\n }\n record.routine = null;\n record.generation += 1;\n record.predicate = null;\n record.awaited = null;\n record.settled = null;\n record.resumeValue = undefined;\n record.handle.isRunning = false;\n record.handle.isDone = true;\n record.handle.record = null;\n this.#deadCount += 1;\n if (this.#walkDepth === 0) {\n this.#compact();\n }\n }\n\n /** Removes retired coroutines from the schedule and from their owner's list. */\n #compact(): void {\n const records = this.#records;\n let write = 0;\n for (let read = 0; read < records.length; read += 1) {\n const record = records[read];\n if (record === undefined) {\n continue;\n }\n if (record.routine === null) {\n this.#detach(record);\n continue;\n }\n records[write] = record;\n write += 1;\n }\n records.length = write;\n this.#deadCount = 0;\n }\n\n /**\n * Removes a retired coroutine from its owner's list, dropping the list when it empties so the map\n * does not grow with every script that ever ran one.\n *\n * @param record - The retired coroutine.\n */\n #detach(record: CoroutineRecord): void {\n const owned = this.#byOwner.get(record.owner);\n if (owned === undefined) {\n return;\n }\n const at = owned.indexOf(record);\n if (at >= 0) {\n const last = owned.length - 1;\n const moved = owned[last];\n if (at !== last && moved !== undefined) {\n owned[at] = moved;\n }\n owned.pop();\n }\n if (owned.length === 0) {\n this.#byOwner.delete(record.owner);\n }\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\n\n/**\n * A named set of numeric counters owned by one subsystem — `render`, `physics`, `assets`, `input`,\n * `audio`, `twoD`, `animation` (`docs/architecture/15-devtools-and-diagnostics.md` §3).\n *\n * @remarks\n * Counter names are resolved to array indices once, at registration. Per-frame code holds the index\n * and never performs a string-keyed lookup (coding standards §7).\n *\n * @example\n * ```ts\n * const counters = app.diagnostics.registerGroup(\"render\", [\"drawCalls\", \"triangles\"]);\n * const drawCalls = counters.index(\"drawCalls\");\n * // …per frame…\n * counters.set(drawCalls, scene.drawCallCount);\n * ```\n *\n * @public\n */\nexport interface DiagnosticsGroup {\n /** The group name, unique within one {@link Diagnostics}. */\n readonly name: string;\n /** The counter names in index order. */\n readonly counterNames: readonly string[];\n\n /**\n * Resolves a counter name to its index. Call it at registration or `awake`, never per frame.\n *\n * @param counter - The counter name.\n * @returns The index to pass to {@link DiagnosticsGroup.get}, `set`, and `add`.\n * @throws IgnifxError with code `IGX-1504` when the group has no such counter.\n */\n index(counter: string): number;\n\n /**\n * Reads a counter.\n *\n * @param index - The index from {@link DiagnosticsGroup.index}.\n * @returns The current value, or `0` when the index is out of range.\n */\n get(index: number): number;\n\n /**\n * Replaces a counter's value. Out-of-range indices are ignored.\n *\n * @param index - The index from {@link DiagnosticsGroup.index}.\n * @param value - The new value.\n */\n set(index: number, value: number): void;\n\n /**\n * Adds to a counter. Out-of-range indices are ignored.\n *\n * @param index - The index from {@link DiagnosticsGroup.index}.\n * @param delta - The amount to add.\n */\n add(index: number, delta: number): void;\n\n /** Zeroes every counter in the group. */\n reset(): void;\n}\n\nclass DiagnosticsGroupImpl implements DiagnosticsGroup {\n readonly name: string;\n readonly counterNames: readonly string[];\n readonly #values: Float64Array;\n readonly #indices: ReadonlyMap<string, number>;\n\n constructor(name: string, counterNames: readonly string[]) {\n this.name = name;\n const names = counterNames.slice();\n this.counterNames = names;\n this.#values = new Float64Array(names.length);\n const indices = new Map<string, number>();\n let index = 0;\n for (const counter of names) {\n indices.set(counter, index);\n index += 1;\n }\n this.#indices = indices;\n }\n\n index(counter: string): number {\n const index = this.#indices.get(counter);\n if (index === undefined) {\n throw new IgnifxError(\n CoreErrorCode.unknownDiagnosticsCounter,\n `${counter} is not a counter of the diagnostics group ${this.name}.`,\n {\n context: { counter, group: this.name },\n hint: \"Declare every counter name when the group is registered.\",\n },\n );\n }\n return index;\n }\n\n get(index: number): number {\n // `noUncheckedIndexedAccess` widens the read; an out-of-range counter reads as zero by design.\n return this.#values[index] ?? 0;\n }\n\n set(index: number, value: number): void {\n if (index >= 0 && index < this.#values.length) {\n this.#values[index] = value;\n }\n }\n\n add(index: number, delta: number): void {\n this.set(index, this.get(index) + delta);\n }\n\n reset(): void {\n this.#values.fill(0);\n }\n}\n\n/**\n * Creates a counter group. {@link Diagnostics.registerGroup} is the entry point games use; this\n * factory exists so a group can be built and tested on its own.\n *\n * @param name - The group name.\n * @param counterNames - The counter names, in the order their indices are assigned.\n * @returns The group.\n *\n * @public\n */\nexport function createDiagnosticsGroup(name: string, counterNames: readonly string[]): DiagnosticsGroup {\n return new DiagnosticsGroupImpl(name, counterNames);\n}\n","/**\n * The per-frame counters the loop publishes (`docs/architecture/01-lifecycle-and-time.md` §9) and\n * the fixed-size CPU timing array they carry.\n */\n\n/**\n * How many update phases the frame loop times. The kernel owns the `Phase` names and their ordinals;\n * diagnostics only needs to know how many slots to preallocate, which keeps the two modules\n * independent.\n *\n * @public\n */\nexport const PHASE_COUNT = 6;\n\n/**\n * A slot in {@link FrameSample.cpuMs}. The kernel's `Phase` ordinals index this array.\n *\n * @public\n */\nexport type PhaseIndex = 0 | 1 | 2 | 3 | 4 | 5;\n\n/**\n * One frame's counters.\n *\n * @remarks\n * The numeric fields are mutable on purpose: the frame loop writes them in place so that publishing\n * diagnostics costs no allocation (coding standards §7). Everything outside the loop treats a\n * sample as read-only, and history samples are read through\n * {@link Diagnostics.readFrame} into a caller-owned sample.\n *\n * @public\n */\nexport interface FrameSample {\n /** The monotonically increasing frame number, starting at 1. */\n frame: number;\n /** The wall-clock delta the loop was handed, before clamping, in milliseconds. */\n rawDeltaMs: number;\n /** How much of `rawDeltaMs` was discarded by the maximum-delta clamp, in milliseconds. */\n droppedMs: number;\n /** How many fixed steps ran this frame. */\n fixedSteps: number;\n /** How many scripts received `update` this frame. */\n scriptsUpdated: number;\n /** How many coroutines were resumed this frame. */\n coroutinesResumed: number;\n /** How many entities and components were destroyed in this frame's flush. */\n destroyed: number;\n /**\n * CPU milliseconds per phase, indexed by {@link PhaseIndex}. Always {@link PHASE_COUNT} long and\n * only filled in development builds.\n */\n readonly cpuMs: Float64Array;\n}\n\n/**\n * Allocates a frame sample with every counter at zero. Call it once, outside the frame loop — the\n * `out` parameter of {@link Diagnostics.readFrame} exists so that reading history never allocates.\n *\n * @returns A zeroed sample.\n *\n * @example\n * ```ts\n * const sample = createFrameSample();\n * for (let index = 0; index < app.diagnostics.historyLength; index += 1) {\n * app.diagnostics.readFrame(index, sample);\n * graph.push(sample.rawDeltaMs);\n * }\n * ```\n *\n * @public\n */\nexport function createFrameSample(): FrameSample {\n return {\n frame: 0,\n rawDeltaMs: 0,\n droppedMs: 0,\n fixedSteps: 0,\n scriptsUpdated: 0,\n coroutinesResumed: 0,\n destroyed: 0,\n cpuMs: new Float64Array(PHASE_COUNT),\n };\n}\n\n/**\n * Zeroes every counter of a sample in place, reusing its `cpuMs` array.\n *\n * @param sample - The sample to reset.\n * @returns The same sample, so it can be used as an expression.\n *\n * @public\n */\nexport function resetFrameSample(sample: FrameSample): FrameSample {\n sample.frame = 0;\n sample.rawDeltaMs = 0;\n sample.droppedMs = 0;\n sample.fixedSteps = 0;\n sample.scriptsUpdated = 0;\n sample.coroutinesResumed = 0;\n sample.destroyed = 0;\n sample.cpuMs.fill(0);\n return sample;\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { createDiagnosticsGroup, type DiagnosticsGroup } from \"./diagnostics-group.js\";\nimport { createFrameSample, PHASE_COUNT, resetFrameSample, type FrameSample } from \"./frame-sample.js\";\n\n/**\n * How many frames of history {@link Diagnostics} keeps by default — five seconds at 60 fps, which is\n * what the devtools graphs plot (`docs/architecture/15-devtools-and-diagnostics.md` §3).\n *\n * @public\n */\nexport const FRAME_HISTORY_LENGTH = 300;\n\n/**\n * A timing scope opened by {@link Diagnostics.profile}. Ending it twice is a no-op.\n *\n * @remarks\n * Scopes are pooled per nesting depth, so opening one allocates nothing after the first frame, and\n * outside development builds `profile` returns a shared scope that does nothing at all.\n *\n * @public\n */\nexport interface ProfileScope {\n /**\n * How long the scope was open, in milliseconds of the diagnostics clock. Valid between\n * {@link ProfileScope.end} and the next {@link Diagnostics.profile} call at the same nesting\n * depth, because scopes are pooled. Always `0` outside development builds.\n */\n readonly durationMs: number;\n\n /** Closes the scope and, in development, records a `performance.measure` entry. */\n end(): void;\n}\n\n/**\n * Options for the {@link Diagnostics} constructor.\n *\n * @public\n */\nexport interface DiagnosticsOptions {\n /**\n * Whether this is a development build. Per-phase CPU timings and `performance.mark`/`measure`\n * entries are only produced when it is `true`. Defaults to `false`.\n */\n readonly development?: boolean;\n /**\n * The clock used for profile scopes, in milliseconds. Defaults to `performance.now` when the host\n * has it and `Date.now` otherwise; tests pass a counter so timings are deterministic.\n */\n readonly now?: () => number;\n /** How many frames of history to keep. Defaults to {@link FRAME_HISTORY_LENGTH}. */\n readonly historyLength?: number;\n}\n\n/**\n * Picks the default clock: the high-resolution monotonic one when the host exposes it.\n *\n * @returns A function returning milliseconds.\n */\nfunction defaultNow(): () => number {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return () => performance.now();\n }\n return () => Date.now();\n}\n\n/**\n * Reads one slot of a preallocated array.\n *\n * @remarks\n * `noUncheckedIndexedAccess` widens every typed-array read to `number | undefined`. Each index here\n * is derived from the array's own length, so the fallback is unreachable; funnelling the reads\n * through one helper keeps that concession in a single place.\n *\n * @param array - The array to read.\n * @param index - The slot, always in range.\n * @returns The stored value.\n */\nfunction readSlot(array: Float64Array, index: number): number {\n return array[index] ?? 0;\n}\n\n/**\n * Reports whether the host implements the User Timing entries `profile` writes.\n *\n * @returns `true` when `performance.mark` and `performance.measure` are callable.\n */\nfunction hasUserTiming(): boolean {\n return (\n typeof performance !== \"undefined\" &&\n typeof performance.mark === \"function\" &&\n typeof performance.measure === \"function\"\n );\n}\n\nclass ProfileScopeImpl implements ProfileScope {\n name = \"\";\n depth = 0;\n startMs = 0;\n durationMs = 0;\n isActive = false;\n readonly #onEnd: (scope: ProfileScopeImpl) => void;\n\n constructor(onEnd: (scope: ProfileScopeImpl) => void) {\n this.#onEnd = onEnd;\n }\n\n end(): void {\n if (!this.isActive) {\n return;\n }\n this.isActive = false;\n this.#onEnd(this);\n }\n}\n\n/** The scope handed out when profiling is off; ending it does nothing. */\nconst INACTIVE_SCOPE: ProfileScope = {\n durationMs: 0,\n end(): void {\n // Profiling is a development-only facility; outside development there is nothing to record.\n },\n};\n\n/**\n * The frame-sampled counters reached as `app.diagnostics`\n * (`docs/architecture/15-devtools-and-diagnostics.md` §3).\n *\n * @remarks\n * Nothing on the per-frame path allocates: {@link Diagnostics.frame} is one long-lived object the\n * loop writes in place, the history is a preallocated structure-of-arrays ring buffer, and counters\n * are typed arrays addressed by index (coding standards §7).\n *\n * @example\n * ```ts\n * const diagnostics = new Diagnostics({ development: true });\n * diagnostics.beginFrame(16.7);\n * diagnostics.frame.fixedSteps = 1;\n * diagnostics.endFrame();\n * diagnostics.readFrame(0, sample).fixedSteps; // 1\n * ```\n *\n * @public\n */\nexport class Diagnostics {\n /**\n * The frame being measured. The frame loop writes its counters in place; everything else reads\n * them. Values are reset by {@link Diagnostics.beginFrame}.\n */\n readonly frame: FrameSample = createFrameSample();\n\n /** Whether per-phase timings and User Timing entries are being recorded. */\n readonly isDevelopment: boolean;\n\n /** How many frames the history can hold. */\n readonly historyCapacity: number;\n\n readonly #now: () => number;\n readonly #hasUserTiming: boolean;\n readonly #groups: DiagnosticsGroup[] = [];\n readonly #groupsByName = new Map<string, DiagnosticsGroup>();\n readonly #scopePool: ProfileScopeImpl[] = [];\n #scopeDepth = 0;\n\n readonly #frameIds: Float64Array;\n readonly #rawDeltaMs: Float64Array;\n readonly #droppedMs: Float64Array;\n readonly #fixedSteps: Float64Array;\n readonly #scriptsUpdated: Float64Array;\n readonly #coroutinesResumed: Float64Array;\n readonly #destroyed: Float64Array;\n readonly #cpuMs: Float64Array;\n #head = 0;\n #historyLength = 0;\n #frameCounter = 0;\n\n readonly #endScope = (scope: ProfileScopeImpl): void => {\n if (scope.depth < this.#scopeDepth) {\n this.#scopeDepth = scope.depth;\n }\n scope.durationMs = this.#now() - scope.startMs;\n if (this.#hasUserTiming) {\n const mark = markName(scope.name, scope.depth);\n performance.measure(`ignifx:${scope.name}`, mark);\n performance.clearMarks(mark);\n }\n };\n\n /**\n * Creates the diagnostics service of one app.\n *\n * @param options - Development flag, clock, and history length.\n */\n constructor(options?: DiagnosticsOptions) {\n this.isDevelopment = options?.development ?? false;\n this.#now = options?.now ?? defaultNow();\n this.#hasUserTiming = this.isDevelopment && hasUserTiming();\n const capacity = Math.max(1, Math.floor(options?.historyLength ?? FRAME_HISTORY_LENGTH));\n this.historyCapacity = capacity;\n this.#frameIds = new Float64Array(capacity);\n this.#rawDeltaMs = new Float64Array(capacity);\n this.#droppedMs = new Float64Array(capacity);\n this.#fixedSteps = new Float64Array(capacity);\n this.#scriptsUpdated = new Float64Array(capacity);\n this.#coroutinesResumed = new Float64Array(capacity);\n this.#destroyed = new Float64Array(capacity);\n this.#cpuMs = new Float64Array(capacity * PHASE_COUNT);\n }\n\n /**\n * How many frames of history are currently recorded, never more than the capacity.\n *\n * @returns The number of retained frames.\n */\n get historyLength(): number {\n return this.#historyLength;\n }\n\n /**\n * Every registered counter group, in registration order.\n *\n * @returns The live list of groups.\n */\n get groups(): readonly DiagnosticsGroup[] {\n return this.#groups;\n }\n\n /**\n * Starts a new frame: zeroes {@link Diagnostics.frame}, assigns the next frame number, and records\n * the raw delta.\n *\n * @param rawDeltaMs - The wall-clock delta handed to the loop, before clamping, in milliseconds.\n */\n beginFrame(rawDeltaMs: number): void {\n const frame = this.frame;\n resetFrameSample(frame);\n this.#frameCounter += 1;\n frame.frame = this.#frameCounter;\n frame.rawDeltaMs = rawDeltaMs;\n }\n\n /** Copies {@link Diagnostics.frame} into the history ring buffer, overwriting the oldest entry. */\n endFrame(): void {\n const slot = this.#head;\n const frame = this.frame;\n this.#frameIds[slot] = frame.frame;\n this.#rawDeltaMs[slot] = frame.rawDeltaMs;\n this.#droppedMs[slot] = frame.droppedMs;\n this.#fixedSteps[slot] = frame.fixedSteps;\n this.#scriptsUpdated[slot] = frame.scriptsUpdated;\n this.#coroutinesResumed[slot] = frame.coroutinesResumed;\n this.#destroyed[slot] = frame.destroyed;\n const base = slot * PHASE_COUNT;\n for (let phase = 0; phase < PHASE_COUNT; phase += 1) {\n this.#cpuMs[base + phase] = readSlot(frame.cpuMs, phase);\n }\n this.#head = (slot + 1) % this.historyCapacity;\n if (this.#historyLength < this.historyCapacity) {\n this.#historyLength += 1;\n }\n }\n\n /**\n * Reads a recorded frame into a caller-owned sample, so plotting the whole history allocates\n * nothing.\n *\n * @param offset - `0` is the most recently ended frame, `historyLength - 1` the oldest retained.\n * @param out - The sample to fill; build it with `createFrameSample()`.\n * @returns The same `out` sample, zeroed when the offset is out of range.\n *\n * @example\n * ```ts\n * const sample = createFrameSample();\n * diagnostics.readFrame(0, sample); // the frame that just ended\n * ```\n */\n readFrame(offset: number, out: FrameSample): FrameSample {\n resetFrameSample(out);\n if (offset < 0 || offset >= this.#historyLength) {\n return out;\n }\n const capacity = this.historyCapacity;\n const slot = (this.#head - 1 - offset + capacity * 2) % capacity;\n out.frame = readSlot(this.#frameIds, slot);\n out.rawDeltaMs = readSlot(this.#rawDeltaMs, slot);\n out.droppedMs = readSlot(this.#droppedMs, slot);\n out.fixedSteps = readSlot(this.#fixedSteps, slot);\n out.scriptsUpdated = readSlot(this.#scriptsUpdated, slot);\n out.coroutinesResumed = readSlot(this.#coroutinesResumed, slot);\n out.destroyed = readSlot(this.#destroyed, slot);\n const base = slot * PHASE_COUNT;\n for (let phase = 0; phase < PHASE_COUNT; phase += 1) {\n out.cpuMs[phase] = readSlot(this.#cpuMs, base + phase);\n }\n return out;\n }\n\n /** Drops every recorded frame and resets the frame counter. */\n clearHistory(): void {\n this.#head = 0;\n this.#historyLength = 0;\n this.#frameCounter = 0;\n }\n\n /**\n * Registers a subsystem's counter group.\n *\n * @param name - The group name, unique within this app.\n * @param counterNames - The counter names, in the order their indices are assigned.\n * @returns The group, whose indices are resolved once with {@link DiagnosticsGroup.index}.\n * @throws IgnifxError with code `IGX-1503` when the name is already registered.\n */\n registerGroup(name: string, counterNames: readonly string[]): DiagnosticsGroup {\n if (this.#groupsByName.has(name)) {\n throw new IgnifxError(\n CoreErrorCode.duplicateDiagnosticsGroup,\n `The diagnostics group ${name} is already registered.`,\n { context: { group: name }, hint: \"Register one group per subsystem and keep a reference to it.\" },\n );\n }\n const group = createDiagnosticsGroup(name, counterNames);\n this.#groups.push(group);\n this.#groupsByName.set(name, group);\n return group;\n }\n\n /**\n * Looks a counter group up by name.\n *\n * @param name - The group name.\n * @returns The group, or `null` when no subsystem registered it — an absent group is expected\n * absence, not a failure (coding standards §5.5).\n */\n group(name: string): DiagnosticsGroup | null {\n return this.#groupsByName.get(name) ?? null;\n }\n\n /**\n * Opens a timing scope. In development builds it writes a `performance.mark`/`measure` pair that\n * shows up in browser profilers; outside development it is free\n * (`docs/architecture/15-devtools-and-diagnostics.md` §6).\n *\n * @param name - The scope name, shown in the profiler.\n * @returns A scope to `end()`; scopes must be ended in the order they were opened.\n *\n * @example\n * ```ts\n * const scope = app.diagnostics.profile(\"physics.step\");\n * stepPhysics();\n * scope.end();\n * ```\n */\n profile(name: string): ProfileScope {\n if (!this.isDevelopment) {\n return INACTIVE_SCOPE;\n }\n const depth = this.#scopeDepth;\n let scope = this.#scopePool[depth];\n if (scope === undefined) {\n scope = new ProfileScopeImpl(this.#endScope);\n this.#scopePool.push(scope);\n }\n this.#scopeDepth = depth + 1;\n scope.name = name;\n scope.depth = depth;\n scope.startMs = this.#now();\n scope.durationMs = 0;\n scope.isActive = true;\n if (this.#hasUserTiming) {\n performance.mark(markName(name, depth));\n }\n return scope;\n }\n}\n\n/**\n * Builds the User Timing mark name for a scope, keyed by depth so that nesting two scopes with the\n * same name still pairs each mark with the right measure.\n *\n * @param name - The scope name.\n * @param depth - The nesting depth of the scope.\n * @returns The mark name.\n */\nfunction markName(name: string, depth: number): string {\n return `ignifx:${name}:${depth}`;\n}\n","import { CORE_ERROR_MESSAGES, CoreErrorCode, isValidErrorCode, type ErrorCode } from \"./error-codes.js\";\nimport { IgnifxError } from \"./ignifx-error.js\";\n\n/**\n * What the registry knows about one code.\n *\n * @public\n */\nexport interface ErrorCodeDescription {\n /** The code itself. */\n readonly code: ErrorCode;\n /** The one-line message template; context keys appear in braces. */\n readonly message: string;\n /** The extension that owns the code (`\"@ignifx/core\"` for the codes in `CoreErrorCode`). */\n readonly owner: string;\n}\n\n/**\n * The per-app table of every diagnostic code the running game can produce. Devtools resolves codes\n * to messages through it, and `ExtensionContext.registerErrorCodes` writes to it.\n *\n * @remarks\n * There is one registry per {@link App}, never a module-level one (`CONSTITUTION.md` §3.5, §3.6):\n * two apps in one test process must not see each other's extensions.\n *\n * @public\n */\nexport interface ErrorCodeRegistry {\n /**\n * Adds a block of codes.\n *\n * @param codes - A map of `IGX-####` code to one-line message template.\n * @param owner - The extension name recorded as the owner of every code in the block.\n * @throws IgnifxError with code `IGX-1502` when a key is not a valid code, or `IGX-1501` when a\n * code is already registered.\n */\n register(codes: Readonly<Record<string, string>>, owner: string): void;\n\n /**\n * Looks a code up.\n *\n * @param code - The code to describe.\n * @returns The description, or `null` when the code was never registered — an unknown code is an\n * expected absence, not a failure (coding standards §5.5).\n */\n describe(code: string): ErrorCodeDescription | null;\n\n /**\n * Reports whether a code is known.\n *\n * @param code - The code to test.\n * @returns `true` when the code has been registered.\n */\n isRegistered(code: string): boolean;\n}\n\n/** The owner recorded for the codes `@ignifx/core` ships with. */\nconst CORE_OWNER = \"@ignifx/core\";\n\nclass ErrorCodeRegistryImpl implements ErrorCodeRegistry {\n readonly #entries = new Map<string, ErrorCodeDescription>();\n\n register(codes: Readonly<Record<string, string>>, owner: string): void {\n for (const entry of Object.entries(codes)) {\n const code = entry[0];\n if (!isValidErrorCode(code)) {\n throw new IgnifxError(\n CoreErrorCode.malformedErrorCode,\n `${code} is not a valid IGX-#### code in a known range.`,\n { context: { code, owner }, hint: \"Codes are IGX- plus four digits in an allocated subsystem range.\" },\n );\n }\n const existing = this.#entries.get(code);\n if (existing !== undefined) {\n throw new IgnifxError(CoreErrorCode.duplicateErrorCode, `The error code ${code} is already registered.`, {\n context: { code, owner, existingOwner: existing.owner },\n hint: \"Third-party extensions allocate codes in the IGX-9### range.\",\n });\n }\n this.#entries.set(code, { code, message: entry[1], owner });\n }\n }\n\n describe(code: string): ErrorCodeDescription | null {\n return this.#entries.get(code) ?? null;\n }\n\n isRegistered(code: string): boolean {\n return this.#entries.has(code);\n }\n}\n\n/**\n * Creates an error code registry pre-loaded with the codes `@ignifx/core` owns.\n *\n * @returns A registry owned by one app.\n *\n * @example\n * ```ts\n * const registry = createErrorCodeRegistry();\n * registry.register({ \"IGX-9001\": \"The {thing} was not spawned.\" }, \"game/spawner\");\n * registry.describe(\"IGX-0701\")?.message; // \"WebGPU is not available in this environment.\"\n * ```\n *\n * @public\n */\nexport function createErrorCodeRegistry(): ErrorCodeRegistry {\n const registry = new ErrorCodeRegistryImpl();\n registry.register(CORE_ERROR_MESSAGES, CORE_OWNER);\n return registry;\n}\n","import type { AssetLoader, AssetTypeDefinition, Assets } from \"../assets/types.js\";\nimport type { ConcreteComponentType } from \"../component/component-type.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { Diagnostics } from \"../diagnostics/diagnostics.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { PhysicsCallbackName } from \"../lifecycle/callbacks.js\";\nimport type { LiteEngine, LiteScene } from \"../lite/scene.js\";\nimport type { Logger } from \"../log/logger.js\";\nimport type { PlatformInfo } from \"../platform/platform.js\";\nimport type { Renderer, RenderingFeature } from \"../render/renderer.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\nimport type { Schema } from \"../schema/types.js\";\nimport type { Script } from \"../script/script.js\";\nimport type { Signal, SignalLike } from \"../signal/signal.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * The contracts the kernel and the runtime agree on: frame phases, the clock, systems, extensions,\n * services, coroutines, and the `App` surface a script sees through `this.app`\n * (`docs/architecture/01-lifecycle-and-time.md`, `03-scripting-and-components.md` §6–§7,\n * `04-extensions.md` §1).\n *\n * The module declares types and two frozen constant tables only — no classes and no behaviour — so\n * that the scene graph and the runtime can be written against it independently.\n */\n\n/**\n * The ordered frame phases (`docs/architecture/01-lifecycle-and-time.md` §3). The ordinals are the\n * order the frame function walks them in, and they index the per-phase CPU timings in\n * `FrameSample.cpuMs`.\n *\n * @remarks\n * `EndOfFrame` is ordinal `0` because the work it carries is drained at the *top* of the next\n * frame, before the clock advances; the name describes when the work was queued, the ordinal\n * describes when it runs.\n *\n * @example\n * ```ts\n * ctx.registerSystem(new SpriteSyncSystem(), { phase: Phase.PreRender, order: 100 });\n * ```\n *\n * @public\n */\nexport const Phase = {\n /** Deferred signal deliveries and end-of-frame systems, drained at the start of the next frame. */\n EndOfFrame: 0,\n /** Input polling and asset delivery, before any script callback. */\n PreUpdate: 1,\n /** The fixed-timestep simulation loop: `fixedUpdate`, physics, collision dispatch. */\n FixedUpdate: 2,\n /** `update` on every enabled script, then coroutine resumption. */\n Update: 3,\n /** Animation, state machines, and tweens, between `update` and `lateUpdate`. */\n PostUpdate: 4,\n /** Render synchronisation: interpolation, sprite and camera sync, audio, diagnostics. */\n PreRender: 5,\n} as const;\n\n/**\n * The union of the frame phases.\n *\n * @public\n */\nexport type Phase = (typeof Phase)[keyof typeof Phase];\n\n/**\n * Every phase in frame order, for loops that walk them all.\n *\n * @public\n */\nexport const PHASES: readonly Phase[] = Object.freeze([\n Phase.EndOfFrame,\n Phase.PreUpdate,\n Phase.FixedUpdate,\n Phase.Update,\n Phase.PostUpdate,\n Phase.PreRender,\n]);\n\n/**\n * The display name of each phase, indexed by its ordinal. Used by diagnostics and error messages.\n *\n * @public\n */\nexport const PHASE_NAMES: readonly string[] = Object.freeze([\n \"EndOfFrame\",\n \"PreUpdate\",\n \"FixedUpdate\",\n \"Update\",\n \"PostUpdate\",\n \"PreRender\",\n]);\n\n/**\n * The clock reached as `app.time` (`docs/architecture/01-lifecycle-and-time.md` §2). Every value is\n * in **seconds** unless its name ends in `Ms`.\n *\n * @example\n * ```ts\n * class Spin extends Script {\n * update(dt: number): void {\n * // `dt` is the argument, never `app.time.deltaTime`, inside a callback.\n * this.transform.rotate({ x: 0, y: 90 * dt, z: 0 });\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface Time {\n /** Scaled seconds since the previous frame; what `update` and `lateUpdate` receive. */\n readonly deltaTime: number;\n /** Wall-clock frame delta after the {@link Time.maximumDeltaTime} clamp, unscaled. */\n readonly unscaledDeltaTime: number;\n /** The size of one fixed step; what `fixedUpdate` receives. Defaults to `1 / 60`. */\n fixedDeltaTime: number;\n /** Multiplier applied to {@link Time.unscaledDeltaTime}; `0` freezes scaled time. Defaults to `1`. */\n timeScale: number;\n /** Upper clamp on one frame's delta, in seconds. Defaults to `0.1`. */\n maximumDeltaTime: number;\n /** Scaled seconds since `app.start()`. */\n readonly time: number;\n /** Unscaled seconds since `app.start()`. */\n readonly unscaledTime: number;\n /** Scaled seconds advanced by fixed steps so far. */\n readonly fixedTime: number;\n /** Wall-clock seconds since the app was created, unaffected by pause or time scale. */\n readonly realtimeSinceStartup: number;\n /** How many frames have started. Starts at `0`. */\n readonly frameCount: number;\n /** `true` while `fixedUpdate` and physics run. */\n readonly inFixedStep: boolean;\n /** `accumulator / fixedDeltaTime` after the fixed loop, in `[0, 1)`; the interpolation alpha. */\n readonly fixedStepAlpha: number;\n /** When `true`, fixed steps stop and only `updateWhenPaused` scripts receive `update`. */\n paused: boolean;\n}\n\n/**\n * What a {@link System} is handed when its phase runs\n * (`docs/architecture/03-scripting-and-components.md` §6).\n *\n * @public\n */\nexport interface SystemContext {\n /** The world the system operates on. */\n readonly world: World;\n /** The app clock. */\n readonly time: Time;\n /** The phase currently running. */\n readonly phase: Phase;\n /** Seconds elapsed: `time.deltaTime`, or `time.fixedDeltaTime` inside the fixed loop. */\n readonly dt: number;\n}\n\n/**\n * Engine-level logic that runs once per phase over many components, registered by an extension\n * (`docs/architecture/03-scripting-and-components.md` §6). Systems are not attached to entities and\n * never call script callbacks themselves.\n *\n * @example\n * ```ts\n * class SpriteSyncSystem implements System {\n * readonly name = \"sprite-sync\";\n * update(ctx: SystemContext): void {\n * const sprites = ctx.world.components(SpriteRenderer);\n * for (let index = 0; index < sprites.length; index += 1) {\n * sprites[index]?.sync();\n * }\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface System {\n /** A unique, human-readable name used in diagnostics and error reports. */\n readonly name: string;\n /**\n * Runs the system's work for one phase.\n *\n * @param ctx - The world, clock, phase, and delta for this invocation.\n */\n update?(ctx: SystemContext): void;\n /**\n * Called once when the world the system belongs to has been created.\n *\n * @param world - The new world.\n */\n onWorldCreated?(world: World): void;\n /**\n * Called once when the world the system belongs to is being disposed.\n *\n * @param world - The world going away.\n */\n onWorldDisposed?(world: World): void;\n /** Releases resources the system owns. */\n dispose?(): void;\n}\n\n/**\n * The token a service is registered and looked up under\n * (`docs/architecture/04-extensions.md` §1). Either the service's own abstract class — the common\n * case, so `ctx.require(PhysicsService)` reads naturally — or a branded token from\n * {@link createServiceKey} for services that have no class of their own.\n *\n * @typeParam T - The service instance type the key stands for.\n *\n * @public\n */\nexport type ServiceKey<T> = ServiceClassKey<T> | ServiceNameKey<T>;\n\n/**\n * A service key that is a class: the constructor itself is the token.\n *\n * @typeParam T - The service instance type.\n *\n * @public\n */\nexport type ServiceClassKey<T> = abstract new (...args: never[]) => T;\n\n/**\n * A service key created from a name, for services that are plain objects rather than classes.\n *\n * @typeParam T - The service instance type. It is a compile-time marker only: `serviceOf` is never\n * assigned at runtime, and it is what makes two keys with different service types different types.\n *\n * @public\n */\nexport interface ServiceNameKey<T> {\n /** The name the key was created with, used in error messages. */\n readonly serviceName: string;\n /** Compile-time marker for the service type; never present at runtime. */\n readonly serviceOf?: T;\n}\n\n/**\n * Creates a named service key for a service that has no class to use as a token.\n *\n * @typeParam T - The service instance type the key stands for.\n * @param name - A unique, human-readable name, used in `IGX-0405` messages.\n * @returns The key. It is a plain frozen object, so it is safe at module scope.\n *\n * @example\n * ```ts\n * export const StorageService: ServiceKey<Storage> = createServiceKey<Storage>(\"storage\");\n * ctx.registerService(StorageService, new LocalStorage());\n * ```\n *\n * @public\n */\nexport function createServiceKey<T>(name: string): ServiceNameKey<T> {\n return Object.freeze({ serviceName: name });\n}\n\n/**\n * The per-app service table (`docs/architecture/04-extensions.md` §1). Extensions write to it\n * through `ExtensionContext.registerService`; scripts read from it.\n *\n * @public\n */\nexport interface ServiceRegistry {\n /**\n * Looks a service up, requiring it to be present.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key the service was registered under.\n * @returns The registered instance.\n * @throws IgnifxError with code `IGX-0405` when no extension registered the service.\n */\n get<T>(key: ServiceKey<T>): T;\n /**\n * Looks a service up, tolerating its absence — the pattern for game code that must work with or\n * without an optional extension.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key the service was registered under.\n * @returns The instance, or `null` when it is not registered.\n */\n tryGet<T>(key: ServiceKey<T>): T | null;\n /**\n * Reports whether a service is registered.\n *\n * @param key - The class or named key.\n * @returns `true` when an instance is registered under the key.\n */\n has(key: ServiceKey<unknown>): boolean;\n}\n\n/**\n * The `layers` project settings section (`docs/architecture/04-extensions.md` §5,\n * `02-scene-graph.md` §7).\n *\n * @public\n */\nexport interface LayersSettings {\n /** The project's layer names in declaration order. */\n readonly layers: readonly string[];\n}\n\n/**\n * The `sortingLayers` project settings section, consumed by the 2D toolkit.\n *\n * @public\n */\nexport interface SortingLayersSettings {\n /** The project's sorting-layer names, back to front. */\n readonly sortingLayers: readonly string[];\n}\n\n/**\n * The `time` project settings section (`docs/architecture/01-lifecycle-and-time.md` §2).\n *\n * @public\n */\nexport interface TimeSettings {\n /** The initial fixed step in seconds. Defaults to `1 / 60`. */\n readonly fixedDeltaTime?: number;\n /** The initial frame-delta clamp in seconds. Defaults to `0.1`. */\n readonly maximumDeltaTime?: number;\n /** The initial time scale. Defaults to `1`. */\n readonly timeScale?: number;\n}\n\n/**\n * Resolved project settings, reached as `app.settings`\n * (`docs/architecture/04-extensions.md` §5). Each section is validated against the schema the\n * owning extension registered.\n *\n * @public\n */\nexport interface AppSettings {\n /** The core `layers` section. */\n readonly layers: LayersSettings;\n /** The core `sortingLayers` section. */\n readonly sortingLayers: SortingLayersSettings;\n /** The core `time` section. */\n readonly time: TimeSettings;\n /**\n * Reads an extension-registered section.\n *\n * @typeParam S - The section's resolved shape.\n * @param name - The section name the extension registered.\n * @returns The resolved section.\n * @throws IgnifxError with code `IGX-0407` when the section was never registered.\n */\n // The type parameter appears once on purpose: it is the caller's declaration of what the section\n // holds, the same escape hatch `JSON.parse`-style APIs use. There is no value to infer it from.\n // oxlint-disable-next-line typescript/no-unnecessary-type-parameters\n section<S>(name: string): S;\n}\n\n/**\n * A failure the engine caught at a boundary and reported instead of rethrowing\n * (`docs/architecture/01-lifecycle-and-time.md` §5, `15-devtools-and-diagnostics.md` §1). One\n * script throwing never stops the others.\n *\n * @example\n * ```ts\n * app.onError.connect((report) => {\n * app.log.error(\"{source} callback threw on {entity}\", report.source, report.entity?.name ?? \"-\");\n * });\n * ```\n *\n * @public\n */\nexport interface ErrorReport {\n /** Whatever was thrown. Usually an `Error`, often an `IgnifxError`. */\n readonly error: unknown;\n /** Which boundary caught it. */\n readonly source: \"lifecycle\" | \"coroutine\" | \"system\" | \"extension\" | \"asset\";\n /** The phase that was running, or `null` outside a phase (a lifecycle flush, say). */\n readonly phase: Phase | null;\n /** The entity involved, or `null` when the failure is not entity-scoped. */\n readonly entity: Entity | null;\n /** The component involved, or `null` when the failure is not component-scoped. */\n readonly component: Component | null;\n}\n\n/**\n * A generator coroutine (`docs/architecture/01-lifecycle-and-time.md` §5, ADR-0010). The scheduler\n * resumes it synchronously at defined points in the frame; it is never an `async` function.\n *\n * @public\n */\nexport type Coroutine = Generator<CoroutineYield, void, unknown>;\n\n/**\n * Everything a coroutine may `yield`: `null`/`undefined` for \"next frame\", a wait instruction, a\n * handle to another coroutine to wait for, or a promise to resume on once it settles.\n *\n * @public\n */\nexport type CoroutineYield = null | undefined | WaitInstruction | CoroutineHandle | Promise<unknown>;\n\n/**\n * A wait a coroutine yielded, built by `waitSeconds`, `waitSecondsRealtime`, `waitFixedUpdate`,\n * `waitUntil`, or `waitWhile`.\n *\n * @public\n */\nexport interface WaitInstruction {\n /** Which kind of wait this is; the scheduler switches on it. */\n readonly kind: \"seconds\" | \"secondsRealtime\" | \"fixedUpdate\" | \"until\" | \"while\";\n /** How long to wait, for the two timed kinds. */\n readonly seconds?: number;\n /** The condition, for the two predicate kinds. */\n readonly predicate?: () => boolean;\n}\n\n/**\n * The observable state of a running coroutine, returned by `Script.startCoroutine`.\n *\n * @public\n */\nexport interface CoroutineHandle {\n /** `true` while the coroutine is still scheduled — including while it is paused. */\n readonly isRunning: boolean;\n /** `true` once the coroutine has finished, been stopped, or been cancelled. */\n readonly isDone: boolean;\n}\n\n/**\n * The coroutine scheduler, reached as `app.coroutines` and driven by `Script.startCoroutine`\n * (`docs/architecture/01-lifecycle-and-time.md` §5). The kernel calls\n * {@link CoroutineHost.setPaused} on every enable transition and {@link CoroutineHost.cancelAll}\n * when a script is destroyed.\n *\n * @public\n */\nexport interface CoroutineHost {\n /**\n * Schedules a coroutine owned by a script.\n *\n * @param owner - The script whose enabled state gates the coroutine.\n * @param routine - The generator to drive.\n * @returns A handle for stopping it or waiting on it.\n */\n start(owner: Script, routine: Coroutine): CoroutineHandle;\n /**\n * Stops one coroutine. Stopping an already finished coroutine is a no-op.\n *\n * @param handle - The handle returned by {@link CoroutineHost.start}.\n */\n stop(handle: CoroutineHandle): void;\n /**\n * Stops every coroutine a script started.\n *\n * @param owner - The owning script.\n */\n stopAll(owner: Script): void;\n /**\n * Pauses or resumes every coroutine a script started, without discarding their state.\n *\n * @param owner - The owning script.\n * @param paused - `true` to pause, `false` to resume.\n */\n setPaused(owner: Script, paused: boolean): void;\n /**\n * Cancels every coroutine a script started and detaches any promise they were waiting on, so the\n * continuation never runs. Called by the destroy flush and by world disposal.\n *\n * @param owner - The owning script.\n */\n cancelAll(owner: Script): void;\n}\n\n/**\n * Babylon Lite objects an app owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3); excluded from the stability guarantees of\n * `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport interface AppLiteHandles {\n /** The Lite engine — a WebGPU engine, or the null engine in headless mode. */\n readonly engine: LiteEngine;\n /** The Lite scene the world renders into. */\n readonly scene: LiteScene;\n}\n\n/**\n * What Babylon Lite reported when the WebGPU device was lost\n * (`docs/architecture/07-rendering.md` §4).\n *\n * @public\n */\nexport interface DeviceLostInfo {\n /** The `GPUDeviceLostInfo.reason` string, or `null` when the host gave none. */\n readonly reason: string | null;\n /** The human-readable message. */\n readonly message: string;\n}\n\n/**\n * The engine-wide events reached as `app.events` (`docs/architecture/02-scene-graph.md` §8,\n * `07-rendering.md` §4). Extensions add their own signals through declaration merging, the same way\n * they add app properties.\n *\n * @example\n * ```ts\n * class Hud extends Script {\n * onEnable(): void {\n * this.app.events.onSceneLoaded.connect((scene) => this.rebuild(scene), { owner: this });\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface AppEvents {\n /** A scene instance and its entities exist. */\n readonly onSceneLoaded: SignalLike<SceneInstance>;\n /** A scene instance is about to be unloaded and its entities destroyed. */\n readonly onSceneUnloaded: SignalLike<SceneInstance>;\n /** The WebGPU device was lost; rendering is suspended while Lite rebuilds it. */\n readonly onDeviceLost: SignalLike<DeviceLostInfo>;\n /** The WebGPU device and its resources were rebuilt. */\n readonly onDeviceRecovered: SignalLike;\n /** Recovery failed; the payload is whatever the recovery path reported. */\n readonly onDeviceRecoveryFailed: SignalLike<unknown>;\n}\n\n/**\n * The root object of a game and the surface a script sees through `this.app`\n * (`docs/architecture/00-overview.md` §1). There are no globals: every engine service is reached\n * from here, or from the `entity`/`world` a script belongs to (`CONSTITUTION.md` §3.6).\n *\n * @remarks\n * Extensions add typed properties through declaration merging\n * (`docs/architecture/03-scripting-and-components.md` §7), so `this.app.input` is fully typed when\n * `@ignifx/input` is installed and a compile error when it is not.\n *\n * @example\n * ```ts\n * class Menu extends Script {\n * static updateWhenPaused = true;\n * onEnable(): void {\n * this.app.pause();\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface App {\n /** The clock. */\n readonly time: Time;\n /** The running simulation. */\n readonly world: World;\n /** Addressed, reference-counted asset loading (`docs/architecture/05-assets-and-loading.md` §4). */\n readonly assets: Assets;\n /** Engine-wide events (`docs/architecture/02-scene-graph.md` §8). */\n readonly events: AppEvents;\n /**\n * Surface sizing, material warm-up, GPU picking, screenshots, and the render diagnostics\n * (`docs/architecture/07-rendering.md` §1, §3, §5).\n */\n readonly renderer: Renderer;\n /** The app-scoped logger. */\n readonly log: Logger;\n /** Per-frame counters and profiling scopes. */\n readonly diagnostics: Diagnostics;\n /** Services registered by extensions. */\n readonly services: ServiceRegistry;\n /** Resolved project settings. */\n readonly settings: AppSettings;\n /** Every failure the engine caught at a boundary rather than rethrowing. */\n readonly onError: Signal<ErrorReport>;\n /** `true` when the app runs on Lite's null engine with no render surface. */\n readonly isHeadless: boolean;\n /** `true` between `start()` and `stop()`/`dispose()`. */\n readonly isRunning: boolean;\n /** The `@ignifx/core` version this app was built from. */\n readonly version: string;\n /**\n * Where the app is running (`docs/architecture/14-platform-electron.md` §1). Phase 1 answers only\n * `kind`; the rest of §1's surface arrives with `@ignifx/electron`.\n */\n readonly platform: PlatformInfo;\n /** Unstable Babylon Lite escape hatch (`docs/architecture/00-overview.md` §3). */\n readonly lite: AppLiteHandles;\n /** The coroutine scheduler. */\n readonly coroutines: CoroutineHost;\n /**\n * Makes component `typeId`s known to the serializer and the inspector\n * (`docs/architecture/03-scripting-and-components.md` §4).\n *\n * @param types - The component classes to register.\n * @throws IgnifxError with code `IGX-0203` when a `typeId` is already registered.\n */\n registerComponents(types: readonly ConcreteComponentType[]): void;\n /**\n * Runs extension `onStart` hooks and starts the frame loop.\n *\n * @returns A promise that settles once the first frame has been submitted.\n */\n start(): Promise<void>;\n /** Stops the frame loop without disposing anything. */\n stop(): void;\n /** Stops the loop, disposes the world, the extensions, and the Lite objects. */\n dispose(): void;\n /**\n * Runs exactly one frame with a supplied delta — the headless driver\n * (`docs/architecture/01-lifecycle-and-time.md` §8).\n *\n * @param deltaSeconds - The raw frame delta in seconds, before the maximum-delta clamp.\n */\n step(deltaSeconds: number): void;\n /** Sets `time.paused`. */\n pause(): void;\n /** Clears `time.paused`. */\n resume(): void;\n}\n\n/**\n * Where in the frame the engine currently is, as far as the scene graph needs to know\n * (`docs/architecture/01-lifecycle-and-time.md` §4, §6). The scheduler and the lifecycle queue\n * write it; `Entity` and the queue read it to decide whether `awake` runs nested and synchronously\n * and whether `destroyImmediate` is legal.\n *\n * @public\n */\nexport interface FrameState {\n /** `true` while a lifecycle callback, a script callback, or a coroutine body is on the stack. */\n readonly isInsideCallback: boolean;\n /** `true` while the fixed loop is running (`time.inFixedStep`). */\n readonly isInsideFixedStep: boolean;\n}\n\n/**\n * Options accepted by `ExtensionContext.registerComponent`.\n *\n * @public\n */\nexport interface RegisterComponentOptions {\n /** An explicit registration id, when the class does not declare one. */\n readonly typeId?: string;\n}\n\n/**\n * Options accepted by `ExtensionContext.registerSystem`.\n *\n * @public\n */\nexport interface RegisterSystemOptions {\n /** Which phase the system runs in. */\n readonly phase: Phase;\n /** Ascending order within the phase; core uses `[-1000, 1000]`, extensions `[1001, 9999]`. */\n readonly order?: number;\n}\n\n/**\n * An extension's registration surface (`docs/architecture/04-extensions.md` §1). Everything an\n * extension contributes is declared here; nothing happens at module import time\n * (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport interface ExtensionContext {\n /** The app being built. */\n readonly app: App;\n /** A logger scoped to this extension. */\n readonly log: Logger;\n /**\n * Registers one component class.\n *\n * @param type - The component class.\n * @param options - An explicit `typeId`, when the class does not declare one.\n */\n registerComponent(type: ConcreteComponentType, options?: RegisterComponentOptions): void;\n /**\n * Registers several component classes.\n *\n * @param types - The component classes.\n */\n registerComponents(types: readonly ConcreteComponentType[]): void;\n /**\n * Registers a system in a phase.\n *\n * @param system - The system.\n * @param options - The phase and the ascending order within it; core uses `[-1000, 1000]`.\n */\n registerSystem(system: System, options: RegisterSystemOptions): void;\n /**\n * Registers a service instance under a key.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @param instance - The service.\n */\n registerService<T>(key: ServiceKey<T>, instance: T): void;\n /**\n * Declares an asset type whose loader is registered separately, or not at all, so that addresses\n * with its extensions resolve to a type (`docs/architecture/04-extensions.md` §1).\n *\n * @param type - The type name and the extensions that select it.\n */\n registerAssetType(type: AssetTypeDefinition): void;\n /**\n * Registers an asset loader (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @param loader - The loader, which also declares the extensions that select its type.\n * @throws IgnifxError with code `IGX-0506` when another extension already owns the type.\n */\n registerAssetLoader(loader: AssetLoader): void;\n /**\n * Declares that this extension needs a rendering feature switched on\n * (`docs/architecture/07-rendering.md` §1.1).\n *\n * @remarks\n * Babylon Lite compiles its shader permutations and records its frame graph inside\n * `registerScene`, so every feature that changes what gets compiled has to be on before that\n * call. `register` runs before `app.start()` does it, so this is a *declaration* there: the\n * feature is switched on whether or not the project listed it. After the scene is registered it\n * is a refusal instead.\n *\n * @param feature - The feature the extension needs.\n * @throws IgnifxError with code `IGX-0704` when the render scene has already been registered.\n *\n * @example\n * ```ts\n * register(ctx: ExtensionContext): void {\n * ctx.requireRenderingFeature(\"skeletons\");\n * }\n * ```\n */\n requireRenderingFeature(feature: RenderingFeature): void;\n /**\n * Defines a property on `App`, pairing with a module augmentation of the `App` interface.\n *\n * @param name - The property name, for example `\"input\"`.\n * @param getter - Returns the value each time the property is read.\n * @throws IgnifxError with code `IGX-0401` when the property is already defined.\n */\n defineAppProperty(name: string, getter: () => unknown): void;\n /**\n * Registers a project settings section.\n *\n * @typeParam S - The section's resolved shape.\n * @param section - The section name as it appears in `ignifx.config.ts`.\n * @param schema - The schema the section is validated against.\n * @param defaults - The values used when the project omits the section.\n */\n // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- see `AppSettings.section`.\n registerSettings<S>(section: string, schema: Schema, defaults: S): void;\n /**\n * Adds diagnostic codes to the app's error-code registry.\n *\n * @param codes - `IGX-####` to one-line message template.\n */\n registerErrorCodes(codes: Readonly<Record<string, string>>): void;\n /**\n * Delivers one physics callback to every script on an entity that implements it, for extension\n * authors (`docs/architecture/09-physics.md` §4). The scheduler stays the only thing that calls a\n * script callback: this routes through the same guarded call site the frame loop uses\n * (`03-scripting-and-components.md` §6).\n *\n * @remarks\n * Delivery is synchronous and in component order, to effectively-enabled scripts only; a\n * destroyed or inactive entity receives nothing. A handler that throws is reported to\n * `app.onError` with `source: \"lifecycle\"` and the running phase, and the remaining scripts still\n * receive the callback. Nothing is allocated per call.\n *\n * @param entity - The entity whose scripts should receive the callback.\n * @param kind - Which physics callback to deliver.\n * @param argument - The single argument the callback receives — a collision or a trigger event.\n * @throws IgnifxError with code `IGX-0409` in development when called from outside the fixed\n * loop, where `01-lifecycle-and-time.md` §3 says these callbacks never run. Production builds\n * deliver it anyway rather than losing the event.\n *\n * @example\n * ```ts\n * for (let index = 0; index < events.length; index += 1) {\n * ctx.dispatchScriptCallback(events[index].entity, PhysicsCallbackName.onTriggerEnter, events[index]);\n * }\n * ```\n *\n * @beta\n */\n dispatchScriptCallback(entity: Entity, kind: PhysicsCallbackName, argument: unknown): void;\n /**\n * Whether any script on an entity implements a physics callback, for extension authors. This is\n * what `Rigidbody.collisionEvents` auto-detection asks (`09-physics.md` §2.1).\n *\n * @remarks\n * The answer ignores `enabled`, so it stays stable while scripts are toggled and only changes\n * when a component is added or removed — the two moments the physics extension recomputes it.\n * Components already queued for destruction do not count.\n *\n * @param entity - The entity to inspect.\n * @param kind - Which physics callback.\n * @returns `true` when at least one script on the entity implements it.\n *\n * @beta\n */\n entityImplements(entity: Entity, kind: PhysicsCallbackName): boolean;\n /**\n * Publishes the scene an extension simulates in as `world.lite.simulationScene`, for extension\n * authors (`docs/architecture/09-physics.md` §1, `02-scene-graph.md` §2).\n *\n * @param scene - The simulation scene, or `null` to clear it from the extension's `dispose`.\n * @throws IgnifxError with code `IGX-0410` when the world already has a different simulation\n * scene.\n *\n * @beta\n */\n setSimulationScene(scene: LiteScene | null): void;\n /**\n * Registers a callback that runs when the app is disposed.\n *\n * @param callback - The teardown to run.\n */\n onDispose(callback: () => void): void;\n /**\n * Looks up a service registered by an earlier extension.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @returns The instance.\n * @throws IgnifxError with code `IGX-0405` when the service is not registered.\n */\n require<T>(key: ServiceKey<T>): T;\n /**\n * Looks up a service registered by an earlier extension, tolerating its absence.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @returns The instance, or `null` when it is not registered.\n */\n tryGet<T>(key: ServiceKey<T>): T | null;\n /**\n * Reads a resolved settings section.\n *\n * @typeParam S - The section's resolved shape.\n * @param section - The section name.\n * @returns The resolved section.\n * @throws IgnifxError with code `IGX-0407` when the section was never registered.\n */\n // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- see `AppSettings.section`.\n settings<S>(section: string): S;\n}\n\n/**\n * The unit of optional functionality (`docs/architecture/04-extensions.md` §1). Core features are\n * extensions too (`CONSTITUTION.md` §8.1).\n *\n * @public\n */\nexport interface Extension {\n /** Unique name; the npm package name for published extensions. */\n readonly name: string;\n /** The semver version of the extension itself. */\n readonly version: string;\n /** The semver range of `@ignifx/core` this extension supports, checked at registration. */\n readonly engine?: string;\n /** Extensions that must be registered before this one. */\n readonly requires?: readonly string[];\n /** Extensions this one integrates with when they are present. */\n readonly optional?: readonly string[];\n /**\n * Declares components, systems, services, loaders, and settings.\n *\n * @param ctx - The registration surface.\n * @returns Nothing, or a promise the host awaits before registering the next extension.\n */\n register(ctx: ExtensionContext): void | Promise<void>;\n /**\n * Runs after every extension registered and the Lite engine exists, before the first frame.\n *\n * @param app - The app being started.\n * @returns Nothing, or a promise `app.start()` awaits.\n */\n onStart?(app: App): void | Promise<void>;\n /**\n * Runs when the app stops, in reverse registration order.\n *\n * @param app - The app being stopped.\n */\n onStop?(app: App): void;\n /**\n * Releases everything the extension owns, in reverse registration order.\n *\n * @param app - The app being disposed.\n */\n dispose?(app: App): void;\n}\n","/**\n * The `@ignifx/core` version this build reports as `app.version` and as the core extension's\n * `version` (`docs/architecture/04-extensions.md` §1).\n *\n * @remarks\n * The literal is `\"0.0.0\"` in the repository and is stamped by the release pipeline: Changesets\n * writes the real number into `package.json`, and the build replaces this constant with it\n * (coding standards §12, `release.yml`). Reading the version from `package.json` at run time is not\n * an option — that would be an import-time side effect and a bundler hazard\n * (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport const VERSION = \"0.0.0\";\n","import type { AssetsImpl } from \"./assets-service.js\";\nimport type { System, SystemContext } from \"../app/types.js\";\n\n/**\n * The `PreUpdate` system that delivers completed loads\n * (`docs/architecture/01-lifecycle-and-time.md` §3 step 2: \"assets delivers completed loads and\n * hot-reload swaps on the main thread\").\n *\n * It is the only place an asset's `state` flips and its `promise` settles, which is what makes the\n * question \"is this asset ready?\" have one answer per frame. The same tick advances the retry and\n * collector countdowns, so both are driven by engine time rather than a wall clock: a headless test\n * that calls `app.step(1 / 60)` sixty times has advanced them by exactly one second\n * (`01-lifecycle-and-time.md` §8, coding standards §10).\n */\n\n/**\n * Where asset delivery sits inside `PreUpdate`.\n *\n * @remarks\n * §3 step 2 lists input polling first and asset delivery second, so the order leaves the band below\n * it free for `@ignifx/input`'s own system while staying inside the `[-1000, 1000]` range core\n * systems are allotted (`docs/architecture/03-scripting-and-components.md` §6).\n *\n * @internal\n */\nexport const ASSET_DELIVERY_ORDER = -900;\n\n/**\n * Drains the asset service's delivery queue once per frame.\n *\n * @internal\n */\nexport class AssetDeliverySystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name: string = \"ignifx/asset-delivery\";\n\n readonly #assets: AssetsImpl;\n\n /**\n * Creates the system.\n *\n * @param assets - The service to drain.\n */\n constructor(assets: AssetsImpl) {\n this.#assets = assets;\n }\n\n /**\n * Delivers everything that settled since the previous frame.\n *\n * @param ctx - The world, the clock, the phase, and the frame delta.\n */\n update(ctx: SystemContext): void {\n this.#assets.deliver(ctx.dt, ctx.time.unscaledDeltaTime);\n }\n}\n","import type { AssetLoader, LoaderContext } from \"./types.js\";\n\n/**\n * The three loaders that need no adapter and no GPU\n * (`docs/architecture/05-assets-and-loading.md` §5, last row of the core table). The core extension\n * registers them; `texture`, `model`, `scene`, `material`, `environment`, and `font` arrive with the\n * rendering layer, which owns the Lite adapter.\n *\n * Each is a frozen object literal rather than a factory: they hold no state, so one instance per\n * process is correct and module scope stays free of allocation (`CONSTITUTION.md` §3.5).\n */\n\n/**\n * Parsed JSON, for `.json` addresses.\n *\n * @remarks\n * The value is whatever the file contained; a loader that needs certainty about its shape validates\n * it with a schema (`docs/architecture/06-serialization-and-scene-format.md` §8). Longer suffixes\n * win the extension match, so registering a `.scene.json` loader takes those addresses away from\n * this one without any ordering rule.\n *\n * @example\n * ```ts\n * const config = app.assets.load<{ readonly hp: number }>(\"data/player.json\");\n * ```\n *\n * @public\n */\nexport const jsonAssetLoader: AssetLoader = Object.freeze({\n type: \"json\",\n extensions: Object.freeze([\".json\"]),\n load: (ctx: LoaderContext): Promise<unknown> => ctx.fetchJson(),\n});\n\n/**\n * UTF-8 text, for `.txt`, `.md`, and `.csv` addresses.\n *\n * @public\n */\nexport const textAssetLoader: AssetLoader<string> = Object.freeze({\n type: \"text\",\n extensions: Object.freeze([\".txt\", \".md\", \".csv\"]),\n load: (ctx: LoaderContext): Promise<string> => ctx.fetchText(),\n});\n\n/**\n * Raw bytes, for `.bin` and `.wasm` addresses — the path `ignifx.assets.public` binaries such as\n * Havok's WASM take (`docs/architecture/05-assets-and-loading.md` §7).\n *\n * @public\n */\nexport const binaryAssetLoader: AssetLoader<ArrayBuffer> = Object.freeze({\n type: \"binary\",\n extensions: Object.freeze([\".bin\", \".wasm\"]),\n load: (ctx: LoaderContext): Promise<ArrayBuffer> => ctx.fetchBytes(),\n});\n\n/**\n * The generic loaders in registration order.\n *\n * @internal\n */\nexport const GENERIC_ASSET_LOADERS: readonly AssetLoader[] = Object.freeze([\n jsonAssetLoader,\n textAssetLoader,\n binaryAssetLoader,\n]);\n","import type { Entity } from \"./entity.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { EntityHandle } from \"../handles/handle.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\nimport type { SceneAsset } from \"../serialization/scene-asset.js\";\nimport type { Signal } from \"../signal/signal.js\";\nimport type { TagSet } from \"../tags/tag-set.js\";\nimport type { Transform } from \"../transform/transform.js\";\nimport type { WorldHost } from \"../world/world-host.js\";\n\n/**\n * The engine-owned state of an entity, kept behind a module symbol for the same reasons as a\n * component's: the world, the lifecycle queue, and the destroy flush all need to read and write it,\n * while game code has no way to name it.\n */\n\n/**\n * The key the engine state hangs off an entity.\n *\n * @internal\n */\nexport const ENTITY_INTERNALS: unique symbol = Symbol(\"ignifx.entity.internals\");\n\n/**\n * Where an entity came from, for the entities a scene file's `instance` entry produced. The scene\n * loader fills it in; `Entity.prefab` and the serializer's override diffing read it\n * (`docs/architecture/02-scene-graph.md` §6, `06-serialization-and-scene-format.md` §5).\n *\n * @internal\n */\nexport interface EntityOrigin {\n /** The uid the entity carries in the scene file that declared it, which overrides address. */\n readonly sourceUid: string;\n /**\n * The instance root this entity sits *inside*, or `null` when the scene file declared it\n * directly. An instance root is inside its own parent instance, if any, not inside itself.\n */\n readonly instanceRoot: Entity | null;\n /** Set when this entity *is* the root of an instance. */\n readonly instanced: EntityInstanceLink | null;\n /** Expanded component uid to the uid that component carries in the file that declared it. */\n readonly componentSourceUids: ReadonlyMap<string, string>;\n}\n\n/**\n * The instanced scene an instance root stands for.\n *\n * @internal\n */\nexport interface EntityInstanceLink {\n /** The address of the instanced scene. */\n readonly address: string;\n /** The handle it was loaded through, when the asset service resolved one. */\n readonly asset: AssetHandle<SceneAsset> | null;\n /** The scene value, so the serializer can diff current state against it. */\n readonly scene: SceneAsset;\n}\n\n/**\n * The engine-owned state of one entity.\n *\n * @internal\n */\nexport interface EntityInternals {\n /** The world that owns the entity. */\n readonly host: WorldHost;\n /** The Babylon Lite node the entity's transform is a view over. */\n readonly node: LiteSceneNode;\n /** The dense runtime handle. */\n readonly handle: EntityHandle;\n /** The stable ULID. */\n readonly uid: string;\n /** Monotonic creation serial; sibling order and dispatch tie-breaks read it. */\n readonly serial: number;\n /** The free-form tags, with the world's index kept current through the set's observer. */\n readonly tags: TagSet;\n /** The entity's transform, assigned the moment the constructor has built it. */\n transform: Transform | null;\n /** The display name; not unique and never used for lookup by the engine. */\n name: string;\n /** The scene instance that owns the entity. */\n scene: SceneInstance;\n /**\n * Where the entity came from when a scene file's `instance` entry produced it, or `null` for an\n * entity a scene declared itself or code created (`docs/architecture/02-scene-graph.md` §6).\n */\n origin: EntityOrigin | null;\n /** The parent, or `null` for a root. */\n parent: Entity | null;\n /** The children, in creation order. */\n children: Entity[];\n /** The components, in attach order. The transform is always index 0. */\n components: Component[];\n /** The entity's own active flag. */\n active: boolean;\n /** `active` and every ancestor's `active`, materialised on change rather than walked per read. */\n activeInHierarchy: boolean;\n /** The layer slot, `0..31`. */\n layer: number;\n /** The immovability hint; settable only before the entity's first `awake`. */\n isStatic: boolean;\n /** `true` once any of the entity's components has run `awake`, which freezes `isStatic`. */\n hasAwoken: boolean;\n /** `true` from the moment `destroy()` is called. */\n isDestroyed: boolean;\n /** `true` once the destroy flush has released the entity. */\n isReleased: boolean;\n /** `true` while the entity sits in the destroy queue, so it is queued at most once. */\n isDestroyQueued: boolean;\n /** Lazily created signals; `null` until something asks for them. */\n onChildAdded: Signal<Entity> | null;\n /** Lazily created. */\n onChildRemoved: Signal<Entity> | null;\n /** Lazily created. */\n onParentChanged: Signal<Entity | null> | null;\n /** Lazily created. */\n onActiveChanged: Signal<boolean> | null;\n /** Lazily created. */\n onComponentAdded: Signal<Component> | null;\n /** Lazily created. */\n onComponentRemoved: Signal<Component> | null;\n /** Lazily created. */\n onDestroyed: Signal<Entity> | null;\n}\n\n/**\n * Reads an entity's engine-owned state.\n *\n * @param entity - The entity.\n * @returns Its internal state.\n *\n * @internal\n */\nexport function entityInternals(entity: Entity): EntityInternals {\n return entity[ENTITY_INTERNALS];\n}\n","import { degToRad, EPSILON } from \"./math-utils.js\";\nimport type { Mat4Like, MutableQuat, MutableVec3, QuatLike, Vec3Like } from \"./types.js\";\n\n/**\n * The backing store of a {@link Mat4}: a `Float32Array` of exactly 16 elements, in column-major\n * order (`m[column * 4 + row]`). The `length: 16` refinement is what makes it a {@link Mat4Like},\n * and therefore what makes it accepted anywhere Babylon Lite wants a `Mat4`.\n *\n * @public\n */\nexport type Mat4Elements = Float32Array & { readonly length: 16 };\n\n/**\n * Allocates the 16-element column-major storage a matrix owns, pre-filled with zeroes.\n *\n * @returns Fresh, zeroed storage.\n */\nfunction allocateElements(): Mat4Elements {\n // Boundary assertion (coding standards §5.2): the invariant is that this array is exactly 16\n // elements long, which `Float32Array`'s `length: number` cannot express. Babylon Lite brands its\n // own allocation the same way (`lib/math/_matrix-allocator.js`).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return new Float32Array(16) as Mat4Elements;\n}\n\n/**\n * The determinant of the upper-left 3×3 basis. Its sign says whether the matrix mirrors, which is\n * how Babylon Lite decides the sign of the decomposed Y scale (`lib/math/mat4-decompose.js`).\n *\n * @param m - The matrix to measure.\n * @returns The 3×3 determinant.\n */\nfunction basisDeterminant(m: Mat4Like): number {\n const m0 = m[0] ?? 0;\n const m1 = m[1] ?? 0;\n const m2 = m[2] ?? 0;\n const m4 = m[4] ?? 0;\n const m5 = m[5] ?? 0;\n const m6 = m[6] ?? 0;\n const m8 = m[8] ?? 0;\n const m9 = m[9] ?? 0;\n const m10 = m[10] ?? 0;\n return m0 * (m5 * m10 - m6 * m9) + m1 * (m6 * m8 - m4 * m10) + m2 * (m4 * m9 - m5 * m8);\n}\n\n/**\n * Writes the unit quaternion of an orthonormal basis into `out`. Arguments are named row-major\n * (`b<row><column>`), matching Babylon Lite's `_quatFromRotationBasis`\n * (`lib/math/quat-from-rotation-matrix.js`), which this reproduces branch for branch.\n *\n * Shared with the quaternion module; not part of the public API.\n *\n * @param b00 - Row 0, column 0.\n * @param b01 - Row 0, column 1.\n * @param b02 - Row 0, column 2.\n * @param b10 - Row 1, column 0.\n * @param b11 - Row 1, column 1.\n * @param b12 - Row 1, column 2.\n * @param b20 - Row 2, column 0.\n * @param b21 - Row 2, column 1.\n * @param b22 - Row 2, column 2.\n * @param out - The quaternion to write.\n *\n * @internal\n */\nexport function basisToQuatToRef(\n b00: number,\n b01: number,\n b02: number,\n b10: number,\n b11: number,\n b12: number,\n b20: number,\n b21: number,\n b22: number,\n out: MutableQuat,\n): void {\n const trace = b00 + b11 + b22;\n if (trace > 0) {\n const s = 0.5 / Math.sqrt(trace + 1);\n out.set((b21 - b12) * s, (b02 - b20) * s, (b10 - b01) * s, 0.25 / s);\n return;\n }\n if (b00 > b11 && b00 > b22) {\n const s = 2 * Math.sqrt(1 + b00 - b11 - b22);\n out.set(0.25 * s, (b01 + b10) / s, (b02 + b20) / s, (b21 - b12) / s);\n return;\n }\n if (b11 > b22) {\n const s = 2 * Math.sqrt(1 + b11 - b00 - b22);\n out.set((b01 + b10) / s, 0.25 * s, (b12 + b21) / s, (b02 - b20) / s);\n return;\n }\n const s = 2 * Math.sqrt(1 + b22 - b00 - b11);\n out.set((b02 + b20) / s, (b12 + b21) / s, 0.25 * s, (b10 - b01) / s);\n}\n\n/**\n * A 4×4 transformation matrix stored column-major in a `Float32Array`, byte-compatible with WGSL's\n * `mat4x4<f32>` and with Babylon Lite's `Mat4` (translation in slots 12/13/14).\n *\n * ignifx is left-handed, Y up, +Z forward (ADR-0011), so the projection helpers are the `LH`\n * family and they use Lite's **reverse depth** convention: the near plane maps to 1 and the far\n * plane to 0.\n *\n * Instance methods mutate the matrix and return `this`; `ToRef` statics write into their `out`\n * matrix and allocate nothing, and are safe when `out` aliases an input. The remaining statics\n * allocate a fresh matrix and say so.\n *\n * @example\n * ```ts\n * const world = new Mat4();\n * Mat4.composeToRef(position, rotation, scale, world);\n *\n * const inverse = new Mat4();\n * if (Mat4.invertToRef(world, inverse)) {\n * Mat4.transformPointToRef(inverse, worldPoint, localPoint);\n * }\n * ```\n *\n * @public\n */\nexport class Mat4 {\n /**\n * The 16 elements, column-major (`elements[column * 4 + row]`). This is the object to hand to\n * anything that wants a {@link Mat4Like} — including Babylon Lite — and the buffer to upload to\n * the GPU. It is never reallocated, so a reference to it stays valid for the matrix's lifetime.\n */\n readonly elements: Mat4Elements;\n\n /**\n * Creates an identity matrix.\n */\n constructor() {\n const e = allocateElements();\n e[0] = 1;\n e[5] = 1;\n e[10] = 1;\n e[15] = 1;\n this.elements = e;\n }\n\n /**\n * Resets this matrix to the identity.\n *\n * @returns This matrix.\n */\n identity(): this {\n const e = this.elements;\n e[0] = 1;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 0;\n e[5] = 1;\n e[6] = 0;\n e[7] = 0;\n e[8] = 0;\n e[9] = 0;\n e[10] = 1;\n e[11] = 0;\n e[12] = 0;\n e[13] = 0;\n e[14] = 0;\n e[15] = 1;\n return this;\n }\n\n /**\n * Copies every element from another matrix.\n *\n * @param m - The matrix to read.\n * @returns This matrix.\n */\n copyFrom(m: Mat4Like): this {\n const e = this.elements;\n for (let i = 0; i < 16; i++) {\n e[i] = m[i] ?? 0;\n }\n return this;\n }\n\n /**\n * Copies this matrix into a new one.\n *\n * @returns A new matrix. **Allocates.**\n */\n clone(): Mat4 {\n return new Mat4().copyFrom(this.elements);\n }\n\n /**\n * Post-multiplies this matrix by another (`this = this * m`), so `m`'s transform is applied first\n * when the product acts on a column vector.\n *\n * @param m - The right-hand matrix.\n * @returns This matrix.\n */\n multiply(m: Mat4Like): this {\n Mat4.multiplyToRef(this.elements, m, this);\n return this;\n }\n\n /**\n * Inverts this matrix in place.\n *\n * @returns `true` on success. When the matrix is singular this returns `false` and leaves the\n * matrix untouched.\n */\n invert(): boolean {\n return Mat4.invertToRef(this.elements, this);\n }\n\n /**\n * Transposes this matrix in place, swapping rows and columns.\n *\n * @returns This matrix.\n */\n transpose(): this {\n Mat4.transposeToRef(this.elements, this);\n return this;\n }\n\n /**\n * The full 4×4 determinant of this matrix.\n *\n * @returns The determinant; zero means the matrix cannot be inverted.\n */\n determinant(): number {\n return Mat4.determinant(this.elements);\n }\n\n /**\n * Compares this matrix with another element by element, with a tolerance.\n *\n * @param m - The matrix to compare against.\n * @param epsilon - The largest per-element difference still considered equal.\n * @returns `true` when every element matches within `epsilon`.\n */\n equalsWithEpsilon(m: Mat4Like, epsilon: number = EPSILON): boolean {\n return Mat4.equalsWithEpsilon(this.elements, m, epsilon);\n }\n\n /**\n * Creates an identity matrix.\n *\n * @returns A new identity matrix. **Allocates.**\n */\n static identity(): Mat4 {\n return new Mat4();\n }\n\n /**\n * Creates a matrix holding a copy of another matrix's elements.\n *\n * @param m - The matrix to copy.\n * @returns A new matrix. **Allocates.**\n */\n static from(m: Mat4Like): Mat4 {\n return new Mat4().copyFrom(m);\n }\n\n /**\n * Builds a translation-rotation-scale matrix, the same composition order Babylon Lite's\n * `mat4Compose` uses (`translation * rotation * scale`).\n *\n * @param position - The translation, in metres.\n * @param rotation - The rotation; assumed to be a unit quaternion.\n * @param scale - The per-axis scale.\n * @returns A new matrix. **Allocates.**\n */\n static compose(position: Vec3Like, rotation: QuatLike, scale: Vec3Like): Mat4 {\n return Mat4.composeToRef(position, rotation, scale, new Mat4());\n }\n\n /**\n * Writes a translation-rotation-scale matrix into `out`.\n *\n * @param position - The translation, in metres.\n * @param rotation - The rotation; assumed to be a unit quaternion.\n * @param scale - The per-axis scale.\n * @param out - The matrix to write.\n * @returns `out`.\n *\n * @example\n * ```ts\n * Mat4.composeToRef(transform.localPosition, transform.localRotation, transform.localScale, local);\n * ```\n */\n static composeToRef(position: Vec3Like, rotation: QuatLike, scale: Vec3Like, out: Mat4): Mat4 {\n const qx = rotation.x;\n const qy = rotation.y;\n const qz = rotation.z;\n const qw = rotation.w;\n const sx = scale.x;\n const sy = scale.y;\n const sz = scale.z;\n const xx = qx * qx;\n const yy = qy * qy;\n const zz = qz * qz;\n const xy = qx * qy;\n const xz = qx * qz;\n const yz = qy * qz;\n const wx = qw * qx;\n const wy = qw * qy;\n const wz = qw * qz;\n const e = out.elements;\n e[0] = (1 - 2 * (yy + zz)) * sx;\n e[1] = 2 * (xy + wz) * sx;\n e[2] = 2 * (xz - wy) * sx;\n e[3] = 0;\n e[4] = 2 * (xy - wz) * sy;\n e[5] = (1 - 2 * (xx + zz)) * sy;\n e[6] = 2 * (yz + wx) * sy;\n e[7] = 0;\n e[8] = 2 * (xz + wy) * sz;\n e[9] = 2 * (yz - wx) * sz;\n e[10] = (1 - 2 * (xx + yy)) * sz;\n e[11] = 0;\n e[12] = position.x;\n e[13] = position.y;\n e[14] = position.z;\n e[15] = 1;\n return out;\n }\n\n /**\n * Splits an affine transformation-rotation-scale matrix back into its parts, using Babylon Lite's\n * convention (`lib/math/mat4-decompose.js`): scales are the lengths of the basis columns, and a\n * mirrored matrix (negative basis determinant) reports a **negative Y scale** rather than\n * silently dropping the reflection. Shear is not detected.\n *\n * @param m - The matrix to split.\n * @param outPosition - Receives the translation.\n * @param outRotation - Receives the rotation as a unit quaternion.\n * @param outScale - Receives the per-axis scale.\n * @returns `true` on success; `false` when a basis column has (near) zero length, in which case\n * the outputs are left untouched.\n *\n * @example\n * ```ts\n * Mat4.decomposeToRef(node.worldMatrix, position, rotation, scale);\n * ```\n */\n static decomposeToRef(\n m: Mat4Like,\n outPosition: MutableVec3,\n outRotation: MutableQuat,\n outScale: MutableVec3,\n ): boolean {\n const m0 = m[0] ?? 0;\n const m1 = m[1] ?? 0;\n const m2 = m[2] ?? 0;\n const m4 = m[4] ?? 0;\n const m5 = m[5] ?? 0;\n const m6 = m[6] ?? 0;\n const m8 = m[8] ?? 0;\n const m9 = m[9] ?? 0;\n const m10 = m[10] ?? 0;\n const sx = Math.hypot(m0, m1, m2);\n const syAbs = Math.hypot(m4, m5, m6);\n const sz = Math.hypot(m8, m9, m10);\n if (sx <= 1e-8 || syAbs <= 1e-8 || sz <= 1e-8) {\n return false;\n }\n const sy = basisDeterminant(m) < 0 ? -syAbs : syAbs;\n const invSx = 1 / sx;\n const invSy = 1 / sy;\n const invSz = 1 / sz;\n // Read the translation before writing anything, so `outPosition` may alias nothing dangerous.\n const tx = m[12] ?? 0;\n const ty = m[13] ?? 0;\n const tz = m[14] ?? 0;\n basisToQuatToRef(\n m0 * invSx,\n m4 * invSy,\n m8 * invSz,\n m1 * invSx,\n m5 * invSy,\n m9 * invSz,\n m2 * invSx,\n m6 * invSy,\n m10 * invSz,\n outRotation,\n );\n const qx = outRotation.x;\n const qy = outRotation.y;\n const qz = outRotation.z;\n const qw = outRotation.w;\n const invLength = 1 / Math.hypot(qx, qy, qz, qw);\n outRotation.set(qx * invLength, qy * invLength, qz * invLength, qw * invLength);\n outPosition.set(tx, ty, tz);\n outScale.set(sx, sy, sz);\n return true;\n }\n\n /**\n * Multiplies two matrices.\n *\n * @param a - The left-hand matrix.\n * @param b - The right-hand matrix.\n * @returns A new matrix holding `a * b`. **Allocates.**\n */\n static multiply(a: Mat4Like, b: Mat4Like): Mat4 {\n return Mat4.multiplyToRef(a, b, new Mat4());\n }\n\n /**\n * Writes `a * b` into `out`. Acting on a column vector, `b` is applied first.\n *\n * @param a - The left-hand matrix.\n * @param b - The right-hand matrix.\n * @param out - The matrix to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef(a: Mat4Like, b: Mat4Like, out: Mat4): Mat4 {\n const a0 = a[0] ?? 0;\n const a1 = a[1] ?? 0;\n const a2 = a[2] ?? 0;\n const a3 = a[3] ?? 0;\n const a4 = a[4] ?? 0;\n const a5 = a[5] ?? 0;\n const a6 = a[6] ?? 0;\n const a7 = a[7] ?? 0;\n const a8 = a[8] ?? 0;\n const a9 = a[9] ?? 0;\n const a10 = a[10] ?? 0;\n const a11 = a[11] ?? 0;\n const a12 = a[12] ?? 0;\n const a13 = a[13] ?? 0;\n const a14 = a[14] ?? 0;\n const a15 = a[15] ?? 0;\n const b0 = b[0] ?? 0;\n const b1 = b[1] ?? 0;\n const b2 = b[2] ?? 0;\n const b3 = b[3] ?? 0;\n const b4 = b[4] ?? 0;\n const b5 = b[5] ?? 0;\n const b6 = b[6] ?? 0;\n const b7 = b[7] ?? 0;\n const b8 = b[8] ?? 0;\n const b9 = b[9] ?? 0;\n const b10 = b[10] ?? 0;\n const b11 = b[11] ?? 0;\n const b12 = b[12] ?? 0;\n const b13 = b[13] ?? 0;\n const b14 = b[14] ?? 0;\n const b15 = b[15] ?? 0;\n const e = out.elements;\n e[0] = a0 * b0 + a4 * b1 + a8 * b2 + a12 * b3;\n e[1] = a1 * b0 + a5 * b1 + a9 * b2 + a13 * b3;\n e[2] = a2 * b0 + a6 * b1 + a10 * b2 + a14 * b3;\n e[3] = a3 * b0 + a7 * b1 + a11 * b2 + a15 * b3;\n e[4] = a0 * b4 + a4 * b5 + a8 * b6 + a12 * b7;\n e[5] = a1 * b4 + a5 * b5 + a9 * b6 + a13 * b7;\n e[6] = a2 * b4 + a6 * b5 + a10 * b6 + a14 * b7;\n e[7] = a3 * b4 + a7 * b5 + a11 * b6 + a15 * b7;\n e[8] = a0 * b8 + a4 * b9 + a8 * b10 + a12 * b11;\n e[9] = a1 * b8 + a5 * b9 + a9 * b10 + a13 * b11;\n e[10] = a2 * b8 + a6 * b9 + a10 * b10 + a14 * b11;\n e[11] = a3 * b8 + a7 * b9 + a11 * b10 + a15 * b11;\n e[12] = a0 * b12 + a4 * b13 + a8 * b14 + a12 * b15;\n e[13] = a1 * b12 + a5 * b13 + a9 * b14 + a13 * b15;\n e[14] = a2 * b12 + a6 * b13 + a10 * b14 + a14 * b15;\n e[15] = a3 * b12 + a7 * b13 + a11 * b14 + a15 * b15;\n return out;\n }\n\n /**\n * Writes the inverse of `m` into `out`.\n *\n * @param m - The matrix to invert.\n * @param out - The matrix to write; may alias `m`. Left untouched when the inverse does not exist.\n * @returns `true` on success, `false` when `m` is singular. Returning a status rather than `null`\n * keeps the call allocation-free (coding standards §7).\n *\n * @example\n * ```ts\n * if (!Mat4.invertToRef(world, worldToLocal)) {\n * // degenerate scale — skip this entity\n * }\n * ```\n */\n static invertToRef(m: Mat4Like, out: Mat4): boolean {\n const a00 = m[0] ?? 0;\n const a01 = m[1] ?? 0;\n const a02 = m[2] ?? 0;\n const a03 = m[3] ?? 0;\n const a10 = m[4] ?? 0;\n const a11 = m[5] ?? 0;\n const a12 = m[6] ?? 0;\n const a13 = m[7] ?? 0;\n const a20 = m[8] ?? 0;\n const a21 = m[9] ?? 0;\n const a22 = m[10] ?? 0;\n const a23 = m[11] ?? 0;\n const a30 = m[12] ?? 0;\n const a31 = m[13] ?? 0;\n const a32 = m[14] ?? 0;\n const a33 = m[15] ?? 0;\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n const determinant = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n // Lite rejects at the same threshold (`lib/math/mat4-invert.js`), so both agree on which\n // matrices are singular.\n if (Math.abs(determinant) < 1e-10) {\n return false;\n }\n const inv = 1 / determinant;\n const e = out.elements;\n e[0] = (a11 * b11 - a12 * b10 + a13 * b09) * inv;\n e[1] = (a02 * b10 - a01 * b11 - a03 * b09) * inv;\n e[2] = (a31 * b05 - a32 * b04 + a33 * b03) * inv;\n e[3] = (a22 * b04 - a21 * b05 - a23 * b03) * inv;\n e[4] = (a12 * b08 - a10 * b11 - a13 * b07) * inv;\n e[5] = (a00 * b11 - a02 * b08 + a03 * b07) * inv;\n e[6] = (a32 * b02 - a30 * b05 - a33 * b01) * inv;\n e[7] = (a20 * b05 - a22 * b02 + a23 * b01) * inv;\n e[8] = (a10 * b10 - a11 * b08 + a13 * b06) * inv;\n e[9] = (a01 * b08 - a00 * b10 - a03 * b06) * inv;\n e[10] = (a30 * b04 - a31 * b02 + a33 * b00) * inv;\n e[11] = (a21 * b02 - a20 * b04 - a23 * b00) * inv;\n e[12] = (a11 * b07 - a10 * b09 - a12 * b06) * inv;\n e[13] = (a00 * b09 - a01 * b07 + a02 * b06) * inv;\n e[14] = (a31 * b01 - a30 * b03 - a32 * b00) * inv;\n e[15] = (a20 * b03 - a21 * b01 + a22 * b00) * inv;\n return true;\n }\n\n /**\n * Writes the transpose of `m` into `out`.\n *\n * @param m - The matrix to transpose.\n * @param out - The matrix to write; may alias `m`.\n * @returns `out`.\n */\n static transposeToRef(m: Mat4Like, out: Mat4): Mat4 {\n const m0 = m[0] ?? 0;\n const m1 = m[1] ?? 0;\n const m2 = m[2] ?? 0;\n const m3 = m[3] ?? 0;\n const m4 = m[4] ?? 0;\n const m5 = m[5] ?? 0;\n const m6 = m[6] ?? 0;\n const m7 = m[7] ?? 0;\n const m8 = m[8] ?? 0;\n const m9 = m[9] ?? 0;\n const m10 = m[10] ?? 0;\n const m11 = m[11] ?? 0;\n const m12 = m[12] ?? 0;\n const m13 = m[13] ?? 0;\n const m14 = m[14] ?? 0;\n const m15 = m[15] ?? 0;\n const e = out.elements;\n e[0] = m0;\n e[1] = m4;\n e[2] = m8;\n e[3] = m12;\n e[4] = m1;\n e[5] = m5;\n e[6] = m9;\n e[7] = m13;\n e[8] = m2;\n e[9] = m6;\n e[10] = m10;\n e[11] = m14;\n e[12] = m3;\n e[13] = m7;\n e[14] = m11;\n e[15] = m15;\n return out;\n }\n\n /**\n * The full 4×4 determinant.\n *\n * @param m - The matrix to measure.\n * @returns The determinant; zero means the matrix cannot be inverted.\n */\n static determinant(m: Mat4Like): number {\n const a00 = m[0] ?? 0;\n const a01 = m[1] ?? 0;\n const a02 = m[2] ?? 0;\n const a03 = m[3] ?? 0;\n const a10 = m[4] ?? 0;\n const a11 = m[5] ?? 0;\n const a12 = m[6] ?? 0;\n const a13 = m[7] ?? 0;\n const a20 = m[8] ?? 0;\n const a21 = m[9] ?? 0;\n const a22 = m[10] ?? 0;\n const a23 = m[11] ?? 0;\n const a30 = m[12] ?? 0;\n const a31 = m[13] ?? 0;\n const a32 = m[14] ?? 0;\n const a33 = m[15] ?? 0;\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n }\n\n /**\n * Builds a pure translation matrix.\n *\n * @param x - Translation along X, in metres.\n * @param y - Translation along Y, in metres.\n * @param z - Translation along Z, in metres.\n * @returns A new matrix. **Allocates.**\n */\n static translation(x: number, y: number, z: number): Mat4 {\n return Mat4.translationToRef(x, y, z, new Mat4());\n }\n\n /**\n * Writes a pure translation matrix into `out`.\n *\n * @param x - Translation along X, in metres.\n * @param y - Translation along Y, in metres.\n * @param z - Translation along Z, in metres.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static translationToRef(x: number, y: number, z: number, out: Mat4): Mat4 {\n const e = out.identity().elements;\n e[12] = x;\n e[13] = y;\n e[14] = z;\n return out;\n }\n\n /**\n * Builds a pure scaling matrix.\n *\n * @param x - Scale along X.\n * @param y - Scale along Y.\n * @param z - Scale along Z.\n * @returns A new matrix. **Allocates.**\n */\n static scaling(x: number, y: number, z: number): Mat4 {\n return Mat4.scalingToRef(x, y, z, new Mat4());\n }\n\n /**\n * Writes a pure scaling matrix into `out`.\n *\n * @param x - Scale along X.\n * @param y - Scale along Y.\n * @param z - Scale along Z.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static scalingToRef(x: number, y: number, z: number, out: Mat4): Mat4 {\n const e = out.identity().elements;\n e[0] = x;\n e[5] = y;\n e[10] = z;\n return out;\n }\n\n /**\n * Builds a pure rotation matrix from a quaternion.\n *\n * @param q - The rotation; assumed to be a unit quaternion.\n * @returns A new matrix. **Allocates.**\n */\n static fromQuat(q: QuatLike): Mat4 {\n return Mat4.fromQuatToRef(q, new Mat4());\n }\n\n /**\n * Writes a pure rotation matrix into `out`.\n *\n * @param q - The rotation; assumed to be a unit quaternion.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static fromQuatToRef(q: QuatLike, out: Mat4): Mat4 {\n return Mat4.composeToRef(ZERO_TRANSLATION, q, UNIT_SCALE, out);\n }\n\n /**\n * Builds a left-handed view matrix that places the camera at `eye` looking at `target`.\n *\n * @param eye - The camera position, in metres.\n * @param target - The point to look at, in metres.\n * @param up - The camera's up direction.\n * @returns A new matrix. **Allocates.**\n */\n static lookAtLH(eye: Vec3Like, target: Vec3Like, up: Vec3Like): Mat4 {\n return Mat4.lookAtLHToRef(eye, target, up, new Mat4());\n }\n\n /**\n * Writes a left-handed view matrix into `out`. Reproduces Babylon Lite's `mat4LookAtLHToRef`,\n * including its degenerate-input behaviour: when `eye` and `target` coincide, or when `up` is\n * parallel to the view direction, `out` becomes the identity.\n *\n * @param eye - The camera position, in metres.\n * @param target - The point to look at, in metres.\n * @param up - The camera's up direction.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static lookAtLHToRef(eye: Vec3Like, target: Vec3Like, up: Vec3Like, out: Mat4): Mat4 {\n const ex = eye.x;\n const ey = eye.y;\n const ez = eye.z;\n let zx = target.x - ex;\n let zy = target.y - ey;\n let zz = target.z - ez;\n const zLength = Math.hypot(zx, zy, zz);\n if (zLength < 1e-10) {\n return out.identity();\n }\n const invZ = 1 / zLength;\n zx *= invZ;\n zy *= invZ;\n zz *= invZ;\n let xx = up.y * zz - up.z * zy;\n let xy = up.z * zx - up.x * zz;\n let xz = up.x * zy - up.y * zx;\n const xLength = Math.hypot(xx, xy, xz);\n if (xLength < 1e-10) {\n return out.identity();\n }\n const invX = 1 / xLength;\n xx *= invX;\n xy *= invX;\n xz *= invX;\n const yx = zy * xz - zz * xy;\n const yy = zz * xx - zx * xz;\n const yz = zx * xy - zy * xx;\n const e = out.elements;\n e[0] = xx;\n e[1] = yx;\n e[2] = zx;\n e[3] = 0;\n e[4] = xy;\n e[5] = yy;\n e[6] = zy;\n e[7] = 0;\n e[8] = xz;\n e[9] = yz;\n e[10] = zz;\n e[11] = 0;\n e[12] = -(xx * ex + xy * ey + xz * ez);\n e[13] = -(yx * ex + yy * ey + yz * ez);\n e[14] = -(zx * ex + zy * ey + zz * ez);\n e[15] = 1;\n return out;\n }\n\n /**\n * Builds a left-handed perspective projection.\n *\n * @param fovDegrees - The vertical field of view, in degrees.\n * @param aspect - The viewport's width divided by its height.\n * @param near - The near plane distance, in metres.\n * @param far - The far plane distance, in metres.\n * @returns A new matrix. **Allocates.**\n */\n static perspectiveLH(fovDegrees: number, aspect: number, near: number, far: number): Mat4 {\n return Mat4.perspectiveLHToRef(fovDegrees, aspect, near, far, new Mat4());\n }\n\n /**\n * Writes a left-handed perspective projection into `out`, matching Babylon Lite's\n * `mat4PerspectiveLHToRef` — which is a **reverse-depth** projection: the near plane maps to\n * clip-space depth 1 and the far plane to 0, the arrangement that keeps float depth precise.\n *\n * @param fovDegrees - The vertical field of view, in degrees.\n * @param aspect - The viewport's width divided by its height.\n * @param near - The near plane distance, in metres.\n * @param far - The far plane distance, in metres.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static perspectiveLHToRef(fovDegrees: number, aspect: number, near: number, far: number, out: Mat4): Mat4 {\n const cot = 1 / Math.tan(degToRad(fovDegrees) * 0.5);\n const range = far - near;\n const e = out.elements;\n e[0] = cot / aspect;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 0;\n e[5] = cot;\n e[6] = 0;\n e[7] = 0;\n e[8] = 0;\n e[9] = 0;\n e[10] = -near / range;\n e[11] = 1;\n e[12] = 0;\n e[13] = 0;\n e[14] = (far * near) / range;\n e[15] = 0;\n return out;\n }\n\n /**\n * Builds a centred left-handed orthographic projection.\n *\n * @param width - The view width, in metres.\n * @param height - The view height, in metres.\n * @param near - The near plane distance, in metres.\n * @param far - The far plane distance, in metres.\n * @returns A new matrix. **Allocates.**\n */\n static orthoLH(width: number, height: number, near: number, far: number): Mat4 {\n return Mat4.orthoLHToRef(width, height, near, far, new Mat4());\n }\n\n /**\n * Writes a centred left-handed orthographic projection into `out`, with the same reverse-depth\n * convention as {@link Mat4.perspectiveLHToRef}.\n *\n * @param width - The view width, in metres.\n * @param height - The view height, in metres.\n * @param near - The near plane distance, in metres.\n * @param far - The far plane distance, in metres.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static orthoLHToRef(width: number, height: number, near: number, far: number, out: Mat4): Mat4 {\n const halfWidth = width * 0.5;\n const halfHeight = height * 0.5;\n return Mat4.orthoOffCenterLHToRef(-halfWidth, halfWidth, -halfHeight, halfHeight, near, far, out);\n }\n\n /**\n * Writes an off-centre left-handed orthographic projection into `out`, reproducing Babylon Lite's\n * `mat4OrthoOffCenterLHToRef` (reverse depth).\n *\n * @param left - The left clip plane, in metres.\n * @param right - The right clip plane, in metres.\n * @param bottom - The bottom clip plane, in metres.\n * @param top - The top clip plane, in metres.\n * @param near - The near plane distance, in metres.\n * @param far - The far plane distance, in metres.\n * @param out - The matrix to write.\n * @returns `out`.\n */\n static orthoOffCenterLHToRef(\n left: number,\n right: number,\n bottom: number,\n top: number,\n near: number,\n far: number,\n out: Mat4,\n ): Mat4 {\n const range = far - near;\n const e = out.elements;\n e[0] = 2 / (right - left);\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 0;\n e[5] = 2 / (top - bottom);\n e[6] = 0;\n e[7] = 0;\n e[8] = 0;\n e[9] = 0;\n e[10] = -1 / range;\n e[11] = 0;\n e[12] = (left + right) / (left - right);\n e[13] = (top + bottom) / (bottom - top);\n e[14] = far / range;\n e[15] = 1;\n return out;\n }\n\n /**\n * Reads a matrix's translation.\n *\n * @param m - The matrix to read.\n * @param out - The vector to write.\n * @returns `out`.\n */\n static getTranslationToRef<TOut extends MutableVec3>(m: Mat4Like, out: TOut): TOut {\n out.set(m[12] ?? 0, m[13] ?? 0, m[14] ?? 0);\n return out;\n }\n\n /**\n * Reads a matrix's per-axis scale as the lengths of its basis columns, negating Y for a mirrored\n * matrix exactly as {@link Mat4.decomposeToRef} does.\n *\n * @param m - The matrix to read.\n * @param out - The vector to write.\n * @returns `out`.\n */\n static getScaleToRef<TOut extends MutableVec3>(m: Mat4Like, out: TOut): TOut {\n const sx = Math.hypot(m[0] ?? 0, m[1] ?? 0, m[2] ?? 0);\n const syAbs = Math.hypot(m[4] ?? 0, m[5] ?? 0, m[6] ?? 0);\n const sz = Math.hypot(m[8] ?? 0, m[9] ?? 0, m[10] ?? 0);\n out.set(sx, basisDeterminant(m) < 0 ? -syAbs : syAbs, sz);\n return out;\n }\n\n /**\n * Reads a matrix's rotation, dividing the scale out of the basis first.\n *\n * @param m - The matrix to read.\n * @param out - The quaternion to write. Left untouched when a basis column has zero length.\n * @returns `out`.\n */\n static getRotationToRef<TOut extends MutableQuat>(m: Mat4Like, out: TOut): TOut {\n const m0 = m[0] ?? 0;\n const m1 = m[1] ?? 0;\n const m2 = m[2] ?? 0;\n const m4 = m[4] ?? 0;\n const m5 = m[5] ?? 0;\n const m6 = m[6] ?? 0;\n const m8 = m[8] ?? 0;\n const m9 = m[9] ?? 0;\n const m10 = m[10] ?? 0;\n const sx = Math.hypot(m0, m1, m2);\n const syAbs = Math.hypot(m4, m5, m6);\n const sz = Math.hypot(m8, m9, m10);\n if (sx <= 1e-8 || syAbs <= 1e-8 || sz <= 1e-8) {\n return out;\n }\n const invSx = 1 / sx;\n const invSy = 1 / (basisDeterminant(m) < 0 ? -syAbs : syAbs);\n const invSz = 1 / sz;\n basisToQuatToRef(\n m0 * invSx,\n m4 * invSy,\n m8 * invSz,\n m1 * invSx,\n m5 * invSy,\n m9 * invSz,\n m2 * invSx,\n m6 * invSy,\n m10 * invSz,\n out,\n );\n const invLength = 1 / Math.hypot(out.x, out.y, out.z, out.w);\n out.set(out.x * invLength, out.y * invLength, out.z * invLength, out.w * invLength);\n return out;\n }\n\n /**\n * Transforms a point by a matrix, applying translation and the perspective divide.\n *\n * @param m - The transformation.\n * @param point - The point to transform, in metres.\n * @param out - The vector to write; may alias `point`.\n * @returns `out`.\n */\n static transformPointToRef<TOut extends MutableVec3>(m: Mat4Like, point: Vec3Like, out: TOut): TOut {\n const x = point.x;\n const y = point.y;\n const z = point.z;\n const rx = x * (m[0] ?? 0) + y * (m[4] ?? 0) + z * (m[8] ?? 0) + (m[12] ?? 0);\n const ry = x * (m[1] ?? 0) + y * (m[5] ?? 0) + z * (m[9] ?? 0) + (m[13] ?? 0);\n const rz = x * (m[2] ?? 0) + y * (m[6] ?? 0) + z * (m[10] ?? 0) + (m[14] ?? 0);\n const invW = 1 / (x * (m[3] ?? 0) + y * (m[7] ?? 0) + z * (m[11] ?? 0) + (m[15] ?? 0));\n out.set(rx * invW, ry * invW, rz * invW);\n return out;\n }\n\n /**\n * Transforms a direction by a matrix, ignoring translation. Note that this is the plain basis\n * transform: a non-uniformly scaled matrix needs its inverse-transpose to keep normals correct.\n *\n * @param m - The transformation.\n * @param direction - The direction to transform.\n * @param out - The vector to write; may alias `direction`.\n * @returns `out`.\n */\n static transformDirectionToRef<TOut extends MutableVec3>(m: Mat4Like, direction: Vec3Like, out: TOut): TOut {\n const x = direction.x;\n const y = direction.y;\n const z = direction.z;\n out.set(\n x * (m[0] ?? 0) + y * (m[4] ?? 0) + z * (m[8] ?? 0),\n x * (m[1] ?? 0) + y * (m[5] ?? 0) + z * (m[9] ?? 0),\n x * (m[2] ?? 0) + y * (m[6] ?? 0) + z * (m[10] ?? 0),\n );\n return out;\n }\n\n /**\n * Compares two matrices element by element, with a tolerance.\n *\n * @param a - The first matrix.\n * @param b - The second matrix.\n * @param epsilon - The largest per-element difference still considered equal.\n * @returns `true` when every element matches within `epsilon`.\n */\n static equalsWithEpsilon(a: Mat4Like, b: Mat4Like, epsilon: number = EPSILON): boolean {\n for (let i = 0; i < 16; i++) {\n if (Math.abs((a[i] ?? 0) - (b[i] ?? 0)) > epsilon) {\n return false;\n }\n }\n return true;\n }\n}\n\n/**\n * The zero translation {@link Mat4.fromQuatToRef} composes with. Module-scope constant, frozen so it\n * can never be written through.\n */\nconst ZERO_TRANSLATION: Vec3Like = Object.freeze({ x: 0, y: 0, z: 0 });\n\n/**\n * The unit scale {@link Mat4.fromQuatToRef} composes with.\n */\nconst UNIT_SCALE: Vec3Like = Object.freeze({ x: 1, y: 1, z: 1 });\n\n/**\n * A frozen identity matrix, for the common case of \"no transform\". It is a plain {@link Mat4Like}\n * rather than a {@link Mat4} because a `Float32Array` cannot be frozen — pass it to anything that\n * reads a matrix, and use `new Mat4()` when you need one you can write to.\n *\n * @example\n * ```ts\n * Mat4.transformPointToRef(MAT4_IDENTITY, point, out); // copies the point\n * ```\n *\n * @public\n */\nexport const MAT4_IDENTITY: Mat4Like = Object.freeze({\n length: 16,\n 0: 1,\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 1,\n 6: 0,\n 7: 0,\n 8: 0,\n 9: 0,\n 10: 1,\n 11: 0,\n 12: 0,\n 13: 0,\n 14: 0,\n 15: 1,\n} as const);\n","import {\n createFreeCamera,\n disableOrthographicCamera,\n enableOrthographicCamera,\n getEffectiveAspectRatio,\n getProjectionMatrix,\n getViewMatrix,\n getViewProjectionMatrix,\n resolveCameraViewport,\n type Camera,\n type FreeCamera,\n type OrthographicBounds,\n type PixelViewport,\n type Ray,\n type SceneContext,\n type SceneNode,\n} from \"@babylonjs/lite\";\nimport { Mat4 } from \"../math/mat4.js\";\nimport { degToRad } from \"../math/math-utils.js\";\nimport type { MutableMat4Like, MutableVec3Like } from \"./node.js\";\nimport type { Vec3Like } from \"../math/types.js\";\n\n/**\n * Camera half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.1). It owns the\n * Lite `FreeCamera` a `Camera` component wraps: projection, clip planes, viewport, and the\n * screen/world conversions the component exposes as methods.\n *\n * Everything here is `@internal`; the `Camera` component is the public surface.\n *\n * ## What Lite does with a camera (verified against `@babylonjs/lite@1.27.0`)\n *\n * - `createFreeCamera(position, target)` (`index.d.ts` 2535, `lib/camera/free-camera.js`) builds a\n * camera whose **local** matrix is `lookAtWorldLH(position, target, up)` and whose world matrix\n * is `parentWorld × local`. So a camera created at the origin looking down `+Z` and parented to\n * an entity node has exactly the entity's world transform — that is what makes spike S2.1 work\n * and why the adapter never writes `camera.position` for a parented camera.\n * - `getViewMatrix(camera)` (`index.d.ts` 6013, `lib/camera/camera.js`) is the *inverse* of the\n * world matrix, built by transposing the rotation block and negating the translation, cached\n * against `worldMatrixVersion`. It therefore follows the parent automatically.\n * - `getProjectionMatrix(camera, aspectRatio)` (`index.d.ts` 5955) is a **reverse-depth**\n * left-handed projection (near maps to clip depth 1, far to 0) and switches to the orthographic\n * projector whenever `camera.ortho` is set.\n * - `resolveCameraViewport(camera, w, h)` (`index.d.ts` 9941, `lib/camera/viewport.js`) converts a\n * Babylon-style normalized viewport, whose `y` is measured **from the bottom**, into integer\n * render-target pixels whose `y` is measured **from the top**: `y0 = clamp01(1 - y - height)`.\n *\n * ## Units\n *\n * Lite stores the vertical field of view and the spot-cone angle in radians; ignifx public API is\n * in degrees (coding standards §5.1). The conversion happens here, at the boundary, and nowhere\n * else.\n */\n\n/**\n * The Babylon Lite camera an ignifx `Camera` component owns, re-exported under an ignifx name so\n * feature code can name the type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4,\n * coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteCamera = FreeCamera;\n\n/**\n * The live orthographic bounds `enableOrthographicCamera` returns, re-exported under an ignifx name.\n *\n * @internal\n */\nexport type LiteOrthographicBounds = OrthographicBounds;\n\n/**\n * A ray whose `origin` and `direction` are written in place. Lite's `Ray` uses three-element\n * tuples, which are mutable, so {@link screenToRay} can fill a caller-owned ray without allocating\n * (coding standards §7).\n *\n * @internal\n */\nexport type MutableRay = Ray;\n\n/** Scratch inverse view-projection matrix, created on first use (coding standards §4). */\nlet inverseViewProjection: Mat4 | null = null;\n\n/**\n * Creates the Lite camera an ignifx `Camera` component owns and parents it under the entity's\n * transform node.\n *\n * @remarks\n * The camera is created at the local origin looking down local `+Z`, ignifx's forward axis\n * (ADR-0011). Its own position and target are never touched again: the entity's node supplies the\n * transform, so the component has no follow logic (`docs/architecture/07-rendering.md` §2.1).\n *\n * @param parent - The entity's transform node, or `null` for a camera in world space.\n * @returns The camera. It is not attached to any scene; call {@link setSceneCamera} for that.\n *\n * @example\n * ```ts\n * const camera = createCameraUnderNode(entityNode);\n * setCameraPerspective(camera, 60);\n * setSceneCamera(scene, camera);\n * ```\n *\n * @internal\n */\nexport function createCameraUnderNode(parent: SceneNode | null): FreeCamera {\n const camera = createFreeCamera({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 1 });\n camera.parent = parent;\n return camera;\n}\n\n/**\n * Re-parents a camera, keeping its local position and target — the entity's node defines the view.\n *\n * @remarks\n * Unlike `linkParent` in `./node.ts` this does not maintain the parent's `children` array. Lite\n * types `SceneNode.children` as `SceneNode[]` and a camera is not a scene node; nothing in Lite\n * walks an ignifx transform node's children either, because ignifx transform nodes are never added\n * to a scene (`docs/architecture/02-scene-graph.md` §5.1). The `parent` link alone is what\n * `worldMatrix` reads.\n *\n * @param camera - The camera to move.\n * @param parent - The new parent node, or `null` to detach the camera to world space.\n *\n * @internal\n */\nexport function setCameraParent(camera: FreeCamera, parent: SceneNode | null): void {\n camera.parent = parent;\n}\n\n/**\n * Switches a camera to a perspective projection with the given vertical field of view.\n *\n * @param camera - The camera to configure.\n * @param fovDegrees - The vertical field of view, in degrees.\n *\n * @internal\n */\nexport function setCameraPerspective(camera: Camera, fovDegrees: number): void {\n camera.fov = degToRad(fovDegrees);\n if (camera.ortho !== null && camera.ortho !== undefined) {\n disableOrthographicCamera(camera);\n }\n}\n\n/**\n * Switches a camera to an orthographic projection of the given half-height.\n *\n * @remarks\n * Only `halfHeight` is set; the four clip planes are left `null` so Lite derives them from the\n * half-height and the render target's aspect ratio (`OrthographicBounds`, `index.d.ts` 7803),\n * which is the behaviour `Camera.orthographicSize` promises. Calling this twice replaces the\n * bounds object, so the adapter keeps the returned handle and mutates it through\n * {@link setCameraOrthographicSize} instead.\n *\n * @param camera - The camera to configure.\n * @param halfHeight - Half of the visible height, in metres.\n * @returns The live bounds object; assigning to its fields takes effect on the next frame.\n *\n * @internal\n */\nexport function setCameraOrthographic(camera: Camera, halfHeight: number): OrthographicBounds {\n const existing = camera.ortho;\n if (existing !== null && existing !== undefined) {\n existing.halfHeight = halfHeight;\n return existing;\n }\n return enableOrthographicCamera(camera, { halfHeight });\n}\n\n/**\n * Changes the half-height of an orthographic camera. Halving it doubles the zoom.\n *\n * @param bounds - The bounds {@link setCameraOrthographic} returned.\n * @param halfHeight - The new half-height, in metres.\n *\n * @internal\n */\nexport function setCameraOrthographicSize(bounds: OrthographicBounds, halfHeight: number): void {\n bounds.halfHeight = halfHeight;\n}\n\n/**\n * Sets the near and far clip planes.\n *\n * @param camera - The camera to configure.\n * @param near - The near plane distance, in metres.\n * @param far - The far plane distance, in metres.\n *\n * @internal\n */\nexport function setCameraClipPlanes(camera: Camera, near: number, far: number): void {\n camera.nearPlane = near;\n camera.farPlane = far;\n}\n\n/**\n * Sets the camera's normalized viewport, in Babylon's convention: the origin is the **bottom** left\n * of the render target.\n *\n * @remarks\n * The viewport object is reused when one is already installed, so a per-frame viewport animation\n * allocates nothing (coding standards §7).\n *\n * @param camera - The camera to configure.\n * @param x - The left edge, 0 to 1.\n * @param y - The bottom edge, 0 to 1.\n * @param width - The width, 0 to 1.\n * @param height - The height, 0 to 1.\n *\n * @internal\n */\nexport function setCameraViewport(camera: Camera, x: number, y: number, width: number, height: number): void {\n const existing = camera.viewport;\n if (existing === undefined) {\n camera.viewport = { x, y, width, height };\n return;\n }\n existing.x = x;\n existing.y = y;\n existing.width = width;\n existing.height = height;\n}\n\n/**\n * Restores the camera's viewport to the full render target.\n *\n * @param camera - The camera to configure.\n *\n * @internal\n */\nexport function resetCameraViewport(camera: Camera): void {\n setCameraViewport(camera, 0, 0, 1, 1);\n}\n\n/**\n * Resolves a camera's normalized viewport to integer render-target pixels.\n *\n * @remarks\n * Lite flips the y axis here: the normalized viewport measures `y` from the bottom (Babylon), the\n * pixel viewport measures it from the top (WebGPU). Verified in `lib/camera/viewport.js`, which\n * computes `y = floor(clamp01(1 - v.y - v.height) * targetHeight)`.\n *\n * @param camera - The camera, or `null` for the full target.\n * @param targetWidth - The render target width, in pixels.\n * @param targetHeight - The render target height, in pixels.\n * @returns A fresh pixel viewport. **Allocates** — Lite builds the object; do not call per frame.\n *\n * @internal\n */\nexport function resolveViewportPixels(camera: Camera | null, targetWidth: number, targetHeight: number): PixelViewport {\n return resolveCameraViewport(camera, targetWidth, targetHeight);\n}\n\n/**\n * The aspect ratio Lite projects with: the render target's ratio scaled by the camera's viewport.\n *\n * @param camera - The camera, or `null` for an unrestricted viewport.\n * @param targetWidth - The render target width, in pixels.\n * @param targetHeight - The render target height, in pixels.\n * @returns Width divided by height.\n *\n * @internal\n */\nexport function cameraAspectRatio(camera: Camera | null, targetWidth: number, targetHeight: number): number {\n return getEffectiveAspectRatio(camera, targetWidth, targetHeight);\n}\n\n/**\n * Copies the camera's view matrix (the inverse of its world matrix) into `out`.\n *\n * @param camera - The camera to read.\n * @param out - A sink of at least 16 elements, written column-major.\n * @returns `out`, for chaining.\n *\n * @internal\n */\nexport function readViewMatrix(camera: Camera, out: MutableMat4Like): MutableMat4Like {\n return copyMatrix(getViewMatrix(camera), out);\n}\n\n/**\n * Copies the camera's projection matrix into `out`.\n *\n * @param camera - The camera to read.\n * @param aspectRatio - Width divided by height, from {@link cameraAspectRatio}.\n * @param out - A sink of at least 16 elements, written column-major.\n * @returns `out`, for chaining.\n *\n * @internal\n */\nexport function readProjectionMatrix(camera: Camera, aspectRatio: number, out: MutableMat4Like): MutableMat4Like {\n return copyMatrix(getProjectionMatrix(camera, aspectRatio), out);\n}\n\n/**\n * Copies the camera's combined view-projection matrix into `out`.\n *\n * @param camera - The camera to read.\n * @param aspectRatio - Width divided by height, from {@link cameraAspectRatio}.\n * @param out - A sink of at least 16 elements, written column-major.\n * @returns `out`, for chaining.\n *\n * @internal\n */\nexport function readViewProjectionMatrix(camera: Camera, aspectRatio: number, out: MutableMat4Like): MutableMat4Like {\n return copyMatrix(getViewProjectionMatrix(camera, aspectRatio), out);\n}\n\n/**\n * Makes a camera the one a scene renders through, or clears it.\n *\n * @remarks\n * Lite renders through exactly one camera per scene (`SceneContext.camera`, `index.d.ts` 10072);\n * a scene with no camera draws nothing. Choosing between several enabled ignifx cameras by\n * `priority` is the component layer's job.\n *\n * @param scene - The render scene.\n * @param camera - The camera to render through, or `null` for none.\n *\n * @internal\n */\nexport function setSceneCamera(scene: SceneContext, camera: Camera | null): void {\n scene.camera = camera;\n}\n\n/**\n * Builds a world-space ray through a point on the render target.\n *\n * @remarks\n * This reproduces Lite's own `createPickingRay` (`lib/picking/ray.js`), which is not exported from\n * the package, and the coordinate handling of `pickAsync` (`lib/picking/gpu-picker.js` lines\n * 176–193): the pixel is made relative to the camera's **pixel** viewport, the projection uses that\n * viewport's aspect ratio, and the normalized device coordinates are\n * `(2x/w - 1, 1 - 2y/h)`. Because the projection is reverse-depth, clip depth `1` unprojects to the\n * near plane and `0` to the far plane.\n *\n * The ray is written into `out`, so a picking loop allocates nothing.\n *\n * @param camera - The camera to look through.\n * @param x - The pixel x inside the viewport, measured from its left edge.\n * @param y - The pixel y inside the viewport, measured from its top edge.\n * @param viewportWidth - The viewport width, in pixels.\n * @param viewportHeight - The viewport height, in pixels.\n * @param out - The ray to fill.\n * @returns `out` when the ray could be built, or `null` when the view-projection matrix is\n * singular (a zero-sized viewport, or a degenerate projection).\n *\n * @example\n * ```ts\n * const ray: MutableRay = { origin: [0, 0, 0], direction: [0, 0, 1], length: 1 };\n * const viewport = resolveViewportPixels(camera, canvas.width, canvas.height);\n * screenToRay(camera, px - viewport.x, py - viewport.y, viewport.width, viewport.height, ray);\n * ```\n *\n * @internal\n */\nexport function screenToRay(\n camera: Camera,\n x: number,\n y: number,\n viewportWidth: number,\n viewportHeight: number,\n out: MutableRay,\n): MutableRay | null {\n if (viewportWidth <= 0 || viewportHeight <= 0) {\n return null;\n }\n const inverse = (inverseViewProjection ??= new Mat4());\n const viewProjection = getViewProjectionMatrix(camera, viewportWidth / viewportHeight);\n if (!Mat4.invertToRef(viewProjection, inverse)) {\n return null;\n }\n const ndcX = (2 * x) / viewportWidth - 1;\n const ndcY = 1 - (2 * y) / viewportHeight;\n const origin = out.origin;\n const direction = out.direction;\n unproject(inverse, ndcX, ndcY, 1, origin);\n unproject(inverse, ndcX, ndcY, 0, direction);\n const dx = direction[0] - origin[0];\n const dy = direction[1] - origin[1];\n const dz = direction[2] - origin[2];\n const length = Math.sqrt(dx * dx + dy * dy + dz * dz);\n if (!(length > 0)) {\n return null;\n }\n const inverseLength = 1 / length;\n direction[0] = dx * inverseLength;\n direction[1] = dy * inverseLength;\n direction[2] = dz * inverseLength;\n out.length = length;\n return out;\n}\n\n/**\n * Projects a world-space point onto the render target.\n *\n * @remarks\n * `out.x`/`out.y` are pixels inside the camera's viewport, measured from its **top** left, matching\n * {@link screenToRay}'s input; `out.z` is the clip-space depth, which is `1` at the near plane and\n * `0` at the far plane because Lite's projection is reverse-depth.\n *\n * @param camera - The camera to look through.\n * @param point - The world-space point.\n * @param viewportWidth - The viewport width, in pixels.\n * @param viewportHeight - The viewport height, in pixels.\n * @param out - Receives the pixel position and the clip depth.\n * @returns `true` when the point is in front of the camera; `false` when it is behind it, in which\n * case `out` holds the mirrored projection and should be ignored.\n *\n * @internal\n */\nexport function worldToScreen(\n camera: Camera,\n point: Vec3Like,\n viewportWidth: number,\n viewportHeight: number,\n out: MutableVec3Like,\n): boolean {\n const viewProjection = getViewProjectionMatrix(camera, viewportWidth / viewportHeight);\n const x = point.x;\n const y = point.y;\n const z = point.z;\n const clipX =\n element(viewProjection, 0) * x +\n element(viewProjection, 4) * y +\n element(viewProjection, 8) * z +\n element(viewProjection, 12);\n const clipY =\n element(viewProjection, 1) * x +\n element(viewProjection, 5) * y +\n element(viewProjection, 9) * z +\n element(viewProjection, 13);\n const clipZ =\n element(viewProjection, 2) * x +\n element(viewProjection, 6) * y +\n element(viewProjection, 10) * z +\n element(viewProjection, 14);\n const clipW =\n element(viewProjection, 3) * x +\n element(viewProjection, 7) * y +\n element(viewProjection, 11) * z +\n element(viewProjection, 15);\n if (clipW === 0) {\n out.x = 0;\n out.y = 0;\n out.z = 0;\n return false;\n }\n const inverseW = 1 / clipW;\n out.x = (clipX * inverseW + 1) * 0.5 * viewportWidth;\n out.y = (1 - clipY * inverseW) * 0.5 * viewportHeight;\n out.z = clipZ * inverseW;\n return clipW > 0;\n}\n\n/**\n * Reads one element of a matrix-like value.\n *\n * @remarks\n * `noUncheckedIndexedAccess` widens every index read to `number | undefined`, and a matrix has no\n * holes, so the fallback is unreachable. Funnelling every read through one function keeps that\n * single dead branch in one place instead of scattering thirty of them through the hot paths.\n *\n * @param matrix - The matrix to read.\n * @param index - The column-major element index, 0 to 15.\n * @returns The element.\n */\nfunction element(matrix: { readonly [index: number]: number }, index: number): number {\n return matrix[index] ?? 0;\n}\n\n/**\n * Unprojects one normalized device coordinate through an inverse view-projection matrix.\n *\n * @param inverse - The inverted view-projection matrix.\n * @param ndcX - The device x, -1 to 1.\n * @param ndcY - The device y, -1 to 1.\n * @param depth - The clip depth: `1` for the near plane, `0` for the far plane.\n * @param out - Receives the world-space point.\n */\nfunction unproject(inverse: Mat4, ndcX: number, ndcY: number, depth: number, out: [number, number, number]): void {\n const e = inverse.elements;\n const x = element(e, 0) * ndcX + element(e, 4) * ndcY + element(e, 8) * depth + element(e, 12);\n const y = element(e, 1) * ndcX + element(e, 5) * ndcY + element(e, 9) * depth + element(e, 13);\n const z = element(e, 2) * ndcX + element(e, 6) * ndcY + element(e, 10) * depth + element(e, 14);\n const w = element(e, 3) * ndcX + element(e, 7) * ndcY + element(e, 11) * depth + element(e, 15);\n const inverseW = w === 0 ? 0 : 1 / w;\n out[0] = x * inverseW;\n out[1] = y * inverseW;\n out[2] = z * inverseW;\n}\n\n/**\n * Copies 16 matrix elements into an output sink.\n *\n * @param source - The matrix to read.\n * @param out - The sink to write.\n * @returns `out`.\n */\nfunction copyMatrix(source: { readonly [index: number]: number }, out: MutableMat4Like): MutableMat4Like {\n for (let i = 0; i < 16; i++) {\n out[i] = element(source, i);\n }\n return out;\n}\n","import {\n createTransformNode,\n mat4Decompose,\n setParent,\n setSubtreeVisible,\n type IWorldMatrixProvider,\n type SceneNode,\n} from \"@babylonjs/lite\";\nimport type { MutableQuat, MutableVec3 } from \"../math/types.js\";\n\n/**\n * Scene-graph half of the Babylon Lite adapter: the transform node primitives the kernel's\n * `Transform` component is built from (`docs/architecture/02-scene-graph.md` §5, §5.1). Together\n * with the other files in this directory it is the only place in the package allowed to import\n * `@babylonjs/lite` (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * Everything here is `@internal`: the kernel decides what becomes public API and what stays behind\n * `Transform`. Nothing in this file is re-exported from `src/index.ts`.\n *\n * ## How Lite computes `worldMatrix` (verified against `@babylonjs/lite@1.27.0`\n * `lib/scene/world-matrix-state.js` and `lib/scene/scene-node.js`)\n *\n * Every node owns a *world-matrix state* holding a cached world matrix, a version counter, a\n * parent link, and a list of the states of the children that were linked through that parent\n * property. The rules that follow from the source are:\n *\n * 1. Writing any TRS value calls the node's dirty hook, which clears the cache, increments the\n * version, and **recursively invalidates every linked descendant** — invalidation is pushed\n * down eagerly, not polled.\n * 2. `ObservableVec3`/`ObservableQuat` per-component setters only fire that hook when the value\n * actually changes; the bulk `set(...)`/`copyFrom(...)` methods fire it unconditionally. So\n * `node.position.x = node.position.x` does not bump the version, while\n * `node.position.set(sameX, sameY, sameZ)` does.\n * 3. `worldMatrix` is a getter. On a cache miss it composes the local matrix from TRS and, when a\n * parent is linked, returns `parentWorld × local` (column-major; translation in elements\n * 12/13/14). A node with no parent returns its local matrix directly.\n * 4. A parent that is a plain {@link IWorldMatrixProvider} rather than a Lite scene node (a camera,\n * for instance) cannot be invalidated eagerly, so the child polls `parent.worldMatrixVersion`\n * on every `worldMatrix` and `worldMatrixVersion` read instead.\n * 5. Nothing in that path touches the scene: a transform node never needs `addToScene` for its\n * matrices to be correct. Only renderable objects do (`docs/architecture/02-scene-graph.md`\n * §5.1).\n */\n\n/**\n * A mutable `{ x, y, z }` accepted as an output parameter. Deliberately the minimal shape: Lite's\n * `Vec3`, the math module's `MutableVec3` (which adds `set`/`copyFrom`), a live `ObservableVec3` over\n * a node's TRS, and a plain object literal all satisfy it, so nothing has to be converted.\n *\n * @internal\n */\nexport interface MutableVec3Like {\n /** The x component. */\n x: number;\n /** The y component. */\n y: number;\n /** The z component. */\n z: number;\n}\n\n/**\n * A mutable `{ x, y, z, w }` accepted as an output parameter. The minimal shape, for the same reason\n * as {@link MutableVec3Like}: Lite's `Quat`, the math module's `MutableQuat`, and a plain object\n * literal all satisfy it.\n *\n * @internal\n */\nexport interface MutableQuatLike {\n /** The x component of the quaternion's vector part. */\n x: number;\n /** The y component of the quaternion's vector part. */\n y: number;\n /** The z component of the quaternion's vector part. */\n z: number;\n /** The scalar part. */\n w: number;\n}\n\n/**\n * A writable 16-element matrix sink in column-major order. `Float32Array` (including the math\n * module's `Mat4.elements`), `Float64Array`, and a plain `number[]` all satisfy it, which is why\n * `length` is a plain `number`: `Float32Array` cannot express the literal `16` that Lite's read-only\n * `Mat4` and the math module's `Mat4Like` declare.\n *\n * @internal\n */\nexport interface MutableMat4Like {\n /** Element count; callers must supply at least 16 slots. */\n readonly length: number;\n /** Column-major element access. */\n [index: number]: number;\n}\n\n/**\n * The ignifx identity written into a Lite node's metadata bag so picking results and physics bodies\n * resolve back to the owning entity (`docs/architecture/00-overview.md` §5,\n * `docs/architecture/02-scene-graph.md` §10).\n *\n * @internal\n */\nexport interface NodeTag {\n /** The dense runtime handle of the entity that owns the node. */\n readonly entity: number;\n /** The component that created the node, when the node is not the entity's own transform. */\n readonly component?: number;\n}\n\n/** The single key ignifx owns inside Lite's open `metadata` record. */\nconst METADATA_KEY = \"ignifx\";\n\n/** Number of elements in a 4x4 matrix. */\nconst MATRIX_LENGTH = 16;\n\n/**\n * Creates a pure transform node at the origin with an identity rotation and unit scale.\n *\n * @remarks\n * The node is deliberately **not** added to any Lite scene: a transform node is only a matrix\n * provider, and `worldMatrix` is valid the moment the node exists (see rule 5 in the module\n * documentation). Renderable Lite objects created by components are parented under it and added\n * with `addToScene` separately.\n *\n * @param name - A human-readable name; Lite never uses it for lookup and it need not be unique.\n * @returns A fresh, unparented transform node.\n *\n * @example\n * ```ts\n * const node = createNode(\"Player\");\n * node.position.set(1, 2, 3);\n * ```\n *\n * @internal\n */\nexport function createNode(name: string): SceneNode {\n return createTransformNode(name);\n}\n\n/**\n * Releases a pure transform node.\n *\n * @remarks\n * Lite requires nothing to release a transform node that was never added to a scene: verified in\n * `lib/scene/transform-node.js` and `lib/scene/scene-node.js`, the node is a plain object holding\n * three observable values, one `Float32Array` for the cached world matrix, and closures — no GPU\n * resource, no ref count, no scene registry. (Reference counting in `lib/resource/ref-count.js`\n * applies to meshes and their GPU buffers only, and `disposeScene` never walks transform nodes.)\n *\n * What *does* need doing is breaking the parent link: a linked parent keeps a reference to this\n * node's world-matrix state so it can invalidate it, so a node dropped while still parented is\n * retained by its parent. This function therefore unlinks the node and drops the ignifx tag. It\n * leaves the node's own `children` alone: the kernel destroys children before parents\n * (`docs/architecture/01-lifecycle-and-time.md` §3 step 9), so each child unlinks itself first.\n *\n * @param node - A node from {@link createNode}.\n *\n * @internal\n */\nexport function disposeNode(node: SceneNode): void {\n linkParent(node, null);\n const metadata = node.metadata;\n if (metadata !== undefined) {\n delete metadata[METADATA_KEY];\n }\n}\n\n/**\n * Links `child` under `parent`, **keeping the child's local values** — its world transform moves\n * with the new parent. This is `setParent(parent, { worldPositionStays: false })` in\n * `docs/architecture/02-scene-graph.md` §5.1.\n *\n * @remarks\n * Lite has no public helper for this case (its own `setParent` preserves the world transform), so\n * the adapter does the linking itself: it assigns `child.parent`, which is the setter that\n * re-registers the child's world-matrix state with the new parent and invalidates the subtree, and\n * maintains the `children` arrays on both the old and the new parent so tree traversal stays\n * consistent. Passing the parent the child already has is a no-op.\n *\n * @param child - The node to move.\n * @param parent - The new parent, or `null` to detach the child to world space.\n *\n * @example\n * ```ts\n * linkParent(child, parent); // child keeps localPosition; its world position changes\n * ```\n *\n * @internal\n */\nexport function linkParent(child: SceneNode, parent: SceneNode | null): void {\n const previous = child.parent;\n if (previous === parent) {\n return;\n }\n const previousChildren = childrenOf(previous);\n if (previousChildren !== null) {\n const index = previousChildren.indexOf(child);\n if (index >= 0) {\n previousChildren.splice(index, 1);\n }\n }\n // The setter, not a field write: it swaps the world-matrix state's parent, re-registers this\n // node in the new parent's invalidation list, and bumps `worldMatrixVersion` down the subtree.\n child.parent = parent;\n if (parent !== null && !parent.children.includes(child)) {\n parent.children.push(child);\n }\n}\n\n/**\n * Reparents `child` under `parent` **keeping its world transform**, by delegating to Lite's own\n * `setParent`. This is `setParent(parent, { worldPositionStays: true })`, the ignifx default\n * (`docs/architecture/02-scene-graph.md` §5.1).\n *\n * @remarks\n * Lite snapshots the child's world matrix, relinks the node (maintaining both `children` arrays),\n * then decomposes `inverse(parentWorld) × childWorld` back into local TRS. Two documented caveats\n * carry straight through to ignifx:\n *\n * - **Singular parent matrices.** When the parent's world matrix has a collapsed axis it cannot be\n * inverted, so no local transform can reproduce the child's world. Lite then keeps the parent\n * link and copies the child's world *position* into its local position, leaving rotation and\n * scale uncompensated. Non-uniform-but-invertible parents are fine; zero scale on any axis is\n * not.\n * - **Canonical, not sign-faithful, decomposition.** The local TRS comes from `mat4Decompose`,\n * which folds a reflection into a negative Y scale. The world matrix is reproduced exactly, but a\n * child that had a negative X scale comes back with a negative Y scale and a different rotation.\n *\n * A third caveat in Lite's TSDoc — that `child.parent` links are only established by `addToScene`,\n * so a node from a freshly loaded asset must have its container added before it is reparented —\n * does not apply to nodes ignifx creates, because {@link linkParent} establishes the link itself.\n *\n * @param child - The node to move.\n * @param parent - The new parent, or `null` to detach the child to world space.\n *\n * @internal\n */\nexport function reparentKeepingWorld(child: SceneNode, parent: SceneNode | null): void {\n setParent(child, parent);\n}\n\n/**\n * Copies a node's world matrix into `out`.\n *\n * @remarks\n * Allocation-free on the ignifx side, which is why the destination is a parameter: Lite's\n * `worldMatrix` getter may recompute up the parent chain, and the object it returns is Lite's own\n * cache — never hold on to it. Lite documents `Mat4` as opaque (\"callers MUST NOT depend on the\n * underlying storage\"); it is a `Float32Array` in 1.27.0 (`lib/math/_matrix-allocator.js`), so\n * copying element by element is the only supported read.\n *\n * @param node - The node to read.\n * @param out - A sink of at least 16 elements, written in column-major order.\n * @returns `out`, for chaining.\n *\n * @internal\n */\nexport function readWorldMatrix(node: SceneNode, out: MutableMat4Like): MutableMat4Like {\n const matrix = node.worldMatrix;\n for (let index = 0; index < MATRIX_LENGTH; index += 1) {\n out[index] = matrix[index] ?? 0;\n }\n return out;\n}\n\n/**\n * Reads a node's world-matrix version — the counter that increases whenever the node's world\n * matrix is invalidated, by its own TRS or by any ancestor's.\n *\n * @remarks\n * Snapshot it to detect movement without comparing matrices; systems that maintain acceleration\n * structures do exactly that (`docs/architecture/02-scene-graph.md` §9). The counter is\n * monotonically increasing but not a change *count*: it moves on invalidation, not on\n * recomputation, and a bulk `position.set(...)` bumps it even when the values are unchanged.\n *\n * @param node - The node to read.\n * @returns The current version.\n *\n * @internal\n */\nexport function worldMatrixVersion(node: SceneNode): number {\n return node.worldMatrixVersion;\n}\n\n/**\n * Decomposes a node's world matrix into translation, rotation, and scale, writing into the three\n * output parameters.\n *\n * @remarks\n * The decomposition is canonical rather than sign-faithful: a mirror is folded into a negative Y\n * scale, so recomposing reproduces the matrix but a matrix built from a negative X or Z scale comes\n * back as a negative Y scale plus a different rotation. A degenerate axis (scale below `1e-8`) is\n * tolerated: the rotation stays finite but is meaningless for that axis.\n *\n * ignifx allocates nothing here, but Lite's `mat4Decompose` allocates its own TRS triple per call\n * (`lib/math/mat4-decompose.js`), so this is not yet a zero-allocation path in the sense of coding\n * standards §7. The math module's in-place decomposition replaces the Lite call when it lands.\n *\n * @param node - The node to read.\n * @param outPosition - Receives the world translation.\n * @param outRotation - Receives the world rotation as a unit quaternion.\n * @param outScale - Receives the per-axis world scale.\n *\n * @internal\n */\nexport function decomposeWorld(\n node: SceneNode,\n outPosition: MutableVec3Like,\n outRotation: MutableQuatLike,\n outScale: MutableVec3Like,\n): void {\n const decomposed = mat4Decompose(node.worldMatrix);\n outPosition.x = decomposed.translation.x;\n outPosition.y = decomposed.translation.y;\n outPosition.z = decomposed.translation.z;\n outRotation.x = decomposed.rotation.x;\n outRotation.y = decomposed.rotation.y;\n outRotation.z = decomposed.rotation.z;\n outRotation.w = decomposed.rotation.w;\n outScale.x = decomposed.scale.x;\n outScale.y = decomposed.scale.y;\n outScale.z = decomposed.scale.z;\n}\n\n/**\n * Shows or hides a node and its whole subtree.\n *\n * @remarks\n * Lite materializes the cascade at write time — it walks `children` and writes `visible` on every\n * descendant — so a node added to the subtree afterwards does not inherit the state and must be\n * set separately. This is how entity deactivation hides render objects\n * (`docs/architecture/01-lifecycle-and-time.md` §6); removing a mesh from its last scene disposes\n * it permanently, so visibility, never removal, is the deactivation path.\n *\n * @param node - The subtree root.\n * @param visible - `true` to show the subtree, `false` to hide it.\n *\n * @internal\n */\nexport function setNodeVisible(node: SceneNode, visible: boolean): void {\n setSubtreeVisible(node, visible);\n}\n\n/**\n * Shows or hides **one** node, without touching its subtree.\n *\n * @remarks\n * Lite's `visible` is per node — the renderer reads each node's own flag, and `setSubtreeVisible`\n * is only a bulk helper that materialises a cascade at write time. ignifx already materialises\n * `activeInHierarchy` over the subtree itself, so it writes one flag per entity: correct for a\n * subtree that mixes active and inactive entities, and linear rather than quadratic.\n *\n * @param node - The node to show or hide.\n * @param visible - `true` to show it, `false` to hide it.\n *\n * @internal\n */\nexport function setNodeSelfVisible(node: SceneNode, visible: boolean): void {\n node.visible = visible;\n}\n\n/**\n * Writes the ignifx identity into a node's Lite metadata bag, under the single `ignifx` key.\n *\n * @remarks\n * `LiteMetadata` is an open record (`{ gltf?: GltfMetadata; [key: string]: unknown }`), so the tag\n * coexists with the `gltf.extras` a glTF load writes. The metadata object is created on demand;\n * nodes ignifx never tags keep `metadata` undefined.\n *\n * @param node - The node to tag.\n * @param tag - The owning entity, and the component that created the node when it is not the\n * entity's own transform.\n *\n * @internal\n */\nexport function tagNode(node: SceneNode, tag: NodeTag): void {\n const metadata = (node.metadata ??= {});\n metadata[METADATA_KEY] = tag;\n}\n\n/**\n * Reads the ignifx identity back from a node.\n *\n * @param node - The node to read; it may be any Lite node, including one ignifx never created.\n * @returns The tag {@link tagNode} wrote, or `null` when the node carries none.\n *\n * @internal\n */\nexport function readNodeTag(node: SceneNode): NodeTag | null {\n const metadata = node.metadata;\n if (metadata === undefined) {\n return null;\n }\n const value = metadata[METADATA_KEY];\n if (typeof value !== \"object\" || value === null || !(\"entity\" in value)) {\n return null;\n }\n const entity = value.entity;\n if (typeof entity !== \"number\") {\n return null;\n }\n const component = \"component\" in value ? value.component : undefined;\n return typeof component === \"number\" ? { entity, component } : { entity };\n}\n\n/**\n * The `children` array of a world-matrix provider, when it has one.\n *\n * @remarks\n * `SceneNode.parent` is typed as the minimal {@link IWorldMatrixProvider}, which declares no\n * `children`, but every parent ignifx links is a scene node. Lite's own `setParent` solves this the\n * same way (`lib/scene/set-parent.js`), and the array check keeps a non-node provider — a camera,\n * say — from being treated as a tree node.\n *\n * @param provider - The candidate parent.\n * @returns The provider's children, or `null` when it is not a tree node.\n */\nfunction childrenOf(provider: IWorldMatrixProvider | null): SceneNode[] | null {\n if (provider === null || !(\"children\" in provider)) {\n return null;\n }\n const children = provider.children;\n // Boundary assertion (coding standards §5.2): the invariant is that a world-matrix provider with\n // an array-valued `children` is a `SceneNode`, which is what Lite itself assumes here.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return Array.isArray(children) ? (children as SceneNode[]) : null;\n}\n\n/**\n * The Babylon Lite node an ignifx `Transform` wraps, re-exported under an ignifx name so that\n * feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's type, reachable only through documented `.lite` escape hatches, and it is\n * excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteSceneNode = SceneNode;\n\n/**\n * The node's local position as a live, writable view.\n *\n * @remarks\n * Zero-copy: the returned object *is* Lite's `ObservableVec3` over the node's TRS, so `.x += 1`,\n * `.set(x, y, z)`, and `.copyFrom(v)` write straight through and invalidate the subtree's world\n * matrices (`docs/architecture/02-scene-graph.md` §5). Never hold it past the node's lifetime.\n *\n * @param node - The node to view.\n * @returns The live local position.\n *\n * @internal\n */\nexport function localPosition(node: SceneNode): MutableVec3 {\n return node.position;\n}\n\n/**\n * The node's local rotation as a live, writable view.\n *\n * @param node - The node to view.\n * @returns The live local rotation quaternion.\n *\n * @internal\n */\nexport function localRotation(node: SceneNode): MutableQuat {\n return node.rotationQuaternion;\n}\n\n/**\n * The node's local scale as a live, writable view.\n *\n * @param node - The node to view.\n * @returns The live local scale.\n *\n * @internal\n */\nexport function localScale(node: SceneNode): MutableVec3 {\n return node.scaling;\n}\n\n/**\n * Reads a node's own visibility flag.\n *\n * @remarks\n * Lite leaves `visible` `undefined` on a node that was never hidden, which means *visible*; this\n * normalises that to `true` so callers never have to spell the tri-state out. Only\n * {@link setNodeVisible} writes it, and it materialises the cascade at write time.\n *\n * @param node - The node to read.\n * @returns `true` when the node renders.\n *\n * @internal\n */\nexport function isNodeVisible(node: SceneNode): boolean {\n return node.visible !== false;\n}\n\n/**\n * Renames a node.\n *\n * @remarks\n * Lite never uses the name for lookup, so this is purely for debugging and for the names that show\n * up in Lite-side tooling; ignifx keeps `Entity.name` as the source of truth and mirrors it here.\n *\n * @param node - The node to rename.\n * @param name - The new name.\n *\n * @internal\n */\nexport function setNodeName(node: SceneNode, name: string): void {\n node.name = name;\n}\n\n/**\n * The parent a node is currently linked to, when that parent is itself a scene node.\n *\n * @param node - The node to read.\n * @returns The parent node, or `null` when the node is unparented or its parent is a bare\n * world-matrix provider such as a camera.\n *\n * @internal\n */\nexport function parentNode(node: SceneNode): SceneNode | null {\n const parent = node.parent;\n if (parent === null || !(\"children\" in parent)) {\n return null;\n }\n // Boundary assertion (coding standards §5.2): a world-matrix provider that carries `children` is\n // a `SceneNode` — the same invariant Lite's own `setParent` relies on.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return parent as SceneNode;\n}\n","import { pickMeshesWithRay, pickWithRay } from \"@babylonjs/lite\";\nimport { readNodeTag } from \"./node.js\";\nimport type { NodeTag } from \"./node.js\";\nimport type { Mesh, PickingInfo, Ray, RayPickOptions, SceneContext } from \"@babylonjs/lite\";\n\n/**\n * CPU picking half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §3): the\n * synchronous ray tests behind `world.raycastRender`, and the mapping from a Lite hit back to the\n * ignifx entity that owns the mesh. The GPU picker lives in `./gpu/picker.ts` because it needs a\n * device and a rendered frame.\n *\n * Everything here is `@internal`.\n *\n * ## What Lite's ray pick does (verified against `@babylonjs/lite@1.27.0` `lib/picking/ray-pick.js`)\n *\n * - It walks `scene.meshes`, skips anything with `pickable === false` unless `skipPickableCheck` is\n * set, then applies the caller's `predicate`, and tests the ray against each candidate's local\n * AABB before its triangles.\n * - The triangle test reads `mesh._cpuPositions`, the CPU copy every mesh factory retains\n * (`lib/mesh/mesh-factories.js`, `retainMeshGeometry`). A mesh with no CPU positions — one built\n * from a GPU-only path — is silently skipped, so a CPU pick can miss a mesh a GPU pick would hit.\n * - **Visibility is ignored.** `mesh.visible === false` still occludes and still returns a hit; only\n * `pickable` and the predicate filter. That is Lite's documented behaviour, and it is why the\n * component layer passes a predicate rather than relying on hiding.\n */\n\n/**\n * The result of a Babylon Lite pick — CPU ray or GPU picker — re-exported under an ignifx name so\n * feature code can name the type without importing `@babylonjs/lite` (coding standards §4).\n *\n * @internal\n */\nexport type LitePickInfo = PickingInfo;\n\n/**\n * A ray in the shape Lite expects: three-element tuples that can be rewritten in place, so a\n * picking loop reuses one ray and allocates nothing (coding standards §7).\n *\n * @internal\n */\nexport type PickRay = Ray;\n\n/**\n * Creates a reusable ray, pointing along `+Z` from the origin.\n *\n * @returns A fresh ray. **Allocates** — create one per picking site, not per pick.\n *\n * @example\n * ```ts\n * const ray = createPickRay();\n * screenToRay(camera, x, y, width, height, ray);\n * const hit = raycastScene(scene, ray);\n * ```\n *\n * @internal\n */\nexport function createPickRay(): PickRay {\n return { origin: [0, 0, 0], direction: [0, 0, 1], length: Number.MAX_VALUE };\n}\n\n/**\n * Points a ray at a world-space origin and direction, in place.\n *\n * @param ray - The ray to rewrite.\n * @param originX - The world-space origin x.\n * @param originY - The world-space origin y.\n * @param originZ - The world-space origin z.\n * @param directionX - The direction x; it need not be normalized.\n * @param directionY - The direction y.\n * @param directionZ - The direction z.\n * @param length - How far the ray reaches, in metres.\n *\n * @internal\n */\nexport function setPickRay(\n ray: PickRay,\n originX: number,\n originY: number,\n originZ: number,\n directionX: number,\n directionY: number,\n directionZ: number,\n length: number,\n): void {\n const origin = ray.origin;\n origin[0] = originX;\n origin[1] = originY;\n origin[2] = originZ;\n const magnitude = Math.hypot(directionX, directionY, directionZ);\n const scale = magnitude > 0 ? 1 / magnitude : 0;\n const direction = ray.direction;\n direction[0] = directionX * scale;\n direction[1] = directionY * scale;\n direction[2] = directionZ * scale;\n ray.length = length;\n}\n\n/**\n * Casts a ray against every renderable mesh in a scene, on the CPU.\n *\n * @remarks\n * This is `world.raycastRender`. It is distinct from a physics raycast\n * (`docs/architecture/09-physics.md` §5): it hits render geometry, including meshes that carry no\n * collider.\n *\n * @param scene - The render scene.\n * @param ray - The ray to cast.\n * @param options - An optional mesh predicate.\n * @returns Lite's picking info. Check `hit` before reading anything else. **Allocates** one result\n * object per call — Lite builds it.\n *\n * @internal\n */\nexport function raycastScene(scene: SceneContext, ray: PickRay, options?: RayPickOptions): PickingInfo {\n return pickWithRay(scene, ray, options);\n}\n\n/**\n * Casts a ray against an explicit list of meshes, on the CPU.\n *\n * @param meshes - The meshes to test.\n * @param ray - The ray to cast.\n * @param options - An optional mesh predicate.\n * @returns Lite's picking info.\n *\n * @internal\n */\nexport function raycastMeshes(meshes: Iterable<Mesh>, ray: PickRay, options?: RayPickOptions): PickingInfo {\n return pickMeshesWithRay(meshes, ray, options);\n}\n\n/**\n * Casts a ray against a scene's renderable meshes, considering only the meshes whose ignifx tag a\n * predicate accepts.\n *\n * @remarks\n * The predicate is stated over the *tag* rather than over Lite's `Mesh` so the component layer can\n * filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). Lite's own\n * `pickable === false` exclusion still runs first.\n *\n * @param scene - The render scene.\n * @param ray - The ray to cast.\n * @param accept - Decides whether a mesh may be picked, from the ignifx tag its node carries.\n * @returns Lite's picking info.\n *\n * @internal\n */\nexport function raycastSceneWhere(\n scene: SceneContext,\n ray: PickRay,\n accept: (tag: NodeTag | null) => boolean,\n): PickingInfo {\n const options: RayPickOptions = { predicate: (mesh: Mesh): boolean => accept(readNodeTag(mesh)) };\n return pickWithRay(scene, ray, options);\n}\n\n/**\n * Resolves a hit back to the ignifx entity and component that own the mesh.\n *\n * @param info - A result from {@link raycastScene}, {@link raycastMeshes}, or the GPU picker.\n * @returns The owning entity's tag, or `null` when the ray missed or the mesh is not one ignifx\n * created (a glTF child node inside a `Model`, for instance, whose tag lives on the model's root).\n *\n * @internal\n */\nexport function readPickedTag(info: PickingInfo): NodeTag | null {\n const mesh = info.pickedMesh;\n if (mesh === null) {\n return null;\n }\n return readNodeTag(mesh);\n}\n","import type { JsonObject, JsonValue } from \"./json.js\";\n\n/**\n * Every field kind a component schema can declare\n * (`docs/architecture/03-scripting-and-components.md` §3). Declared as an `as const` table with a\n * derived union rather than an `enum`, which `erasableSyntaxOnly` bans (coding standards §5.2).\n *\n * @public\n */\nexport const FieldKind = {\n /** A 32-bit-ranged floating point number. */\n f32: \"f32\",\n /** A double-precision floating point number. */\n f64: \"f64\",\n /** A signed 32-bit integer. */\n i32: \"i32\",\n /** An unsigned 32-bit integer. */\n u32: \"u32\",\n /** A boolean toggle. */\n bool: \"bool\",\n /** A UTF-8 string. */\n str: \"str\",\n /** A 2D vector. */\n vec2: \"vec2\",\n /** A 3D vector. */\n vec3: \"vec3\",\n /** A 4D vector. */\n vec4: \"vec4\",\n /** A rotation quaternion. */\n quat: \"quat\",\n /** An RGBA color. */\n color: \"color\",\n /** One of a fixed set of string values. */\n enum: \"enum\",\n /** A reference to another entity in the same scene file. */\n entityRef: \"entityRef\",\n /** A reference to a component on an entity in the same scene file. */\n componentRef: \"componentRef\",\n /** A reference to an addressable asset. */\n asset: \"asset\",\n /** A list of values of one kind. */\n array: \"array\",\n /** A fixed group of named sub-fields. */\n record: \"record\",\n /** A string-keyed dictionary of values of one kind. */\n map: \"map\",\n /** A value that may also be `null`. */\n optional: \"optional\",\n /** A set of layer names. */\n layerMask: \"layerMask\",\n /** An animation curve. */\n curve: \"curve\",\n /** A value with a hand-written encoder and decoder. */\n custom: \"custom\",\n} as const;\n\n/**\n * The union of every field kind.\n *\n * @public\n */\nexport type FieldKind = (typeof FieldKind)[keyof typeof FieldKind];\n\n/**\n * Inspector and serializer metadata carried by every field\n * (`docs/architecture/03-scripting-and-components.md` §3,\n * `docs/architecture/06-serialization-and-scene-format.md` §5). Options never change a field's\n * value type; they constrain and present it.\n *\n * @public\n */\nexport interface FieldOptions {\n /** Help text shown next to the field in the inspector. */\n readonly tooltip?: string;\n /** Lowest accepted value for numeric kinds; validation reports `IGX-0606` below it. */\n readonly min?: number;\n /** Highest accepted value for numeric kinds; validation reports `IGX-0606` above it. */\n readonly max?: number;\n /** Increment used by the inspector's drag and spinner controls. */\n readonly step?: number;\n /** Hides the field from the inspector while still serializing it. */\n readonly hidden?: boolean;\n /** Shows the field in the inspector but forbids editing it there. */\n readonly readonly?: boolean;\n /** Name of the inspector group the field is folded into. */\n readonly group?: string;\n /** Excludes the field from saved games and scene files; it always takes its default on load. */\n readonly transient?: boolean;\n}\n\n/**\n * How a component class is named in a schema. A class satisfies it structurally through its\n * `prototype`, so `componentRef(Camera)` infers `Camera` without the class having to implement\n * anything. The optional `typeId` is the namespaced registration id from\n * `docs/architecture/03-scripting-and-components.md` §4 when the class carries one.\n *\n * @typeParam C - The component instance type the token stands for.\n *\n * @public\n */\nexport interface ComponentTypeToken<C> {\n /** The component's namespaced registration id, when it declares one. */\n readonly typeId?: string;\n /** The instance shape the token names. */\n readonly prototype: C;\n}\n\n/**\n * How an asset class is named in a schema. Like {@link ComponentTypeToken}, a class satisfies it\n * structurally; `assetType` supplies the `type` discriminator written into `{ \"$asset\": … }` when\n * the loader cannot infer it from the address extension\n * (`docs/architecture/05-assets-and-loading.md` §2).\n *\n * @typeParam A - The asset value type the token stands for.\n *\n * @public\n */\nexport interface AssetTypeToken<A> {\n /** The asset type name written into files when the extension is ambiguous. */\n readonly assetType?: string;\n /** The instance shape the token names. */\n readonly prototype: A;\n}\n\n/**\n * The plain, serializable form of an asset reference: what `{ \"$asset\": … }` decodes to before the\n * asset service turns it into a handle, and what a tool that reads a scene file without an app\n * works with (`docs/architecture/05-assets-and-loading.md` §2).\n *\n * @remarks\n * It is **not** the runtime value of an `asset()` field. Since Phase 2 that value is\n * `AssetHandle<A> | null`: a component receives the handle already loaded\n * (`docs/architecture/05-assets-and-loading.md` §3), so `this.mesh?.value` reaches the asset with no\n * second lookup. The two shapes overlap on `address`/`type`, which is why the encoder accepts\n * either.\n *\n * @typeParam A - The asset value type this reference points at. It is a compile-time marker only:\n * `assetOf` is never assigned at runtime and is never serialized. It exists so that\n * `AssetRefValue<Texture>` and `AssetRefValue<Mesh>` are different types.\n *\n * @public\n */\nexport interface AssetRefValue<A> {\n /** The address the asset is registered under, for example `models/hero.glb#mesh:Body`. */\n readonly address: string;\n /** The asset type name, when the address alone does not identify it. */\n readonly type?: string;\n /** Compile-time marker for the asset type; never present at runtime. */\n readonly assetOf?: A;\n}\n\n/**\n * One key of an animation curve: time, value, incoming tangent, outgoing tangent\n * (`docs/architecture/06-serialization-and-scene-format.md` §3).\n *\n * @public\n */\nexport type CurveKey = readonly [time: number, value: number, inTangent: number, outTangent: number];\n\n/**\n * The value a `curve()` field holds.\n *\n * @public\n */\nexport interface CurveValue {\n /** The curve's keys, ordered by time. */\n readonly keys: readonly CurveKey[];\n}\n\n/**\n * The hand-written encoder and decoder behind a `custom()` field. The codec owns both the default\n * value and the JSON representation, so `custom` is the escape hatch for value types the built-in\n * kinds cannot express.\n *\n * @typeParam T - The runtime value type.\n *\n * @public\n */\nexport interface CustomFieldCodec<T> {\n /**\n * Builds a fresh default value. It is a factory, not a constant, so two components never share\n * one mutable default object.\n *\n * @returns A newly allocated default value.\n */\n createDefault(): T;\n /**\n * Converts a runtime value into JSON.\n *\n * @param value - The value to serialize.\n * @returns The JSON representation written into the file.\n */\n serialize(value: T): JsonValue;\n /**\n * Rebuilds a runtime value from JSON.\n *\n * @param json - The JSON previously produced by `serialize`.\n * @returns The runtime value.\n */\n deserialize(json: JsonValue): T;\n /** A JSON Schema fragment describing the encoded form, merged into the generated document. */\n readonly jsonSchema?: JsonObject;\n}\n\n/**\n * Kind-specific data for the numeric kinds.\n *\n * @public\n */\nexport interface NumberFieldSpec {\n /** The numeric kind. */\n readonly kind: \"f32\" | \"f64\" | \"i32\" | \"u32\";\n}\n\n/**\n * Kind-specific data for `bool`.\n *\n * @public\n */\nexport interface BoolFieldSpec {\n /** The boolean kind. */\n readonly kind: \"bool\";\n}\n\n/**\n * Kind-specific data for `str`.\n *\n * @public\n */\nexport interface StringFieldSpec {\n /** The string kind. */\n readonly kind: \"str\";\n}\n\n/**\n * Kind-specific data for the vector kinds. `components` says how many numbers the encoded array\n * holds, so encoders do not have to re-derive it from the kind.\n *\n * @public\n */\nexport interface VectorFieldSpec {\n /** The vector kind. */\n readonly kind: \"vec2\" | \"vec3\" | \"vec4\" | \"quat\";\n /** How many components the value has: 2, 3, or 4. */\n readonly components: 2 | 3 | 4;\n}\n\n/**\n * Kind-specific data for `color`.\n *\n * @public\n */\nexport interface ColorFieldSpec {\n /** The color kind. */\n readonly kind: \"color\";\n}\n\n/**\n * Kind-specific data for `enumOf`.\n *\n * @public\n */\nexport interface EnumFieldSpec {\n /** The enumeration kind. */\n readonly kind: \"enum\";\n /** Every accepted string value, in declaration order. */\n readonly values: readonly string[];\n}\n\n/**\n * Kind-specific data for `entityRef`.\n *\n * @public\n */\nexport interface EntityRefFieldSpec {\n /** The entity-reference kind. */\n readonly kind: \"entityRef\";\n}\n\n/**\n * Kind-specific data for `componentRef`.\n *\n * @public\n */\nexport interface ComponentRefFieldSpec {\n /** The component-reference kind. */\n readonly kind: \"componentRef\";\n /** The component class the field may point at. */\n readonly componentType: ComponentTypeToken<unknown>;\n}\n\n/**\n * Kind-specific data for `asset`.\n *\n * @public\n */\nexport interface AssetFieldSpec {\n /** The asset-reference kind. */\n readonly kind: \"asset\";\n /** The asset class the field may point at. */\n readonly assetType: AssetTypeToken<unknown>;\n /** The `type` discriminator written into files, or `null` when the address is unambiguous. */\n readonly typeName: string | null;\n}\n\n/**\n * Kind-specific data for `array`.\n *\n * @public\n */\nexport interface ArrayFieldSpec {\n /** The array kind. */\n readonly kind: \"array\";\n /** The field definition every element follows. */\n readonly item: FieldDefinition<unknown>;\n}\n\n/**\n * Kind-specific data for `record`.\n *\n * @public\n */\nexport interface RecordFieldSpec {\n /** The record kind. */\n readonly kind: \"record\";\n /** The sub-fields, in declaration order. */\n readonly fields: Schema;\n}\n\n/**\n * Kind-specific data for `map`.\n *\n * @public\n */\nexport interface MapFieldSpec {\n /** The map kind. */\n readonly kind: \"map\";\n /** The field definition every entry's value follows. */\n readonly value: FieldDefinition<unknown>;\n}\n\n/**\n * Kind-specific data for `optional`.\n *\n * @public\n */\nexport interface OptionalFieldSpec {\n /** The optional kind. */\n readonly kind: \"optional\";\n /** The field definition a non-`null` value follows. */\n readonly inner: FieldDefinition<unknown>;\n}\n\n/**\n * Kind-specific data for `layerMask`.\n *\n * @public\n */\nexport interface LayerMaskFieldSpec {\n /** The layer-mask kind. */\n readonly kind: \"layerMask\";\n}\n\n/**\n * Kind-specific data for `curve`.\n *\n * @public\n */\nexport interface CurveFieldSpec {\n /** The curve kind. */\n readonly kind: \"curve\";\n}\n\n/**\n * Kind-specific data for `custom`.\n *\n * @public\n */\nexport interface CustomFieldSpec {\n /** The custom kind. */\n readonly kind: \"custom\";\n /** The hand-written codec that owns the value's default and JSON form. */\n readonly codec: CustomFieldCodec<unknown>;\n}\n\n/**\n * The discriminated union of kind-specific field data. Switching on `spec.kind` narrows to the\n * member that carries the extra information that kind needs — the enumeration's values, an array's\n * item definition, a component reference's class token — so no branch has to guess.\n *\n * @public\n */\nexport type FieldSpec =\n | NumberFieldSpec\n | BoolFieldSpec\n | StringFieldSpec\n | VectorFieldSpec\n | ColorFieldSpec\n | EnumFieldSpec\n | EntityRefFieldSpec\n | ComponentRefFieldSpec\n | AssetFieldSpec\n | ArrayFieldSpec\n | RecordFieldSpec\n | MapFieldSpec\n | OptionalFieldSpec\n | LayerMaskFieldSpec\n | CurveFieldSpec\n | CustomFieldSpec;\n\n/**\n * One declared field of a component schema. Field definitions are plain, immutable data built by\n * the constructors in this module; nothing about them is reflective and nothing runs at import\n * time (ADR-0004, `CONSTITUTION.md` §3.5).\n *\n * The type parameter is the field's *runtime* value type, which is what\n * `Script.define({ … })` uses to type the generated properties.\n *\n * @typeParam T - The runtime value type of the field.\n *\n * @example\n * ```ts\n * const speed = f32(5, { min: 0, max: 50, tooltip: \"Units per second\" });\n * speed.kind; // \"f32\"\n * speed.createDefault(); // 5\n * ```\n *\n * @public\n */\nexport interface FieldDefinition<T> {\n /** The field kind, mirroring `spec.kind` for quick reads by tooling and the docs harness. */\n readonly kind: FieldKind;\n /** The kind-specific data, discriminated by `spec.kind`. */\n readonly spec: FieldSpec;\n /** Inspector and serializer metadata. */\n readonly options: FieldOptions;\n /**\n * Builds a fresh default value. Object-valued kinds allocate on every call, so two components\n * never share one mutable default.\n *\n * @returns A newly allocated default value.\n */\n createDefault(): T;\n}\n\n/**\n * A component's declared fields, keyed by property name and ordered by declaration. Declaration\n * order is the canonical key order used when writing files\n * (`docs/architecture/06-serialization-and-scene-format.md` §1).\n *\n * @public\n */\nexport type Schema = Readonly<Record<string, FieldDefinition<unknown>>>;\n\n/**\n * The object type a schema describes: every field name mapped to its runtime value type. This is\n * what gives `this.speed` its `number` type inside a component declared with\n * `Script.define({ speed: f32(5) })`.\n *\n * @typeParam S - The schema to project.\n *\n * @example\n * ```ts\n * const schema = { speed: f32(5), label: str(\"\") };\n * type Fields = FieldsOf<typeof schema>; // { speed: number; label: string }\n * ```\n *\n * @public\n */\nexport type FieldsOf<S extends Schema> = {\n -readonly [K in keyof S]: S[K] extends FieldDefinition<infer T> ? T : never;\n};\n\n/**\n * The field object of a schema with every property optional, and an explicit `undefined` allowed.\n * `exactOptionalPropertyTypes` normally separates \"absent\" from \"present and `undefined`\"; both\n * mean \"take the schema default\" here, so both are accepted (`applyInit`, `encodeProps`).\n *\n * @typeParam S - The schema to project.\n *\n * @public\n */\nexport type PartialFieldsOf<S extends Schema> = {\n [K in keyof FieldsOf<S>]?: FieldsOf<S>[K] | undefined;\n};\n","import { SchemaIssueCode, throwSchemaError } from \"./issues.js\";\nimport { createDefaults } from \"./schema.js\";\nimport { FieldKind } from \"./types.js\";\nimport type {\n AssetTypeToken,\n ComponentTypeToken,\n CurveKey,\n CurveValue,\n CustomFieldCodec,\n FieldDefinition,\n FieldOptions,\n FieldSpec,\n FieldsOf,\n Schema,\n} from \"./types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { ColorLike, QuatLike, Vec2Like, Vec3Like, Vec4Like } from \"../math/types.js\";\n\n/**\n * The default a `vec2()` field takes when none is given.\n *\n * @internal\n */\nconst ZERO2: Vec2Like = { x: 0, y: 0 };\n/**\n * The default a `vec3()` field takes when none is given.\n *\n * @internal\n */\nconst ZERO3: Vec3Like = { x: 0, y: 0, z: 0 };\n/**\n * The default a `vec4()` field takes when none is given.\n *\n * @internal\n */\nconst ZERO4: Vec4Like = { x: 0, y: 0, z: 0, w: 0 };\n/**\n * The identity rotation, the default a `quat()` field takes when none is given.\n *\n * @internal\n */\nconst IDENTITY_QUAT: QuatLike = { x: 0, y: 0, z: 0, w: 1 };\n/**\n * Opaque white, the default a `color()` field takes when none is given.\n *\n * @internal\n */\nconst WHITE: ColorLike = { r: 1, g: 1, b: 1, a: 1 };\n/**\n * The default a `curve()` field takes when none is given.\n *\n * @internal\n */\nconst EMPTY_CURVE: CurveValue = { keys: [] };\n/**\n * Matches `#rgb`, `#rgba`, `#rrggbb`, and `#rrggbbaa`.\n *\n * @internal\n */\nconst HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/u;\n\n/**\n * Assembles a field definition. Centralising construction keeps `kind` and `spec.kind` in step and\n * keeps every field a plain, frozen-by-convention data object.\n *\n * @param spec - The kind-specific data, which also supplies the discriminant.\n * @param options - Inspector and serializer metadata, if any.\n * @param createDefault - Factory for a fresh default value.\n * @returns The field definition.\n *\n * @internal\n */\nfunction field<T>(spec: FieldSpec, options: FieldOptions | undefined, createDefault: () => T): FieldDefinition<T> {\n return { kind: spec.kind, spec, options: options ?? {}, createDefault };\n}\n\n/**\n * Parses a CSS-style hexadecimal color into normalized sRGB channels.\n *\n * @param hex - `#rgb`, `#rgba`, `#rrggbb`, or `#rrggbbaa`.\n * @returns The parsed color with channels in the 0–1 range.\n * @throws A `TypeError` when the string is not one of the accepted forms.\n *\n * @internal\n */\nfunction parseHexColor(hex: string): ColorLike {\n if (!HEX_COLOR_PATTERN.test(hex)) {\n throwSchemaError(\n SchemaIssueCode.typeMismatch,\n `color(\"${hex}\") is not a hexadecimal color; use #rgb, #rgba, #rrggbb, or #rrggbbaa.`,\n );\n }\n const digits = hex.slice(1);\n const short = digits.length <= 4;\n const size = short ? 1 : 2;\n const scale = short ? 15 : 255;\n const channel = (index: number): number => {\n const start = index * size;\n if (start >= digits.length) {\n return 1;\n }\n return Number.parseInt(digits.slice(start, start + size), 16) / scale;\n };\n return { r: channel(0), g: channel(1), b: channel(2), a: channel(3) };\n}\n\n/**\n * Declares a single-precision floating point field.\n *\n * @param defaultValue - The value a new component starts with.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * speed: f32(5, { min: 0, max: 50, tooltip: \"Units per second\" });\n * ```\n *\n * @public\n */\nexport function f32(defaultValue: number = 0, options?: FieldOptions): FieldDefinition<number> {\n return field({ kind: FieldKind.f32 }, options, () => defaultValue);\n}\n\n/**\n * Declares a double-precision floating point field.\n *\n * @param defaultValue - The value a new component starts with.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function f64(defaultValue: number = 0, options?: FieldOptions): FieldDefinition<number> {\n return field({ kind: FieldKind.f64 }, options, () => defaultValue);\n}\n\n/**\n * Declares a signed 32-bit integer field. Validation rejects fractional values and values outside\n * the signed 32-bit range with `IGX-0606`.\n *\n * @param defaultValue - The value a new component starts with.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function i32(defaultValue: number = 0, options?: FieldOptions): FieldDefinition<number> {\n return field({ kind: FieldKind.i32 }, options, () => defaultValue);\n}\n\n/**\n * Declares an unsigned 32-bit integer field. Validation rejects fractional and negative values, and\n * values above 4294967295, with `IGX-0606`.\n *\n * @param defaultValue - The value a new component starts with.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function u32(defaultValue: number = 0, options?: FieldOptions): FieldDefinition<number> {\n return field({ kind: FieldKind.u32 }, options, () => defaultValue);\n}\n\n/**\n * Declares a boolean field.\n *\n * @param defaultValue - The value a new component starts with.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function bool(defaultValue: boolean = false, options?: FieldOptions): FieldDefinition<boolean> {\n return field({ kind: FieldKind.bool }, options, () => defaultValue);\n}\n\n/**\n * Declares a string field.\n *\n * @param defaultValue - The value a new component starts with.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function str(defaultValue: string = \"\", options?: FieldOptions): FieldDefinition<string> {\n return field({ kind: FieldKind.str }, options, () => defaultValue);\n}\n\n/**\n * Declares a 2D vector field. The runtime value type is the structural `Vec2Like`, so the engine's\n * `Vec2` class and plain object literals are both accepted.\n *\n * @param defaultValue - The value a new component starts with; defaults to the origin.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function vec2(defaultValue: Vec2Like = ZERO2, options?: FieldOptions): FieldDefinition<Vec2Like> {\n const { x, y } = defaultValue;\n return field({ kind: FieldKind.vec2, components: 2 }, options, (): Vec2Like => ({ x, y }));\n}\n\n/**\n * Declares a 3D vector field.\n *\n * @param defaultValue - The value a new component starts with; defaults to the origin.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * offset: vec3({ x: 0, y: 1, z: 0 });\n * ```\n *\n * @public\n */\nexport function vec3(defaultValue: Vec3Like = ZERO3, options?: FieldOptions): FieldDefinition<Vec3Like> {\n const { x, y, z } = defaultValue;\n return field({ kind: FieldKind.vec3, components: 3 }, options, (): Vec3Like => ({ x, y, z }));\n}\n\n/**\n * Declares a 4D vector field.\n *\n * @param defaultValue - The value a new component starts with; defaults to all zeroes.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function vec4(defaultValue: Vec4Like = ZERO4, options?: FieldOptions): FieldDefinition<Vec4Like> {\n const { x, y, z, w } = defaultValue;\n return field({ kind: FieldKind.vec4, components: 4 }, options, (): Vec4Like => ({ x, y, z, w }));\n}\n\n/**\n * Declares a rotation field.\n *\n * @param defaultValue - The value a new component starts with; defaults to the identity rotation.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @public\n */\nexport function quat(defaultValue: QuatLike = IDENTITY_QUAT, options?: FieldOptions): FieldDefinition<QuatLike> {\n const { x, y, z, w } = defaultValue;\n return field({ kind: FieldKind.quat, components: 4 }, options, (): QuatLike => ({ x, y, z, w }));\n}\n\n/**\n * Declares an RGBA color field. Channels are sRGB in the 0–1 range, in memory and in files alike:\n * conversion to linear space belongs to the renderer, not the schema\n * (`docs/architecture/06-serialization-and-scene-format.md` §3).\n *\n * @param defaultValue - The starting color, either as channels or as a `#rgb`/`#rgba`/`#rrggbb`/\n * `#rrggbbaa` string; defaults to opaque white.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n * @throws A `TypeError` when a string default is not a valid hexadecimal color.\n *\n * @example\n * ```ts\n * tint: color(\"#ffffff\");\n * ```\n *\n * @public\n */\nexport function color(defaultValue: ColorLike | string = WHITE, options?: FieldOptions): FieldDefinition<ColorLike> {\n const { r, g, b, a } = typeof defaultValue === \"string\" ? parseHexColor(defaultValue) : defaultValue;\n return field({ kind: FieldKind.color }, options, (): ColorLike => ({ r, g, b, a }));\n}\n\n/**\n * Declares a field restricted to a fixed set of string values.\n *\n * @param values - Every accepted value, in the order the inspector should list them.\n * @param defaultValue - The value a new component starts with; `NoInfer` keeps it out of the\n * inference for `T`, so passing a value `values` does not contain is a compile error as well as a\n * runtime one.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n * @throws A `TypeError` when `defaultValue` is not one of `values`.\n *\n * @example\n * ```ts\n * mode: enumOf([\"walk\", \"run\"] as const, \"walk\");\n * ```\n *\n * @public\n */\nexport function enumOf<const T extends string>(\n values: readonly T[],\n defaultValue: NoInfer<T>,\n options?: FieldOptions,\n): FieldDefinition<T> {\n if (!values.includes(defaultValue)) {\n throwSchemaError(\n SchemaIssueCode.outOfRange,\n `enumOf default \"${defaultValue}\" is not one of [${values.join(\", \")}].`,\n );\n }\n return field({ kind: FieldKind.enum, values: [...values] }, options, () => defaultValue);\n}\n\n/**\n * Declares a reference to another entity in the same scene file. The value is `null` until the\n * scene is fully constructed and is nulled again when the target is destroyed\n * (`docs/architecture/03-scripting-and-components.md` §3).\n *\n * The entity type is supplied by the caller because `Entity` lives in the kernel, which is layered\n * above this module.\n *\n * @typeParam E - The entity type the reference resolves to.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * target: entityRef<Entity>();\n * ```\n *\n * @public\n */\nexport function entityRef<E = unknown>(options?: FieldOptions): FieldDefinition<E | null> {\n return field({ kind: FieldKind.entityRef }, options, (): E | null => null);\n}\n\n/**\n * Declares a reference to a component on an entity in the same scene file.\n *\n * @typeParam C - The component type the reference resolves to, inferred from the class.\n * @param type - The component class the field may point at.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * follow: componentRef(Camera); // Camera | null\n * ```\n *\n * @public\n */\nexport function componentRef<C>(type: ComponentTypeToken<C>, options?: FieldOptions): FieldDefinition<C | null> {\n return field({ kind: FieldKind.componentRef, componentType: type }, options, (): C | null => null);\n}\n\n/**\n * Declares a reference to an addressable asset. The **runtime** value is the loaded\n * {@link AssetHandle}, not an address: a component's `asset()` fields are resolved before its props\n * are written, so `awake` can already read `this.mesh.value`\n * (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * @remarks\n * Files store the address instead — `{ \"$asset\": \"models/hero.glb\", \"type\"?: \"model\" }`\n * (`06-serialization-and-scene-format.md` §3). Encoding reads `handle.address`; decoding hands that\n * address to the `asset` resolver of the `ReferenceDecoder` the scene loader supplies, which answers\n * with the handle the scene already retains. Two consequences game code sees:\n *\n * - An address the resolver cannot answer decodes to `null` and reports `IGX-0602`; the component\n * keeps working with a missing asset rather than failing the whole scene.\n * - An **in-code** asset — anything from `Assets.register`, which includes `MeshAsset.box(…)` and\n * `createMaterialAsset(app, pbrMaterialDefinition({ … }))` — lives at a `memory:` address that names no file, so serializing a\n * component that holds one writes `null` and reports the loss. Save the asset as a file when it\n * has to survive a round trip.\n *\n * The field does **not** retain the handle: the scene instance that loaded it owns the reference\n * count and releases it on unload.\n *\n * @typeParam A - The asset type the reference points at, inferred from the class.\n * @param type - The asset class the field may point at.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * class Hero extends Component.define({ clip: asset(AudioClip) }) {\n * static typeId = \"mygame/Hero\";\n * awake(): void {\n * this.clip?.value.play();\n * }\n * }\n * ```\n *\n * @public\n */\nexport function asset<A>(type: AssetTypeToken<A>, options?: FieldOptions): FieldDefinition<AssetHandle<A> | null> {\n const typeName = type.assetType ?? null;\n return field({ kind: FieldKind.asset, assetType: type, typeName }, options, (): AssetHandle<A> | null => null);\n}\n\n/**\n * Declares a list field. The runtime value type is a *mutable* array because game code is expected\n * to push to it (`this.waypoints.push(p)`); the default is copied on every instantiation, shallowly,\n * so element objects supplied as defaults are shared and should be treated as immutable.\n *\n * @typeParam T - The element value type, inferred from `item`.\n * @param item - The field definition every element follows.\n * @param defaultValue - The list a new component starts with; defaults to empty.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * waypoints: array(vec3()); // Vec3Like[]\n * ```\n *\n * @public\n */\nexport function array<T>(\n item: FieldDefinition<T>,\n defaultValue: readonly T[] = [],\n options?: FieldOptions,\n): FieldDefinition<T[]> {\n const snapshot = [...defaultValue];\n return field({ kind: FieldKind.array, item }, options, (): T[] => [...snapshot]);\n}\n\n/**\n * Declares a fixed group of named sub-fields. Sub-fields are serialized as a nested JSON object in\n * declaration order and validated recursively.\n *\n * @typeParam S - The sub-schema, inferred from `fields`.\n * @param fields - The sub-fields.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * stats: record({ hp: i32(10), armor: f32(0) }); // { hp: number; armor: number }\n * ```\n *\n * @public\n */\nexport function record<S extends Schema>(fields: S, options?: FieldOptions): FieldDefinition<FieldsOf<S>> {\n return field({ kind: FieldKind.record, fields }, options, () => createDefaults(fields));\n}\n\n/**\n * Declares a string-keyed dictionary field. Keys are written in lexicographic order so that two\n * saves of the same state are byte-identical\n * (`docs/architecture/06-serialization-and-scene-format.md` §1).\n *\n * @typeParam T - The entry value type, inferred from `value`.\n * @param value - The field definition every entry's value follows.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * ammo: map(i32(0)); // Record<string, number>\n * ```\n *\n * @public\n */\nexport function map<T>(value: FieldDefinition<T>, options?: FieldOptions): FieldDefinition<Record<string, T>> {\n return field({ kind: FieldKind.map, value }, options, (): Record<string, T> => ({}));\n}\n\n/**\n * Declares a field that may also be `null`, defaulting to `null` (coding standards §5.5: `null` is\n * \"absent value\", `undefined` never reaches a file).\n *\n * @typeParam T - The value type when present, inferred from `inner`.\n * @param inner - The field definition a non-`null` value follows.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * nickname: optional(str()); // string | null\n * ```\n *\n * @public\n */\nexport function optional<T>(inner: FieldDefinition<T>, options?: FieldOptions): FieldDefinition<T | null> {\n return field({ kind: FieldKind.optional, inner }, options, (): T | null => null);\n}\n\n/**\n * Declares a set of layers. Layers are stored by *name*, not by bit value, so renaming a layer in\n * project settings does not silently repoint existing files\n * (`docs/architecture/06-serialization-and-scene-format.md` §3).\n *\n * The value type is a read-only array of names in Phase 1; the kernel's `LayerMask` class arrives\n * with the layer registry and will satisfy the same structural shape.\n *\n * @param defaultValue - The names a new component starts with; defaults to empty.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * collidesWith: layerMask([\"Default\", \"Enemy\"]);\n * ```\n *\n * @public\n */\nexport function layerMask(\n defaultValue: readonly string[] = [],\n options?: FieldOptions,\n): FieldDefinition<readonly string[]> {\n const snapshot = [...defaultValue];\n return field({ kind: FieldKind.layerMask }, options, (): readonly string[] => [...snapshot]);\n}\n\n/**\n * Declares an animation curve field.\n *\n * @param defaultValue - The curve a new component starts with; defaults to no keys.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * falloff: curve({ keys: [[0, 1, 0, 0], [1, 0, 0, 0]] });\n * ```\n *\n * @public\n */\nexport function curve(defaultValue: CurveValue = EMPTY_CURVE, options?: FieldOptions): FieldDefinition<CurveValue> {\n const keys = defaultValue.keys.map((key): CurveKey => [key[0], key[1], key[2], key[3]]);\n return field({ kind: FieldKind.curve }, options, (): CurveValue => ({ keys: [...keys] }));\n}\n\n/**\n * Declares a field whose JSON form is written by hand. Use it for value types the built-in kinds\n * cannot express; the codec owns the default, the encoding, and the generated JSON Schema fragment.\n *\n * @typeParam T - The runtime value type.\n * @param codec - The default factory, `serialize`, `deserialize`, and optional `jsonSchema`.\n * @param options - Inspector and serializer metadata.\n * @returns The field definition.\n *\n * @example\n * ```ts\n * grid: custom({\n * createDefault: () => new Uint8Array(16),\n * serialize: (value) => [...value],\n * deserialize: (json) => Uint8Array.from(Array.isArray(json) ? json.map(Number) : []),\n * jsonSchema: { type: \"array\", items: { type: \"integer\" } },\n * });\n * ```\n *\n * @public\n */\nexport function custom<T>(codec: CustomFieldCodec<T>, options?: FieldOptions): FieldDefinition<T> {\n return field({ kind: FieldKind.custom, codec }, options, () => codec.createDefault());\n}\n","import { Component } from \"../component/component.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport {\n cameraAspectRatio,\n createCameraUnderNode,\n readProjectionMatrix,\n readViewMatrix,\n resolveViewportPixels,\n screenToRay as adapterScreenToRay,\n setCameraClipPlanes,\n setCameraOrthographic,\n setCameraOrthographicSize,\n setCameraParent,\n setCameraPerspective,\n setCameraViewport,\n worldToScreen as adapterWorldToScreen,\n} from \"../lite/camera.js\";\nimport { createPickRay } from \"../lite/picking.js\";\nimport { color, enumOf, f32, i32, optional, record } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { ComponentHooks } from \"../component/component.js\";\nimport type { LiteCamera, LiteOrthographicBounds, MutableRay } from \"../lite/camera.js\";\nimport type { Mat4 } from \"../math/mat4.js\";\nimport type { ColorLike, MutableVec3, Vec3Like } from \"../math/types.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `Camera` component (`docs/architecture/07-rendering.md` §2.1): the entity that defines the\n * view.\n *\n * ## The entity's transform *is* the view\n *\n * `createFreeCamera(position, target)` builds a camera whose **local** matrix is\n * `lookAtWorldLH(position, target, up)` and whose world matrix is `parentWorld × local`\n * (`src/lite/camera.ts`). The adapter creates it at the local origin looking down local `+Z`,\n * ignifx's forward axis (ADR-0011), and parents it under the entity's node — so the camera has\n * exactly the entity's world transform and the component has no follow logic of its own. Moving the\n * entity moves the view, with no per-frame copy. Cinemachine-style rigs are scripts in `@ignifx/3d`\n * that drive that transform.\n *\n * ## Decisions the documents left open\n *\n * - **`clearColor` is optional, not \"default from scene settings\".** §2.1's table says the default\n * comes from the scene settings, which a plain colour field cannot express: every colour has a\n * value. The field is `optional(color())` instead, so `null` means \"leave the scene's clear\n * colour alone\" — whatever the `rendering.clearColor` setting or an `Environment` last put there\n * — and a value means \"this camera owns it while it is the main camera\". The main camera is\n * written every frame, so it is the strongest of the three (`RendererImpl.applyClearColor`).\n * - **`cullingMask` is not declared at all.** §2.1 marks it post-1.0 (Lite has no per-camera mesh\n * list yet) and §8 repeats it. A field that serialises but does nothing is worse than no field:\n * it would round-trip through save files and quietly stop mattering when the feature lands.\n *\n * ## Headless\n *\n * The Lite camera is plain data — `createFreeCamera` touches no device — so a headless `Camera`\n * constructs, keeps its state, and answers `getViewMatrix`. What it cannot answer is anything that\n * needs the render target's pixel size: with no canvas the viewport is 1x1, so `screenToRay` and\n * `worldToScreen` degenerate. `07-rendering.md` §6 says tests assert on component state there.\n */\n\n/** The projections a camera can use. */\n/**\n * The `as const` name table behind the public union of the same name.\n *\n * @public\n */\nexport const PROJECTIONS = [\"perspective\", \"orthographic\"] as const;\n\n/**\n * The union of the camera projections.\n *\n * @public\n */\nexport type CameraProjection = (typeof PROJECTIONS)[number];\n\n/** The render-target size a headless camera pretends to have, so no conversion divides by zero. */\nconst HEADLESS_TARGET_SIZE = 1;\n\n/**\n * A world-space ray, as `Camera.screenToRay` produces and `world.raycastRender` consumes\n * (`docs/architecture/07-rendering.md` §3).\n *\n * @remarks\n * Both vectors are written in place, so a picking loop reuses one ray and allocates nothing\n * (coding standards §7).\n *\n * @public\n */\nexport interface Ray {\n /** Where the ray starts, in world space. */\n readonly origin: RayVector;\n /** The unit direction it travels in. */\n readonly direction: RayVector;\n /** How far it reaches, in metres. */\n length: number;\n}\n\n/**\n * A writable `{ x, y, z }` a ray's origin and direction are stated in.\n *\n * @remarks\n * Deliberately the minimal shape rather than the math module's `MutableVec3`: the engine's `Vec3`,\n * a plain object literal, and a live view over a Lite node all satisfy it, so nothing has to be\n * converted to build or read a ray.\n *\n * @public\n */\nexport interface RayVector {\n /** The x component. */\n x: number;\n /** The y component. */\n y: number;\n /** The z component. */\n z: number;\n}\n\n/**\n * Creates a reusable ray at the origin pointing along `+Z`.\n *\n * @returns A fresh ray. **Allocates** — make one per call site, not per frame.\n *\n * @example\n * ```ts\n * const ray = createRay();\n * camera.screenToRay(event.offsetX, event.offsetY, ray);\n * ```\n *\n * @public\n */\nexport function createRay(): Ray {\n return { origin: { x: 0, y: 0, z: 0 }, direction: { x: 0, y: 0, z: 1 }, length: Number.MAX_VALUE };\n}\n\n/**\n * The camera an entity renders the world through (`docs/architecture/07-rendering.md` §2.1).\n *\n * @remarks\n * A world renders through the enabled camera with the highest `priority`; ties break on creation\n * order. A world with no enabled camera draws nothing and logs `IGX-0706` once.\n *\n * @example\n * ```ts\n * const eye = world.createEntity(\"Main Camera\", { position: { x: 0, y: 2, z: -6 } });\n * eye.addComponent(Camera, { fov: 50, near: 0.05 });\n * ```\n *\n * @public\n */\nexport class Camera extends Component implements ComponentHooks {\n /** The namespaced registration id. */\n static typeId = \"ignifx/Camera\";\n\n /** At most one camera per entity: two views from one transform would be the same view. */\n static allowMultiple = false;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = cameraSchema();\n\n declare projection: CameraProjection;\n\n declare fov: number;\n\n declare orthographicSize: number;\n\n declare near: number;\n\n declare far: number;\n\n declare viewport: { x: number; y: number; width: number; height: number };\n\n declare clearColor: ColorLike | null;\n\n declare priority: number;\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(Camera.schema));\n }\n\n readonly #ray: MutableRay = createPickRay();\n\n readonly #targetSize = { width: HEADLESS_TARGET_SIZE, height: HEADLESS_TARGET_SIZE };\n\n #camera: LiteCamera | null = null;\n\n #ortho: LiteOrthographicBounds | null = null;\n\n #appliedProjection: CameraProjection | null = null;\n\n #appliedFov = Number.NaN;\n\n #appliedOrthographicSize = Number.NaN;\n\n #appliedNear = Number.NaN;\n\n #appliedFar = Number.NaN;\n\n #appliedViewportX = Number.NaN;\n\n #appliedViewportY = Number.NaN;\n\n #appliedViewportWidth = Number.NaN;\n\n #appliedViewportHeight = Number.NaN;\n\n /**\n * The Babylon Lite camera this component owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The camera, or `null` before the component is attached.\n */\n get lite(): { readonly camera: LiteCamera | null } {\n return { camera: this.#camera };\n }\n\n /** Creates the Lite camera and parents it under the entity's node. */\n onAttach(): void {\n this.#camera = createCameraUnderNode(entityInternals(this.entity).node);\n this.#apply();\n }\n\n /**\n * Drops the Lite camera.\n *\n * @remarks\n * A Lite camera holds no GPU resource and is never added to the scene — only assigned to\n * `scene.camera` — so breaking the parent link and forgetting it is the whole teardown. The\n * `PreRender` system re-picks the main camera on the next frame and clears `scene.camera` when\n * this was the last one.\n */\n onDetach(): void {\n const camera = this.#camera;\n this.#camera = null;\n this.#ortho = null;\n if (camera !== null) {\n setCameraParent(camera, null);\n }\n }\n\n /**\n * Builds a world-space ray through a point on the canvas.\n *\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param out - The ray to fill; a fresh one is allocated when omitted.\n * @returns `out`, or `null` when the view-projection matrix is singular — a zero-sized viewport,\n * or a camera that is not attached.\n *\n * @example\n * ```ts\n * const ray = camera.screenToRay(event.offsetX, event.offsetY);\n * const hit = ray === null ? null : world.raycastRender(ray);\n * ```\n */\n screenToRay(x: number, y: number, out: Ray = createRay()): Ray | null {\n const camera = this.#camera;\n if (camera === null) {\n return null;\n }\n const viewport = resolveViewportPixels(camera, this.#width(), this.#height());\n const filled = adapterScreenToRay(\n camera,\n x - viewport.x,\n y - viewport.y,\n viewport.width,\n viewport.height,\n this.#ray,\n );\n if (filled === null) {\n return null;\n }\n writeVec3(out.origin, filled.origin);\n writeVec3(out.direction, filled.direction);\n out.length = filled.length;\n return out;\n }\n\n /**\n * Projects a world-space point onto the canvas.\n *\n * @param point - The world-space point.\n * @param out - Receives the pixel position in `x`/`y` — measured from the viewport's top left —\n * and the clip depth in `z`, which is `1` at the near plane and `0` at the far plane because\n * Lite's projection is reverse-depth.\n * @returns `true` when the point is in front of the camera; `false` when it is behind it, in which\n * case `out` holds a mirrored projection and should be ignored.\n */\n worldToScreen(point: Vec3Like, out: MutableVec3): boolean {\n const camera = this.#camera;\n if (camera === null) {\n return false;\n }\n const viewport = resolveViewportPixels(camera, this.#width(), this.#height());\n const inFront = adapterWorldToScreen(camera, point, viewport.width, viewport.height, out);\n out.x += viewport.x;\n out.y += viewport.y;\n return inFront;\n }\n\n /**\n * The world-space point a canvas pixel maps to at a given distance along the view ray.\n *\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param distance - How far along the ray to travel, in metres.\n * @param out - Receives the point.\n * @returns `out`, or `null` when no ray could be built.\n */\n screenToWorldPoint(x: number, y: number, distance: number, out: MutableVec3): MutableVec3 | null {\n const ray = this.screenToRay(x, y, rayScratch());\n if (ray === null) {\n return null;\n }\n out.x = ray.origin.x + ray.direction.x * distance;\n out.y = ray.origin.y + ray.direction.y * distance;\n out.z = ray.origin.z + ray.direction.z * distance;\n return out;\n }\n\n /**\n * The world-space point a **normalized** viewport coordinate maps to.\n *\n * @param u - The horizontal coordinate, `0` at the viewport's left edge and `1` at its right.\n * @param v - The vertical coordinate, `0` at the **bottom** edge and `1` at the top, matching\n * Babylon's viewport convention.\n * @param distance - How far along the ray to travel, in metres.\n * @param out - Receives the point.\n * @returns `out`, or `null` when no ray could be built.\n */\n viewportToWorldPoint(u: number, v: number, distance: number, out: MutableVec3): MutableVec3 | null {\n const camera = this.#camera;\n if (camera === null) {\n return null;\n }\n const viewport = resolveViewportPixels(camera, this.#width(), this.#height());\n return this.screenToWorldPoint(\n viewport.x + u * viewport.width,\n viewport.y + (1 - v) * viewport.height,\n distance,\n out,\n );\n }\n\n /**\n * Copies the camera's projection matrix into `out`.\n *\n * @param out - A 4x4 matrix that receives the result, column-major.\n * @returns `out`, for chaining.\n */\n getProjectionMatrix(out: Mat4): Mat4 {\n const camera = this.#camera;\n if (camera !== null) {\n readProjectionMatrix(camera, cameraAspectRatio(camera, this.#width(), this.#height()), out.elements);\n }\n return out;\n }\n\n /**\n * Copies the camera's view matrix — the inverse of its world matrix — into `out`.\n *\n * @param out - A 4x4 matrix that receives the result, column-major.\n * @returns `out`, for chaining.\n */\n getViewMatrix(out: Mat4): Mat4 {\n const camera = this.#camera;\n if (camera !== null) {\n readViewMatrix(camera, out.elements);\n }\n return out;\n }\n\n /**\n * Writes every field that changed since the last frame onto the Lite camera, and refreshes the\n * render-target size the screen conversions divide by. The `PreRender` system calls it.\n *\n * @param renderer - The rendering service, for the surface size.\n *\n * @internal\n */\n sync(renderer: RendererImpl): void {\n renderer.readTargetSize(this.#targetSize);\n this.#apply();\n }\n\n /** Writes every field whose value differs from the one last applied. */\n #apply(): void {\n const camera = this.#camera;\n if (camera === null) {\n return;\n }\n const projection: CameraProjection = this.projection;\n if (projection === \"orthographic\") {\n const bounds = this.#ortho;\n if (this.#appliedProjection !== projection || bounds === null) {\n this.#ortho = setCameraOrthographic(camera, this.orthographicSize);\n this.#appliedOrthographicSize = this.orthographicSize;\n } else if (this.#appliedOrthographicSize !== this.orthographicSize) {\n // Mutating the live bounds rather than calling `enableOrthographicCamera` again keeps the\n // object identity Lite caches against, so a zoom animation allocates nothing.\n setCameraOrthographicSize(bounds, this.orthographicSize);\n this.#appliedOrthographicSize = this.orthographicSize;\n }\n } else if (this.#appliedProjection !== projection || this.#appliedFov !== this.fov) {\n setCameraPerspective(camera, this.fov);\n this.#ortho = null;\n this.#appliedFov = this.fov;\n }\n this.#appliedProjection = projection;\n if (this.#appliedNear !== this.near || this.#appliedFar !== this.far) {\n setCameraClipPlanes(camera, this.near, this.far);\n this.#appliedNear = this.near;\n this.#appliedFar = this.far;\n }\n const viewport = this.viewport;\n if (\n this.#appliedViewportX !== viewport.x ||\n this.#appliedViewportY !== viewport.y ||\n this.#appliedViewportWidth !== viewport.width ||\n this.#appliedViewportHeight !== viewport.height\n ) {\n setCameraViewport(camera, viewport.x, viewport.y, viewport.width, viewport.height);\n this.#appliedViewportX = viewport.x;\n this.#appliedViewportY = viewport.y;\n this.#appliedViewportWidth = viewport.width;\n this.#appliedViewportHeight = viewport.height;\n }\n }\n\n /**\n * The render target's width in pixels.\n *\n * @returns The width; `1` before the first sync, and under a headless app.\n */\n #width(): number {\n return this.#targetSize.width;\n }\n\n /**\n * The render target's height in pixels.\n *\n * @returns The height; `1` before the first sync, and under a headless app.\n */\n #height(): number {\n return this.#targetSize.height;\n }\n}\n\n/** One reusable ray per module, for the conversions that build one and throw it away. */\nlet scratchRay: Ray | null = null;\n\n/**\n * The module's scratch ray, created on first use (coding standards §4 — no allocation at module\n * scope, none per call).\n *\n * @returns The shared ray.\n */\nfunction rayScratch(): Ray {\n return (scratchRay ??= createRay());\n}\n\n/**\n * Copies a Lite three-element tuple into an ignifx vector.\n *\n * @param out - The vector to fill.\n * @param source - Lite's tuple.\n */\nfunction writeVec3(out: RayVector, source: readonly [number, number, number]): void {\n out.x = source[0];\n out.y = source[1];\n out.z = source[2];\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function, not at module scope: a schema field is a function\n * call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4).\n */\nfunction cameraSchema(): Schema {\n return defineSchema({\n projection: enumOf(PROJECTIONS, \"perspective\", { tooltip: \"Perspective, or a flat orthographic view.\" }),\n fov: f32(60, { min: 1, max: 179, tooltip: \"Vertical field of view, in degrees.\" }),\n orthographicSize: f32(5, { min: 0.0001, tooltip: \"Half the visible height, in metres.\" }),\n near: f32(0.1, { min: 0.0001, tooltip: \"Near clip plane, in metres.\" }),\n far: f32(1000, { min: 0.0002, tooltip: \"Far clip plane, in metres.\" }),\n viewport: record(\n {\n x: f32(0, { min: 0, max: 1 }),\n y: f32(0, { min: 0, max: 1 }),\n width: f32(1, { min: 0, max: 1 }),\n height: f32(1, { min: 0, max: 1 }),\n },\n { tooltip: \"Normalized viewport; y is measured from the bottom.\" },\n ),\n clearColor: optional(color(\"#000000\"), { tooltip: \"Overrides the scene clear colour while this camera renders.\" }),\n priority: i32(0, { tooltip: \"The enabled camera with the highest priority renders.\" }),\n });\n}\n","import {\n AcesToneMapping,\n loadEnvironment,\n loadSkybox,\n NeutralToneMapping,\n setEnvironmentBlur,\n setEnvironmentRotation,\n setSceneImageProcessing,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../../errors/ignifx-error.js\";\nimport { degToRad } from \"../../math/math-utils.js\";\nimport type { EnvironmentTextures, SceneContext, ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * Environment half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.5): image\n * based lighting, the skybox, fog, image processing, and the clear colour.\n *\n * Everything here is `@internal`. Loading uploads cube maps, so the module is GPU-only.\n *\n * ## The BRDF LUT is mandatory (verified against `@babylonjs/lite@1.27.0`)\n *\n * `loadEnvironment(scene, url, options)` (`index.d.ts` 6779) takes a **required** `brdfUrl`: Lite\n * decodes the split-sum BRDF lookup table from a pre-baked RGBD PNG rather than computing it, \"for\n * pixel-perfect parity\" with Babylon.js (`lib/_chunks/env-helpers-*.js`, `loadBrdfImage`, which\n * `fetch`es the URL and decodes it with `createImageBitmap`). ignifx ships that PNG as\n * `tests/fixtures/assets/brdf-lut.png`, decoded from Babylon.js's own\n * `_environmentBRDFBase64Texture` (`packages/dev/core/src/Misc/brdfTextureTools.ts`, Apache-2.0).\n * It is 256×256 RGBA8 and 23 KB.\n *\n * ## Fog\n *\n * `SceneContext.fog` is `FogConfig | null` (`index.d.ts` 5350) with a numeric `mode`; Lite exports\n * no named constants for it, so {@link FOG_MODES} maps ignifx's names onto the numbers.\n *\n * ## Image processing\n *\n * `setSceneImageProcessing` is **async** (`index.d.ts` 10917) because tone mapping is baked into\n * the PBR shaders at `registerScene` time; changing it recompiles the affected pipelines\n * (`rebuildScenePbrPipelines`). Setting exposure or contrast alone still goes through the same\n * call.\n */\n\n/**\n * The GPU-resident image-based-lighting textures `loadEnvironment` resolves to, re-exported under an\n * ignifx name (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteEnvironmentTextures = EnvironmentTextures;\n\n/**\n * ignifx fog mode names mapped to the numbers `FogConfig.mode` uses.\n *\n * @internal\n */\nexport const FOG_MODES = {\n /** No fog. */\n none: 0,\n /** Exponential fog. */\n exp: 1,\n /** Squared-exponential fog. */\n exp2: 2,\n /** Linear fog between `start` and `end`. */\n linear: 3,\n} as const;\n\n/**\n * The union of the fog mode names.\n *\n * @internal\n */\nexport type FogMode = keyof typeof FOG_MODES;\n\n/**\n * The tone-mapping curves `docs/architecture/07-rendering.md` §2.5 exposes.\n *\n * @internal\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\"] as const;\n\n/**\n * The union of the tone-mapping curve names.\n *\n * @internal\n */\nexport type ToneMappingName = (typeof TONE_MAPPING_NAMES)[number];\n\n/**\n * How an ignifx `Environment` component configures image based lighting.\n *\n * @internal\n */\nexport interface EnvironmentLoadOptions {\n /** The `.env` file holding the prefiltered specular cube map and its spherical harmonics. */\n readonly url: string;\n /** The RGBD PNG BRDF lookup table. Required by Lite. */\n readonly brdfUrl: string;\n /** A `.dds` or `.env` skybox. Omit for a flat background. */\n readonly skyboxUrl?: string;\n /** The skybox cube's size, in metres. Lite defaults to 20. */\n readonly skyboxSize?: number;\n /** Skip the skybox entirely. */\n readonly skipSkybox?: boolean;\n /** Skip the reflective ground plane Lite would otherwise add. */\n readonly skipGround?: boolean;\n /** A texture for that ground plane. */\n readonly groundTextureUrl?: string;\n}\n\n/**\n * Loads an `.env` environment and installs it on a scene.\n *\n * @param scene - The scene to light.\n * @param options - The environment, BRDF, and skybox URLs.\n * @returns The GPU-resident environment textures, for materials that need them explicitly.\n *\n * @example\n * ```ts\n * await loadSceneEnvironment(scene, {\n * url: \"environments/studio.env\",\n * brdfUrl: \"environments/brdf-lut.png\",\n * });\n * ```\n *\n * @internal\n */\nexport function loadSceneEnvironment(\n scene: SceneContext,\n options: EnvironmentLoadOptions,\n): Promise<EnvironmentTextures> {\n const liteOptions: {\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround?: boolean;\n groundTextureUrl?: string;\n } = { brdfUrl: options.brdfUrl };\n if (options.skyboxUrl !== undefined) {\n liteOptions.skyboxUrl = options.skyboxUrl;\n }\n if (options.skyboxSize !== undefined) {\n liteOptions.skyboxSize = options.skyboxSize;\n }\n if (options.skipSkybox !== undefined) {\n liteOptions.skipSkybox = options.skipSkybox;\n }\n if (options.skipGround !== undefined) {\n liteOptions.skipGround = options.skipGround;\n }\n if (options.groundTextureUrl !== undefined) {\n liteOptions.groundTextureUrl = options.groundTextureUrl;\n }\n return loadEnvironment(scene, options.url, liteOptions);\n}\n\n/**\n * Loads a six-face cube-map skybox from a base URL.\n *\n * @param scene - The scene to give a background.\n * @param baseUrl - The URL prefix each face name is appended to.\n * @param extension - The face file extension, such as `\".jpg\"`.\n * @param size - The skybox cube's size, in metres.\n * @returns A promise that resolves when the faces are uploaded.\n *\n * @internal\n */\nexport function loadSceneSkybox(scene: SceneContext, baseUrl: string, extension: string, size?: number): Promise<void> {\n return loadSkybox(scene, baseUrl, extension, size);\n}\n\n/**\n * Rotates the environment around the world Y axis.\n *\n * @param scene - The scene to rotate the environment of.\n * @param degrees - The rotation, in degrees.\n *\n * @internal\n */\nexport function setSceneEnvironmentRotation(scene: SceneContext, degrees: number): void {\n setEnvironmentRotation(scene, degToRad(degrees));\n}\n\n/**\n * Blurs the environment's specular reflection.\n *\n * @param scene - The scene to change.\n * @param blur - The blur amount, 0 to 1.\n *\n * @internal\n */\nexport function setSceneEnvironmentBlur(scene: SceneContext, blur: number): void {\n setEnvironmentBlur(scene, blur);\n}\n\n/**\n * Sets the colour the scene is cleared to each frame.\n *\n * @param scene - The scene to change.\n * @param r - The linear red component, 0 to 1.\n * @param g - The linear green component, 0 to 1.\n * @param b - The linear blue component, 0 to 1.\n * @param a - The alpha component; only meaningful with a premultiplied canvas alpha mode.\n *\n * @internal\n */\nexport function setSceneClearColor(scene: SceneContext, r: number, g: number, b: number, a: number): void {\n const clear = scene.clearColor;\n clear.r = r;\n clear.g = g;\n clear.b = b;\n clear.a = a;\n}\n\n/**\n * Configures the scene's fog, or turns it off.\n *\n * @param scene - The scene to change.\n * @param mode - The fog falloff, or `\"none\"` to disable it.\n * @param r - The linear red component of the fog colour.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n * @param density - The density, for the exponential modes.\n * @param start - Where linear fog begins, in metres.\n * @param end - Where linear fog reaches full strength, in metres.\n *\n * @internal\n */\nexport function setSceneFog(\n scene: SceneContext,\n mode: FogMode,\n r: number,\n g: number,\n b: number,\n density: number,\n start: number,\n end: number,\n): void {\n if (mode === \"none\") {\n scene.fog = null;\n return;\n }\n const existing = scene.fog;\n if (existing === null) {\n scene.fog = { mode: FOG_MODES[mode], density, start, end, color: [r, g, b] };\n return;\n }\n existing.mode = FOG_MODES[mode];\n existing.density = density;\n existing.start = start;\n existing.end = end;\n const color = existing.color;\n color[0] = r;\n color[1] = g;\n color[2] = b;\n}\n\n/**\n * Sets exposure, contrast, and the tone-mapping curve.\n *\n * @remarks\n * Asynchronous by nature: tone mapping is compiled into the PBR shaders, so changing it after\n * `registerScene` recompiles the scene's PBR pipelines. Exposure and contrast alone are uniform\n * values, but Lite routes them through the same call.\n *\n * @param scene - The scene to change.\n * @param exposure - The exposure multiplier.\n * @param contrast - The contrast multiplier.\n * @param toneMapping - The curve, or `\"none\"` to leave the colour untouched.\n * @returns A promise that resolves when any affected pipeline has been rebuilt.\n *\n * @internal\n */\nexport function setSceneImageProcessingOptions(\n scene: SceneContext,\n exposure: number,\n contrast: number,\n toneMapping: ToneMappingName,\n): Promise<void> {\n if (toneMapping === \"none\") {\n return setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: false });\n }\n return setSceneImageProcessing(scene, {\n exposure,\n contrast,\n toneMappingEnabled: true,\n toneMapping: toneMappingCurve(toneMapping),\n });\n}\n\n/**\n * Maps an ignifx tone-mapping name onto the Lite curve object.\n *\n * @param name - The curve name; `\"none\"` is handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\">): ToneMapping {\n switch (name) {\n case \"standard\":\n return StandardToneMapping;\n case \"aces\":\n return AcesToneMapping;\n case \"neutral\":\n return NeutralToneMapping;\n default:\n return assertNever(name, \"tone mapping\");\n }\n}\n","import { clamp01, EPSILON, lerp } from \"./math-utils.js\";\nimport type { ColorLike } from \"./types.js\";\n\n/**\n * Matches `#rrggbb`, `#rrggbbaa`, and the same two without the leading `#`.\n */\nconst HEX_PATTERN = /^#?(?:[\\da-f]{6}|[\\da-f]{8})$/iu;\n\n/**\n * Formats a 0-255 channel as two lowercase hex digits.\n *\n * @param value - The channel value, already rounded into 0-255.\n * @returns Two hex digits.\n */\nfunction hexByte(value: number): string {\n return value.toString(16).padStart(2, \"0\");\n}\n\n/**\n * An RGBA colour whose components are **linear** and normally in 0-1 (values above 1 are allowed\n * and mean HDR intensity). Lighting maths only works in linear space, which is why this is the\n * space ignifx stores; scene files and hex strings are sRGB, and\n * {@link Color.fromHex}/{@link Color.fromSrgb} are the doors between the two\n * (`docs/architecture/06-serialization-and-scene-format.md` section 3).\n *\n * Every method says which space it works in. The rule of thumb: if it takes or returns a hex string\n * or has `Srgb` in its name, it is sRGB; everything else is linear.\n *\n * @example\n * ```ts\n * const tint = Color.fromHex(\"#ff8800\") ?? new Color(1, 1, 1, 1); // parsed as sRGB, stored linear\n * tint.scaleRgb(2); // twice as bright, same alpha\n * tint.toHex(); // back to sRGB: \"#ffbe00\"\n * ```\n *\n * @public\n */\nexport class Color {\n /** The linear red component. */\n r: number;\n /** The linear green component. */\n g: number;\n /** The linear blue component. */\n b: number;\n /** The alpha component in 0-1. Alpha is always linear, never gamma encoded. */\n a: number;\n\n /**\n * Creates a colour from linear components.\n *\n * @param r - The linear red component. Defaults to 0.\n * @param g - The linear green component. Defaults to 0.\n * @param b - The linear blue component. Defaults to 0.\n * @param a - The alpha component. Defaults to 1 (opaque).\n */\n constructor(r: number = 0, g: number = 0, b: number = 0, a: number = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n /**\n * Assigns every component at once, in linear space.\n *\n * @param r - The new linear red component.\n * @param g - The new linear green component.\n * @param b - The new linear blue component.\n * @param a - The new alpha component.\n * @returns This colour.\n */\n set(r: number, g: number, b: number, a: number): this {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n return this;\n }\n\n /**\n * Copies every component from another colour.\n *\n * @param c - The colour to read.\n * @returns This colour.\n */\n copyFrom(c: ColorLike): this {\n this.r = c.r;\n this.g = c.g;\n this.b = c.b;\n this.a = c.a;\n return this;\n }\n\n /**\n * Copies this colour into a new one.\n *\n * @returns A new colour. **Allocates.**\n */\n clone(): Color {\n return new Color(this.r, this.g, this.b, this.a);\n }\n\n /**\n * Multiplies this colour by another, component by component including alpha — the usual way a\n * tint is applied.\n *\n * @param c - The colour to multiply by.\n * @returns This colour.\n */\n multiply(c: ColorLike): this {\n this.r *= c.r;\n this.g *= c.g;\n this.b *= c.b;\n this.a *= c.a;\n return this;\n }\n\n /**\n * Scales the linear RGB components, leaving alpha alone. This is what \"brighter\" means: alpha is\n * coverage, not colour.\n *\n * @param factor - The intensity factor.\n * @returns This colour.\n */\n scaleRgb(factor: number): this {\n this.r *= factor;\n this.g *= factor;\n this.b *= factor;\n return this;\n }\n\n /**\n * Moves this colour towards a target, in linear space (which is where blending belongs; lerping\n * sRGB values darkens midpoints).\n *\n * @param target - The colour reached at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns This colour.\n */\n lerp(target: ColorLike, t: number): this {\n return Color.lerpToRef(this, target, t, this);\n }\n\n /**\n * Compares this colour with another, component by component, with a tolerance.\n *\n * @param c - The colour to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(c: ColorLike, epsilon: number = EPSILON): boolean {\n return Color.equalsWithEpsilon(this, c, epsilon);\n }\n\n /**\n * Writes the **linear** components into a `Float32Array`, the form a shader wants. The output\n * comes first to mirror Babylon Lite's `toArray` helpers.\n *\n * @param out - The array to write into.\n * @param offset - The index of the red component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.r;\n out[offset + 1] = this.g;\n out[offset + 2] = this.b;\n out[offset + 3] = this.a;\n return out;\n }\n\n /**\n * Writes this colour's **sRGB-encoded** components into `out`, for display, pickers and files.\n * Components are clamped into 0-1 by the encoding curve.\n *\n * @param out - The colour to write; may be this colour. Its fields hold sRGB values afterwards,\n * not linear ones.\n * @returns `out`.\n */\n toSrgbToRef<TOut extends Color>(out: TOut): TOut {\n return out.set(Color.linearToSrgb(this.r), Color.linearToSrgb(this.g), Color.linearToSrgb(this.b), this.a);\n }\n\n /**\n * Encodes this colour as an sRGB hex string.\n *\n * @returns `#rrggbb` for an opaque colour, `#rrggbbaa` when alpha is below 1. **Allocates a\n * string.**\n *\n * @example\n * ```ts\n * new Color(1, 1, 1, 1).toHex(); // \"#ffffff\"\n * ```\n */\n toHex(): string {\n const r = hexByte(Math.round(Color.linearToSrgb(this.r) * 255));\n const g = hexByte(Math.round(Color.linearToSrgb(this.g) * 255));\n const b = hexByte(Math.round(Color.linearToSrgb(this.b) * 255));\n const alpha = clamp01(this.a);\n if (alpha >= 1) {\n return `#${r}${g}${b}`;\n }\n return `#${r}${g}${b}${hexByte(Math.round(alpha * 255))}`;\n }\n\n /**\n * Opaque white.\n *\n * @returns A new linear `(1, 1, 1, 1)`. **Allocates.**\n */\n static white(): Color {\n return new Color(1, 1, 1, 1);\n }\n\n /**\n * Opaque black.\n *\n * @returns A new linear `(0, 0, 0, 1)`. **Allocates.**\n */\n static black(): Color {\n return new Color(0, 0, 0, 1);\n }\n\n /**\n * Fully transparent black.\n *\n * @returns A new linear `(0, 0, 0, 0)`. **Allocates.**\n */\n static transparent(): Color {\n return new Color(0, 0, 0, 0);\n }\n\n /**\n * Copies any colour-shaped value into a `Color`.\n *\n * @param c - The linear colour to copy.\n * @returns A new colour. **Allocates.**\n */\n static from(c: ColorLike): Color {\n return new Color(c.r, c.g, c.b, c.a);\n }\n\n /**\n * Converts one **sRGB** channel to linear, using the IEC 61966-2-1 curve Babylon Lite uses\n * (`lib/math/color.js`).\n *\n * @param channel - The sRGB channel value; clamped into 0-1.\n * @returns The linear value.\n */\n static srgbToLinear(channel: number): number {\n const c = clamp01(channel);\n return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n }\n\n /**\n * Converts one **linear** channel to sRGB, the inverse of {@link Color.srgbToLinear}.\n *\n * @param channel - The linear channel value; clamped into 0-1, so HDR intensity is lost.\n * @returns The sRGB value.\n */\n static linearToSrgb(channel: number): number {\n const c = clamp01(channel);\n return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;\n }\n\n /**\n * Builds a colour from **sRGB** components, converting RGB to linear and taking alpha as-is.\n *\n * @param r - The sRGB red component, 0-1.\n * @param g - The sRGB green component, 0-1.\n * @param b - The sRGB blue component, 0-1.\n * @param a - The alpha component, 0-1. Defaults to 1.\n * @returns A new colour holding linear components. **Allocates.**\n */\n static fromSrgb(r: number, g: number, b: number, a: number = 1): Color {\n return Color.fromSrgbToRef(r, g, b, a, new Color());\n }\n\n /**\n * Writes a colour built from **sRGB** components into `out`.\n *\n * @param r - The sRGB red component, 0-1.\n * @param g - The sRGB green component, 0-1.\n * @param b - The sRGB blue component, 0-1.\n * @param a - The alpha component, 0-1.\n * @param out - The colour to write; holds linear components afterwards.\n * @returns `out`.\n */\n static fromSrgbToRef<TOut extends Color>(r: number, g: number, b: number, a: number, out: TOut): TOut {\n return out.set(Color.srgbToLinear(r), Color.srgbToLinear(g), Color.srgbToLinear(b), a);\n }\n\n /**\n * Parses an **sRGB** hex string into a linear colour.\n *\n * @param hex - `#rrggbb` or `#rrggbbaa`, with or without the leading `#`, in either case.\n * @returns A new colour, or `null` when the string is not a hex colour. Colours arrive from files\n * and user input, so a bad one is expected absence rather than API misuse (coding standards\n * section 5.5): the caller decides whether to substitute a default or raise a load error.\n * **Allocates.**\n *\n * @example\n * ```ts\n * const tint = Color.fromHex(\"#ff8800aa\") ?? Color.white();\n * ```\n */\n static fromHex(hex: string): Color | null {\n const out = new Color();\n return Color.fromHexToRef(hex, out) ? out : null;\n }\n\n /**\n * Parses an **sRGB** hex string into `out` as linear components.\n *\n * @param hex - `#rrggbb` or `#rrggbbaa`, with or without the leading `#`, in either case.\n * @param out - The colour to write; left untouched when parsing fails.\n * @returns `true` when `hex` was a valid hex colour.\n */\n static fromHexToRef(hex: string, out: Color): boolean {\n if (!HEX_PATTERN.test(hex)) {\n return false;\n }\n const body = hex.startsWith(\"#\") ? hex.slice(1) : hex;\n const r = Number.parseInt(body.slice(0, 2), 16) / 255;\n const g = Number.parseInt(body.slice(2, 4), 16) / 255;\n const b = Number.parseInt(body.slice(4, 6), 16) / 255;\n const a = body.length === 8 ? Number.parseInt(body.slice(6, 8), 16) / 255 : 1;\n Color.fromSrgbToRef(r, g, b, a, out);\n return true;\n }\n\n /**\n * Writes the component-wise product `a * b` into `out`, in linear space.\n *\n * @param a - The first colour.\n * @param b - The second colour.\n * @param out - The colour to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends Color>(a: ColorLike, b: ColorLike, out: TOut): TOut {\n return out.set(a.r * b.r, a.g * b.g, a.b * b.b, a.a * b.a);\n }\n\n /**\n * Writes `c` with its RGB scaled and its alpha untouched into `out`.\n *\n * @param c - The colour to scale.\n * @param factor - The intensity factor.\n * @param out - The colour to write; may alias `c`.\n * @returns `out`.\n */\n static scaleRgbToRef<TOut extends Color>(c: ColorLike, factor: number, out: TOut): TOut {\n return out.set(c.r * factor, c.g * factor, c.b * factor, c.a);\n }\n\n /**\n * Writes the linear-space interpolation of `a` and `b` into `out`.\n *\n * @param a - The colour written at `t === 0`.\n * @param b - The colour written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The colour to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static lerpToRef<TOut extends Color>(a: ColorLike, b: ColorLike, t: number, out: TOut): TOut {\n return out.set(lerp(a.r, b.r, t), lerp(a.g, b.g, t), lerp(a.b, b.b, t), lerp(a.a, b.a, t));\n }\n\n /**\n * Compares two colours component by component, with a tolerance.\n *\n * @param a - The first colour.\n * @param b - The second colour.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: ColorLike, b: ColorLike, epsilon: number = EPSILON): boolean {\n return (\n Math.abs(a.r - b.r) <= epsilon &&\n Math.abs(a.g - b.g) <= epsilon &&\n Math.abs(a.b - b.b) <= epsilon &&\n Math.abs(a.a - b.a) <= epsilon\n );\n }\n}\n","import type { LiteEnvironmentTextures } from \"../lite/gpu/environment.js\";\n\n/**\n * `EnvironmentAsset` (`docs/architecture/05-assets-and-loading.md` §5,\n * `07-rendering.md` §2.5): the image-based lighting a scene is lit by, and the skybox that shows\n * behind it.\n *\n * ## Why an environment is loaded against a scene\n *\n * Lite's `loadEnvironment(scene, url, { brdfUrl, … })` (`index.d.ts` 6779) does not return a\n * detached texture set: it installs the prefiltered cube map, its spherical harmonics, and the\n * skybox **onto a scene** and hands back the GPU handles as a receipt. So an `EnvironmentAsset` is\n * unusual among assets — it is bound to the world it was loaded for, and a second world would have\n * to load it again. That is Lite's shape, not a choice; the asset records the addresses so the\n * `Environment` component can say what it installed, and holds the receipt for materials that need\n * the textures explicitly.\n *\n * ## The BRDF lookup table is mandatory\n *\n * `brdfUrl` is a **required** parameter: Lite decodes the split-sum lookup table from a pre-baked\n * RGBD PNG rather than computing it, for pixel-perfect parity with Babylon.js\n * (`lib/_chunks/env-helpers-*.js`). Nothing in `07-rendering.md` says where a game gets that file,\n * so ignifx puts the address in the `rendering.brdfLut` setting and lets an `Environment` override\n * it. The repository ships one at `tests/fixtures/assets/brdf-lut.png` (Apache-2.0, decoded from\n * Babylon.js's own `_environmentBRDFBase64Texture`).\n *\n * ## Headless\n *\n * The load uploads cube maps, so a headless app produces an asset with `lite.textures === null` and\n * an `Environment` that holds it applies only the parts that are plain scene state — fog, the clear\n * colour, the rotation — and skips the rest (`07-rendering.md` §6).\n */\n\n/**\n * The asset type environments are registered under.\n *\n * @public\n */\nexport const ENVIRONMENT_ASSET_TYPE = \"environment\";\n\n/**\n * The address suffixes that select the environment loader.\n *\n * @public\n */\nexport const ENVIRONMENT_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".env\", \".hdr\", \".dds\"]);\n\n/**\n * The `format` header an `.environment.json` carries\n * (`docs/architecture/06-serialization-and-scene-format.md` §6).\n *\n * @public\n */\nexport const ENVIRONMENT_FILE_FORMAT = \"ignifx.environment\";\n\n/**\n * The only `.environment.json` `formatVersion` this build reads.\n *\n * @public\n */\nexport const ENVIRONMENT_FORMAT_VERSION = 1;\n\n/**\n * The address suffix that selects the environment *description* file.\n *\n * @public\n */\nexport const ENVIRONMENT_FILE_EXTENSION = \".environment.json\";\n\n/**\n * What an `.environment.json` declares, or what an `.env` address implies\n * (`docs/architecture/06-serialization-and-scene-format.md` §6).\n *\n * @remarks\n * The description file exists so a project can pin the skybox and the BRDF table next to the IBL\n * rather than repeating them on every `Environment` component. Loading a bare `.env` address\n * produces the same shape with everything but `environment` left at its default.\n *\n * @public\n */\nexport interface EnvironmentDefinition {\n /** The `.env` file holding the prefiltered specular cube map and its spherical harmonics. */\n readonly environment: string;\n /** The RGBD BRDF lookup table, or empty to take `rendering.brdfLut`. */\n readonly brdfLut: string;\n /** A `.dds` or `.env` skybox, or empty for none. */\n readonly skybox: string;\n /** The skybox cube's size, in metres. Lite defaults to 20. */\n readonly skyboxSize: number;\n /** Whether a skybox is drawn at all. */\n readonly skyboxEnabled: boolean;\n /** How blurred the specular reflection is, 0 to 1. */\n readonly blur: number;\n /** Rotation around the world Y axis, in degrees. */\n readonly rotation: number;\n}\n\n/**\n * The Babylon Lite objects an {@link EnvironmentAsset} owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @public\n */\nexport interface EnvironmentAssetLiteHandles {\n /** The GPU-resident cube map, BRDF table, samplers, and harmonics, or `null` under a headless app. */\n readonly textures: LiteEnvironmentTextures | null;\n}\n\n/**\n * A loaded image-based lighting environment (`docs/architecture/07-rendering.md` §2.5).\n *\n * @example\n * ```ts\n * const studio = await app.assets.loadAsync<EnvironmentAsset>(\"environments/studio.env\");\n * world.createEntity(\"Env\").addComponent(Environment, { environment: studio.retain() });\n * ```\n *\n * @public\n */\nexport class EnvironmentAsset {\n /** The type name the asset service registers environments under. */\n static assetType: string = ENVIRONMENT_ASSET_TYPE;\n\n /** The address the environment was loaded from. */\n readonly address: string;\n\n /** What the file declared, with the defaults filled in. */\n readonly definition: EnvironmentDefinition;\n\n /** The URL Lite fetched the BRDF lookup table from, or empty when the load was headless. */\n readonly brdfUrl: string;\n\n readonly #textures: LiteEnvironmentTextures | null;\n\n /**\n * Wraps a loaded environment. The `environment` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param definition - The resolved declaration.\n * @param brdfUrl - The URL the BRDF table was fetched from.\n * @param textures - The GPU handles, or `null` when the app is headless.\n *\n * @internal\n */\n constructor(\n address: string,\n definition: EnvironmentDefinition,\n brdfUrl: string,\n textures: LiteEnvironmentTextures | null,\n ) {\n this.address = address;\n this.definition = definition;\n this.brdfUrl = brdfUrl;\n this.#textures = textures;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch.\n *\n * @returns The GPU handles, or `null` under a headless app.\n */\n get lite(): EnvironmentAssetLiteHandles {\n return { textures: this.#textures };\n }\n}\n\n/**\n * Fills in an environment declaration's defaults.\n *\n * @param overrides - The properties the file or the caller set.\n * @returns A complete declaration.\n *\n * @example\n * ```ts\n * environmentDefinition({ environment: \"environments/studio.env\", skyboxEnabled: false });\n * ```\n *\n * @public\n */\nexport function environmentDefinition(overrides: Partial<EnvironmentDefinition> = {}): EnvironmentDefinition {\n return {\n environment: overrides.environment ?? \"\",\n brdfLut: overrides.brdfLut ?? \"\",\n skybox: overrides.skybox ?? \"\",\n skyboxSize: overrides.skyboxSize ?? 20,\n skyboxEnabled: overrides.skyboxEnabled ?? true,\n blur: overrides.blur ?? 0,\n rotation: overrides.rotation ?? 0,\n };\n}\n","import {\n setSceneEnvironmentBlur,\n setSceneEnvironmentRotation,\n setSceneImageProcessingOptions,\n} from \"../../lite/gpu/environment.js\";\nimport type { ToneMappingName } from \"../../lite/gpu/environment.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\n\n/**\n * The device-only half of the `Environment` component\n * (`docs/architecture/07-rendering.md` §2.5).\n *\n * Rotating or blurring an environment writes into the prefiltered cube map's sampling state, and\n * tone mapping is compiled into the PBR shaders — neither exists without a device, which is why\n * both live under `src/render/gpu/` and are measured by the browser project rather than the Node\n * coverage floor. Fog, the clear colour, and the \"which asset is installed\" bookkeeping are plain\n * scene state and stay on the component, where Node tests reach them.\n */\n\n/**\n * Applies an environment's rotation and blur to the scene.\n *\n * @param scene - The render scene.\n * @param rotationDegrees - The rotation around world Y, in degrees.\n * @param blur - How blurred the specular reflection is, 0 to 1.\n *\n * @internal\n */\nexport function applyEnvironmentOrientation(scene: LiteScene, rotationDegrees: number, blur: number): void {\n setSceneEnvironmentRotation(scene, rotationDegrees);\n setSceneEnvironmentBlur(scene, blur);\n}\n\n/**\n * Applies exposure, contrast, and the tone-mapping curve.\n *\n * @remarks\n * Asynchronous by nature: changing the curve recompiles the scene's PBR pipelines. The caller fires\n * it and tracks the promise rather than awaiting it inside a frame.\n *\n * @param scene - The render scene.\n * @param exposure - The exposure multiplier.\n * @param contrast - The contrast multiplier.\n * @param toneMapping - The curve name.\n * @returns A promise that resolves when any affected pipeline has been rebuilt.\n *\n * @internal\n */\nexport function applySceneImageProcessing(\n scene: LiteScene,\n exposure: number,\n contrast: number,\n toneMapping: ToneMappingName,\n): Promise<void> {\n return setSceneImageProcessingOptions(scene, exposure, contrast, toneMapping);\n}\n","import { Component } from \"../component/component.js\";\nimport { setSceneFog, TONE_MAPPING_NAMES } from \"../lite/gpu/environment.js\";\nimport { Color } from \"../math/color.js\";\nimport { asset, bool, color, enumOf, f32, record } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport { EnvironmentAsset } from \"./environment-asset.js\";\nimport { applyEnvironmentOrientation, applySceneImageProcessing } from \"./gpu/environment-install.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { ComponentHooks } from \"../component/component.js\";\nimport type { FogMode, ToneMappingName, FOG_MODES } from \"../lite/gpu/environment.js\";\nimport type { ColorLike } from \"../math/types.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `Environment` component (`docs/architecture/07-rendering.md` §2.5): image based lighting, the\n * skybox, fog, image processing, and the clear colour — one per world.\n *\n * ## Why the second one wins\n *\n * Every field here is *scene* state: Lite has one `scene.fog`, one `scene.clearColor`, one\n * environment. §2.5 says \"the most recently enabled wins\" and asks for a warning on the second, so\n * the `PreRender` system picks the enabled `Environment` with the highest creation serial, logs\n * `IGX-0705` once per world while more than one is enabled, and applies only that one. Disabling\n * the winner hands the world back to the previous one on the next frame.\n *\n * ## Image processing is asynchronous, and must not block the frame\n *\n * `setSceneImageProcessing` is async because tone mapping is compiled into the PBR shaders and\n * changing it recompiles the scene's PBR pipelines (`src/lite/gpu/environment.ts`). A `PreRender`\n * system cannot await that. So the component fires the call, keeps the promise, and refuses to fire\n * a second one until the first has settled; a failure is reported through `app.onError` rather than\n * becoming an unhandled rejection (coding standards §8). The visible consequence is that a script\n * that ramps exposure every frame gets as many recompiles as the GPU can keep up with and no queue.\n *\n * ## `ambientColor` does not exist\n *\n * §2.5 lists an `ambientColor` field. Babylon Lite 1.27.0 has no scene-level ambient term:\n * `ambientColor` appears once in `index.d.ts`, on `StandardMaterialProps`, and `SceneContext`\n * declares nothing of the kind. A field that mapped onto nothing would serialise into save files\n * and quietly start mattering when the mapping appeared, so the component does not declare one. The\n * flat term a project wants from it is a hemispheric `Light`, which Lite does have.\n *\n * ## Headless\n *\n * Fog, the clear colour, and the rotation are plain scene state and are applied under the null\n * engine too. Anything that needs the cube map — the environment textures, the skybox, image\n * processing — is skipped (`07-rendering.md` §6).\n */\n\n/** The fog modes an environment can declare, in the order §2.5 lists them. */\n/**\n * The `as const` name table behind the public union of the same name.\n *\n * @public\n */\nexport const FOG_MODE_NAMES = [\"none\", \"linear\", \"exp\", \"exp2\"] as const;\n\n/**\n * The union of the fog modes.\n *\n * @public\n */\nexport type EnvironmentFogMode = (typeof FOG_MODE_NAMES)[number];\n\n/**\n * The union of the tone-mapping curves.\n *\n * @public\n */\nexport type ToneMappingCurve = (typeof TONE_MAPPING_NAMES)[number];\n\n/**\n * The `fog` record an `Environment` declares (`docs/architecture/07-rendering.md` §2.5).\n *\n * @public\n */\nexport interface EnvironmentFogSettings {\n /** The falloff, or `\"none\"` to disable fog. */\n mode: EnvironmentFogMode;\n /** The fog's sRGB colour. */\n color: ColorLike;\n /** Density, for the exponential modes. */\n density: number;\n /** Where linear fog begins, in metres. */\n start: number;\n /** Where linear fog reaches full strength, in metres. */\n end: number;\n}\n\n/**\n * The `imageProcessing` record an `Environment` declares\n * (`docs/architecture/07-rendering.md` §2.5).\n *\n * @public\n */\nexport interface ImageProcessingSettings {\n /** Exposure multiplier. */\n exposure: number;\n /** Contrast multiplier. */\n contrast: number;\n /** The tone-mapping curve. */\n toneMapping: ToneMappingCurve;\n}\n\n/**\n * The world's lighting environment (`docs/architecture/07-rendering.md` §2.5).\n *\n * @example\n * ```ts\n * const studio = await app.assets.loadAsync<EnvironmentAsset>(\"environments/studio.env\");\n * world.createEntity(\"Environment\").addComponent(Environment, {\n * environment: studio.retain(),\n * imageProcessing: { exposure: 1.2, contrast: 1, toneMapping: \"aces\" },\n * });\n * ```\n *\n * @public\n */\nexport class Environment extends Component implements ComponentHooks {\n /** The namespaced registration id. */\n static typeId = \"ignifx/Environment\";\n\n /** One per entity, and effectively one per world: the fields are all scene state. */\n static allowMultiple = false;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = environmentSchema();\n\n declare environment: AssetHandle<EnvironmentAsset> | null;\n\n declare rotation: number;\n\n declare blur: number;\n\n declare skybox: { enabled: boolean; size: number };\n\n declare fog: EnvironmentFogSettings;\n\n declare imageProcessing: ImageProcessingSettings;\n\n declare clearColor: ColorLike;\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(Environment.schema));\n }\n\n #appliedRotation = Number.NaN;\n\n #appliedBlur = Number.NaN;\n\n #appliedFog = \"\";\n\n #appliedClearColor = \"\";\n\n #appliedImageProcessing = \"\";\n\n #imageProcessingInFlight = false;\n\n #appliedEnvironment: EnvironmentAsset | null = null;\n\n /**\n * The environment asset this component installed, once it has loaded.\n *\n * @returns The asset, or `null` when none is loaded.\n */\n get installed(): EnvironmentAsset | null {\n return this.#appliedEnvironment;\n }\n\n /** Records that the component exists; the scene is written on the first sync. */\n onAttach(): void {\n this.#appliedEnvironment = null;\n }\n\n /**\n * Leaves the scene as it is.\n *\n * @remarks\n * Lite offers no \"unload environment\": `loadEnvironment` installs textures and a skybox and has\n * no inverse. Rather than pretend otherwise, removing an `Environment` leaves what it installed\n * in place until another one replaces it — which is also what \"the most recently enabled wins\"\n * implies. The `PreRender` system re-picks the winner on the next frame.\n */\n onDetach(): void {\n this.#appliedEnvironment = null;\n }\n\n /**\n * Writes every field that changed onto the scene. The `PreRender` system calls it for the winning\n * environment only.\n *\n * @param renderer - The rendering service, for the scene and the headless flag.\n *\n * @internal\n */\n sync(renderer: RendererImpl): void {\n this.#applyClearColor(renderer);\n this.#applyFog(renderer);\n this.#applyEnvironment(renderer);\n this.#applyImageProcessing(renderer);\n }\n\n /**\n * Writes the clear colour, decoded to linear.\n *\n * @remarks\n * Only when the field changed, which is what leaves the `rendering.clearColor` setting standing\n * in a world whose `Environment` never touches its own — and what keeps the main camera's\n * override, written every frame, on top of this one (`RendererImpl.applyClearColor`).\n *\n * @param renderer - The rendering service, for the scene.\n */\n #applyClearColor(renderer: RendererImpl): void {\n const key = colorKey(this.clearColor);\n if (key === this.#appliedClearColor) {\n return;\n }\n this.#appliedClearColor = key;\n renderer.applyClearColor(this.clearColor);\n }\n\n /**\n * Writes the fog record, decoded to linear.\n *\n * @param renderer - The rendering service, for the scene.\n */\n #applyFog(renderer: RendererImpl): void {\n const fog = this.fog;\n const key = `${fog.mode}|${colorKey(fog.color)}|${String(fog.density)}|${String(fog.start)}|${String(fog.end)}`;\n if (key === this.#appliedFog) {\n return;\n }\n this.#appliedFog = key;\n setSceneFog(\n renderer.scene,\n toFogMode(fog.mode),\n Color.srgbToLinear(fog.color.r),\n Color.srgbToLinear(fog.color.g),\n Color.srgbToLinear(fog.color.b),\n fog.density,\n fog.start,\n fog.end,\n );\n }\n\n /**\n * Applies the loaded environment's rotation and blur, and records which asset is installed.\n *\n * @param renderer - The rendering service, for the scene.\n */\n #applyEnvironment(renderer: RendererImpl): void {\n const loaded = this.environment?.state === \"loaded\" ? this.environment.value : null;\n if (loaded !== this.#appliedEnvironment) {\n this.#appliedEnvironment = loaded;\n this.#appliedRotation = Number.NaN;\n this.#appliedBlur = Number.NaN;\n }\n if (loaded === null || renderer.isHeadless) {\n // The rotation and the blur are properties of the installed cube map, which a headless load\n // never produced; the asset is still recorded, so `installed` answers.\n return;\n }\n if (this.#appliedRotation !== this.rotation || this.#appliedBlur !== this.blur) {\n this.#appliedRotation = this.rotation;\n this.#appliedBlur = this.blur;\n applyEnvironmentOrientation(renderer.scene, this.rotation, this.blur);\n }\n }\n\n /**\n * Fires the asynchronous image-processing update, at most one at a time.\n *\n * @param renderer - The rendering service, for the scene and the error sink.\n */\n #applyImageProcessing(renderer: RendererImpl): void {\n const settings = this.imageProcessing;\n const key = `${String(settings.exposure)}|${String(settings.contrast)}|${settings.toneMapping}`;\n if (key === this.#appliedImageProcessing || this.#imageProcessingInFlight) {\n return;\n }\n this.#appliedImageProcessing = key;\n if (renderer.isHeadless) {\n // Tone mapping is compiled into the PBR shaders; there are none without a device.\n return;\n }\n this.#imageProcessingInFlight = true;\n const curve: ToneMappingName = settings.toneMapping;\n void applySceneImageProcessing(renderer.scene, settings.exposure, settings.contrast, curve)\n .catch((error: unknown): void => {\n renderer.app.onError.emit({\n error,\n source: \"system\",\n phase: null,\n entity: this.entity,\n component: this,\n });\n })\n .finally((): void => {\n this.#imageProcessingInFlight = false;\n });\n }\n}\n\n/**\n * Maps the component's fog mode name onto the adapter's.\n *\n * @remarks\n * They differ by one name: `07-rendering.md` §2.5 spells the modes\n * `\"none\" | \"linear\" | \"exp\" | \"exp2\"`, and the adapter's table is keyed the same way\n * (`FOG_MODES`), so the mapping is the identity — stated explicitly so a rename on either side\n * fails to compile instead of silently picking mode `0`.\n *\n * @param mode - The declared mode.\n * @returns The adapter's mode name.\n */\nfunction toFogMode(mode: EnvironmentFogMode): FogMode {\n return mode satisfies keyof typeof FOG_MODES;\n}\n\n/**\n * A colour's change key.\n *\n * @param value - The colour.\n * @returns The key.\n */\nfunction colorKey(value: ColorLike): string {\n return `${String(value.r)},${String(value.g)},${String(value.b)},${String(value.a)}`;\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function, not at module scope: a schema field is a function\n * call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4).\n */\nfunction environmentSchema(): Schema {\n return defineSchema({\n environment: asset(EnvironmentAsset, { tooltip: \"The .env image-based lighting to install.\" }),\n rotation: f32(0, { tooltip: \"Rotation of the environment around world Y, in degrees.\" }),\n blur: f32(0, { min: 0, max: 1, tooltip: \"How blurred the specular reflection is.\" }),\n skybox: record(\n {\n enabled: bool(true, { tooltip: \"Whether a skybox is drawn behind the scene.\" }),\n size: f32(20, { min: 0.001, tooltip: \"The skybox cube's size, in metres.\" }),\n },\n { tooltip: \"The background the environment draws.\" },\n ),\n fog: record(\n {\n mode: enumOf(FOG_MODE_NAMES, \"none\", { tooltip: \"Fog falloff, or none.\" }),\n color: color(\"#c8c8c8\", { tooltip: \"The fog's sRGB colour.\" }),\n density: f32(0.01, { min: 0, tooltip: \"Density, for the exponential modes.\" }),\n start: f32(10, { min: 0, tooltip: \"Where linear fog begins, in metres.\" }),\n end: f32(100, { min: 0, tooltip: \"Where linear fog reaches full strength, in metres.\" }),\n },\n { tooltip: \"Distance fog.\" },\n ),\n imageProcessing: record(\n {\n exposure: f32(1, { min: 0, tooltip: \"Exposure multiplier.\" }),\n contrast: f32(1, { min: 0, tooltip: \"Contrast multiplier.\" }),\n toneMapping: enumOf(TONE_MAPPING_NAMES, \"none\", { tooltip: \"The tone-mapping curve.\" }),\n },\n { tooltip: \"Exposure, contrast, and tone mapping. Recompiles PBR pipelines when it changes.\" },\n ),\n clearColor: color(\"#000000\", { tooltip: \"The colour the scene is cleared to, in sRGB.\" }),\n });\n}\n","import {\n addToScene,\n createDirectionalLight,\n createHemisphericLight,\n createPointLight,\n createSpotLight,\n removeFromScene,\n type DirectionalLight,\n type HemisphericLight,\n type LightBase,\n type PointLight,\n type SceneContext,\n type SpotLight,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport { degToRad } from \"../math/math-utils.js\";\n\n/**\n * Light half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.2): the four Lite\n * light kinds a `Light` component can own, each of them **unparented** and posed in world space.\n *\n * Everything here is `@internal`. Colours arrive **linear**: the sRGB decode that the component's\n * `color` field performs belongs to the component layer, not to the adapter.\n *\n * ## Why an ignifx light is never parented in Lite\n *\n * A Lite light is an `IParentable` with a world matrix (`LightBase`, `index.d.ts` 6589), so\n * parenting it under the entity's node looks like the obvious mirror of what `Camera` and\n * `MeshRenderer` do. It is wrong, and the visual suite caught it:\n *\n * - Lite composes a light's world matrix as `parentWorld × localMatrixFromDirection(direction,\n * position)` (`lib/light/directional-light.js` 8-10, `lib/light/light-matrix.js`), and the shader\n * reads the **third column of that world matrix** as the light direction\n * (`lib/light/directional-light.js` 20-22 copies `w[8]`, `w[9]`, `w[10]`; the spot light also\n * takes its position from `w[12..14]`, `lib/light/spot-light.js` 28-30). Writing the entity's\n * **world** forward into `direction` while the light is **also** parented applies the entity's\n * rotation twice, so the light shades from a direction that is neither the local nor the world\n * one.\n * - The shadow frustum does not go through the world matrix at all:\n * `computeDirectionalLightMatrix` fits it from `light.direction` and `light.position` directly\n * (`lib/shadow/shadow-base.js` 54-55). A parented light therefore shades from one direction and\n * casts along another.\n *\n * One pose, written once, is the only arrangement in which shading, the lights UBO, and the shadow\n * frustum agree: the adapter creates every light with `parent = null` and the component writes the\n * entity's **world** direction and position into the light's own observables with\n * {@link syncLightWorldPose} in each frame the entity moved. With no parent, `worldMatrix` is the\n * local matrix, whose third column is exactly the direction that was written.\n *\n * ## The lights uniform buffer only follows the light's own observables\n *\n * It is re-uploaded when the summed `_lightVersion` of the scene's lights changes\n * (`lib/render/lights-ubo.js`, `refreshSceneLightsUBO`), and that counter is bumped by writes to the\n * light's **own** observable vectors (`lib/light/light-base.js`, `onDirty`). `ObservableVec3.set`\n * fires its dirty hook unconditionally (`lib/math/observable-vec3.js`), so {@link syncLightWorldPose}\n * re-marks the light as a side effect of posing it, and {@link markLightTransformDirty} is the\n * allocation-free nudge for a caller that has nothing new to write.\n *\n * ## Two more things Lite spells its own way\n *\n * - Include/exclude lists are sets of `Mesh.id` **strings**, not mesh references\n * (`lib/render/lights-ubo.js`, `affectsMesh`), and a mesh with no `id` is never excluded.\n * - Hemispheric lights spell their colours `diffuseColor`/`specularColor`, not `diffuse`/`specular`\n * (`index.d.ts` 6286) — `docs/architecture/07-rendering.md` §2.2 says \"`diffuse`/`specular`\" for\n * every type, which is wrong for this one.\n */\n\n/**\n * The Lite light kinds an ignifx `Light` component can own, re-exported under an ignifx name so\n * feature code can name the type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4,\n * coding standards §4). The barrel exports it as `LiteLight`, the name `Light.lite.light` reads by.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type AdapterLight = DirectionalLight | PointLight | SpotLight | HemisphericLight;\n\n/**\n * A light that has a range: the two punctual kinds with distance falloff.\n *\n * @internal\n */\nexport type RangedLight = PointLight | SpotLight;\n\n/**\n * Creates a directional light in world space, pointing along `+Z` until it is posed.\n *\n * @remarks\n * `parent` is left `null` on purpose; see the module note. The component poses it every frame the\n * entity moves with {@link syncLightWorldPose}.\n *\n * @param intensity - The initial intensity.\n * @returns The light. Add it to a scene with {@link addLightToScene}.\n *\n * @example\n * ```ts\n * const sun = createDirectionalLightInWorld(3);\n * syncLightWorldPose(sun, 0, -1, 0, 0, 0, 1, 0, 10, 0);\n * addLightToScene(scene, sun);\n * ```\n *\n * @internal\n */\nexport function createDirectionalLightInWorld(intensity: number): DirectionalLight {\n return createDirectionalLight([0, 0, 1], intensity);\n}\n\n/**\n * Creates a point light at the world origin.\n *\n * @param intensity - The initial intensity.\n * @returns The light.\n *\n * @internal\n */\nexport function createPointLightInWorld(intensity: number): PointLight {\n return createPointLight([0, 0, 0], intensity);\n}\n\n/**\n * Creates a spot light at the world origin pointing along `+Z`.\n *\n * @param angleDegrees - The full cone angle, in degrees.\n * @param exponent - The falloff exponent; higher is sharper.\n * @param intensity - The initial intensity.\n * @returns The light.\n *\n * @internal\n */\nexport function createSpotLightInWorld(angleDegrees: number, exponent: number, intensity: number): SpotLight {\n return createSpotLight([0, 0, 0], [0, 0, 1], degToRad(angleDegrees), exponent, intensity);\n}\n\n/**\n * Creates a hemispheric light whose sky direction is `+Y`.\n *\n * @param intensity - The initial intensity.\n * @returns The light.\n *\n * @internal\n */\nexport function createHemisphericLightInWorld(intensity: number): HemisphericLight {\n return createHemisphericLight([0, 1, 0], intensity);\n}\n\n/**\n * Poses an unparented light in **world** space: the axis it shines along and the point it shines\n * from, in the one place every consumer reads them.\n *\n * @remarks\n * The light's world matrix is its local matrix (there is no parent), so `worldMatrix[8..10]` — what\n * the shader reads as the direction — is exactly what was written to `direction`,\n * `worldMatrix[12..14]` — what a spot light reports as its position — is exactly `position`, and\n * `computeDirectionalLightMatrix` fits the shadow frustum from the same two vectors.\n *\n * Each kind is written only what it uses, and each kind reads a different axis of the entity:\n *\n * | Kind | Direction | Position |\n * | --- | --- | --- |\n * | `directional`, `spot` | the entity's world **forward** | yes |\n * | `point` | — | yes |\n * | `hemispheric` | the entity's world **up**: it is a sky direction, not a beam | — |\n *\n * Both writes fire `ObservableVec3`'s dirty hook, so the lights uniform buffer re-uploads without a\n * separate {@link markLightTransformDirty}.\n *\n * @param light - The light to pose.\n * @param forwardX - The entity's world-space forward x.\n * @param forwardY - The entity's world-space forward y.\n * @param forwardZ - The entity's world-space forward z.\n * @param upX - The entity's world-space up x.\n * @param upY - The entity's world-space up y.\n * @param upZ - The entity's world-space up z.\n * @param positionX - The entity's world-space position x.\n * @param positionY - The entity's world-space position y.\n * @param positionZ - The entity's world-space position z.\n *\n * @internal\n */\nexport function syncLightWorldPose(\n light: AdapterLight,\n forwardX: number,\n forwardY: number,\n forwardZ: number,\n upX: number,\n upY: number,\n upZ: number,\n positionX: number,\n positionY: number,\n positionZ: number,\n): void {\n switch (light.lightType) {\n case \"directional\":\n case \"spot\":\n light.direction.set(forwardX, forwardY, forwardZ);\n light.position.set(positionX, positionY, positionZ);\n break;\n case \"point\":\n light.position.set(positionX, positionY, positionZ);\n break;\n case \"hemispheric\":\n light.direction.set(upX, upY, upZ);\n break;\n default:\n assertNever(light, \"light type\");\n }\n}\n\n/**\n * Sets a light's diffuse and specular colour from one **linear** RGB triple.\n *\n * @param light - The light to colour.\n * @param r - The linear red component.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n *\n * @internal\n */\nexport function setLightColor(light: AdapterLight, r: number, g: number, b: number): void {\n switch (light.lightType) {\n case \"directional\":\n case \"point\":\n case \"spot\": {\n const diffuse = light.diffuse;\n diffuse[0] = r;\n diffuse[1] = g;\n diffuse[2] = b;\n const specular = light.specular;\n specular[0] = r;\n specular[1] = g;\n specular[2] = b;\n break;\n }\n case \"hemispheric\": {\n const diffuse = light.diffuseColor;\n diffuse[0] = r;\n diffuse[1] = g;\n diffuse[2] = b;\n const specular = light.specularColor;\n specular[0] = r;\n specular[1] = g;\n specular[2] = b;\n break;\n }\n default:\n assertNever(light, \"light type\");\n }\n markLightDirty(light);\n}\n\n/**\n * Sets the ground colour of a hemispheric light, in **linear** RGB.\n *\n * @param light - The hemispheric light.\n * @param r - The linear red component.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n *\n * @internal\n */\nexport function setHemisphericGroundColor(light: HemisphericLight, r: number, g: number, b: number): void {\n const ground = light.groundColor;\n ground[0] = r;\n ground[1] = g;\n ground[2] = b;\n markLightDirty(light);\n}\n\n/**\n * Sets a light's intensity.\n *\n * @param light - The light to change.\n * @param intensity - The new intensity.\n *\n * @internal\n */\nexport function setLightIntensity(light: AdapterLight, intensity: number): void {\n light.intensity = intensity;\n markLightDirty(light);\n}\n\n/**\n * Sets the distance at which a point or spot light's contribution reaches zero.\n *\n * @param light - The point or spot light.\n * @param range - The range, in metres.\n *\n * @internal\n */\nexport function setLightRange(light: RangedLight, range: number): void {\n light.range = range;\n markLightDirty(light);\n}\n\n/**\n * Sets a spot light's full cone angle.\n *\n * @param light - The spot light.\n * @param angleDegrees - The full cone angle, in degrees.\n *\n * @internal\n */\nexport function setSpotAngle(light: SpotLight, angleDegrees: number): void {\n light.angle = degToRad(angleDegrees);\n markLightDirty(light);\n}\n\n/**\n * Sets a spot light's falloff exponent.\n *\n * @param light - The spot light.\n * @param exponent - The exponent; higher values give a sharper edge.\n *\n * @internal\n */\nexport function setSpotExponent(light: SpotLight, exponent: number): void {\n light.exponent = exponent;\n markLightDirty(light);\n}\n\n/**\n * Restricts a light to a set of mesh ids, or lifts the restriction.\n *\n * @remarks\n * Lite matches on `Mesh.id`, a string a loader or the adapter assigns; the include list wins over\n * the exclude list when both are present (`lib/render/lights-ubo.js`, `affectsMesh`).\n *\n * @param light - The light to restrict.\n * @param meshIds - The mesh ids that may be lit, or `null` to light everything.\n *\n * @internal\n */\nexport function setLightIncludedMeshIds(light: LightBase, meshIds: ReadonlySet<string> | null): void {\n if (meshIds === null) {\n delete light.includedOnlyMeshIds;\n } else {\n light.includedOnlyMeshIds = meshIds;\n }\n}\n\n/**\n * Excludes a set of mesh ids from a light, or lifts the exclusion.\n *\n * @param light - The light to restrict.\n * @param meshIds - The mesh ids that must not be lit, or `null` to light everything.\n *\n * @internal\n */\nexport function setLightExcludedMeshIds(light: LightBase, meshIds: ReadonlySet<string> | null): void {\n if (meshIds === null) {\n delete light.excludedMeshIds;\n } else {\n light.excludedMeshIds = meshIds;\n }\n}\n\n/**\n * Tells Lite that a light's row in the lights uniform buffer is stale, without changing its pose.\n *\n * @remarks\n * Lite bumps a light's version only when the light's own `direction`/`position` are written\n * (`lib/light/light-base.js`), so anything that changes what the light contributes *without*\n * touching those vectors — a colour, an intensity, a cone angle — has to say so. This re-sets the\n * light's own vector to the value it already holds, which fires `ObservableVec3`'s dirty hook\n * unconditionally and costs no allocation. A pose change goes through {@link syncLightWorldPose}\n * instead, which marks the light as a side effect of writing it.\n *\n * @param light - The light whose uniform row is stale.\n *\n * @internal\n */\nexport function markLightTransformDirty(light: AdapterLight): void {\n markLightDirty(light);\n}\n\n/**\n * Adds a light to a render scene.\n *\n * @param scene - The render scene.\n * @param light - The light to add.\n *\n * @internal\n */\nexport function addLightToScene(scene: SceneContext, light: LightBase): void {\n addToScene(scene, light);\n}\n\n/**\n * Removes a light from a render scene, disposing its shadow generator when it has one.\n *\n * @remarks\n * `removeFromScene` also detaches the light from its parent and recursively removes its `children`\n * (`lib/scene/scene-remove.js`), which is harmless here because the adapter never puts anything in\n * a light's `children` array.\n *\n * @param scene - The render scene.\n * @param light - The light to remove.\n *\n * @internal\n */\nexport function removeLightFromScene(scene: SceneContext, light: LightBase): void {\n removeFromScene(scene, light);\n}\n\n/**\n * Bumps a light's change counter so the next frame re-uploads the lights uniform buffer.\n *\n * @param light - The light to mark.\n */\nfunction markLightDirty(light: AdapterLight): void {\n switch (light.lightType) {\n case \"directional\":\n case \"spot\":\n case \"hemispheric\": {\n const direction = light.direction;\n direction.set(direction.x, direction.y, direction.z);\n break;\n }\n case \"point\": {\n const position = light.position;\n position.set(position.x, position.y, position.z);\n break;\n }\n default:\n assertNever(light, \"light type\");\n }\n}\n","import { rebuildSceneRenderables, removeFromScene, setShadowTaskCasterMeshes } from \"@babylonjs/lite\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type {\n CsmDirectionalShadowGeneratorConfig,\n EsmDirectionalShadowGeneratorConfig,\n LightBase,\n Mesh,\n PcfDirectionalShadowGeneratorConfig,\n PcfSpotlightShadowGeneratorConfig,\n SceneContext,\n ShadowGenerator,\n} from \"@babylonjs/lite\";\n\n/**\n * Shadow half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.2): everything\n * about shadow generators that does **not** need a GPU device. Creating a generator allocates a\n * depth texture and a sampler, so the four factories live in `./gpu/shadow-generator.ts`.\n *\n * Everything here is `@internal`.\n *\n * ## How Lite renders shadows (verified against `@babylonjs/lite@1.27.0`)\n *\n * - A scene grows a shadow pass only through `registerSceneWithShadowSupport`\n * (`index.d.ts` 9542), which unshifts a task named `\"shadow\"` at the front of the frame graph\n * (`lib/scene/scene-core.js`, `ensureShadowTask`). `registerScene` never adds one, and there is\n * no public call that adds it later — so the decision is made once, at start, from whether any\n * shadow-casting light exists (`docs/architecture/07-rendering.md` §1).\n * - The shadow task finds its work by walking `scene.lights` and reading `light.shadowGenerator`\n * (`lib/frame-graph/shadow-task.js`). Assigning that property is what turns shadows on for a\n * light; `scene.shadowGenerators` is **never written** by Lite in 1.27.0 — only read by\n * device-loss recovery — so the adapter does not maintain it either.\n * - The caster list is a side table keyed by generator (`setShadowTaskCasterMeshes`,\n * `index.d.ts` 10981, `lib/frame-graph/shadow-inputs.js`). Passing a new array parks the\n * generator until an async preload of the shadow pipeline finishes, so the list is replaced as\n * rarely as possible: once per frame in which the caster set actually changed.\n * - `computeDirectionalLightMatrix` (`lib/shadow/shadow-base.js` 54-55) fits the shadow frustum\n * from the light's **own** `direction` and `position`, not from its world matrix, while the\n * shader reads the world matrix. The two only agree when the light has no parent and its own\n * vectors hold the world pose, which is what `syncLightWorldPose` in `./light.ts` writes and why\n * this adapter parents no light. Nothing extra is needed here: a posed light casts where it\n * shades.\n */\n\n/**\n * The Babylon Lite shadow generator a `Light` owns, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteShadowGenerator = ShadowGenerator;\n\n/**\n * The shadow techniques Lite offers, in the order `docs/architecture/07-rendering.md` §2.2 lists them.\n *\n * @internal\n */\nexport const SHADOW_TECHNIQUES = [\"esm\", \"pcf\", \"csm\"] as const;\n\n/**\n * The union of the shadow techniques a directional light can use.\n *\n * @internal\n */\nexport type ShadowTechnique = (typeof SHADOW_TECHNIQUES)[number];\n\n/**\n * The technique-independent shadow settings a `Light` component declares. Every field is optional;\n * Lite's own defaults apply when one is omitted.\n *\n * @internal\n */\nexport interface ShadowSettings {\n /** The technique to use. Spot lights ignore it and always use PCF, the only one Lite offers them. */\n readonly technique: ShadowTechnique;\n /** The shadow map resolution, in texels per side. Lite defaults to 1024. */\n readonly mapSize?: number;\n /** Depth bias applied while sampling, in Lite's units. */\n readonly bias?: number;\n /** Offset along the surface normal, PCF only. */\n readonly normalBias?: number;\n /** How dark a fully shadowed texel is: `0` is black, `1` is unshadowed. */\n readonly darkness?: number;\n /** Cascade count, CSM only; Lite clamps it to four. */\n readonly cascades?: number;\n /** The distance beyond which nothing is shadowed, CSM only, in metres. */\n readonly maxDistance?: number;\n}\n\n/**\n * Refuses to build a shadow generator for a light kind Lite cannot shadow.\n *\n * @remarks\n * Lite has no point-light (cube) shadow generator and no area lights\n * (`docs/architecture/07-rendering.md` §8). Hemispheric lights have no position or frustum at all.\n *\n * @param lightType - The Lite `lightType` discriminant of the light.\n * @throws IgnifxError with code `IGX-0703` for any light kind other than `directional` or `spot`.\n *\n * @example\n * ```ts\n * assertShadowsSupported(light.lightType); // throws IGX-0703 for \"point\"\n * ```\n *\n * @internal\n */\nexport function assertShadowsSupported(lightType: string): void {\n if (lightType === \"directional\" || lightType === \"spot\") {\n return;\n }\n throw new IgnifxError(\n CoreErrorCode.shadowsUnsupportedForLight,\n `Babylon Lite has no shadow generator for a ${lightType} light.`,\n {\n context: { lightType },\n hint: \"Cast shadows from a directional or spot light instead.\",\n },\n );\n}\n\n/**\n * Turns shadows on for a light by attaching its generator.\n *\n * @param light - The light that should cast shadows.\n * @param generator - A generator built for that light by `./gpu/shadow-generator.ts`.\n *\n * @internal\n */\nexport function attachShadowGenerator(light: LightBase, generator: ShadowGenerator): void {\n light.shadowGenerator = generator;\n}\n\n/**\n * Turns shadows off for a light.\n *\n * @remarks\n * This only breaks the link. The generator's GPU resources are released when the scene disposes it\n * through {@link disposeShadowGenerator}.\n *\n * @param light - The light that should stop casting shadows.\n *\n * @internal\n */\nexport function detachShadowGenerator(light: LightBase): void {\n delete light.shadowGenerator;\n}\n\n/**\n * Replaces the list of meshes a generator renders into its shadow map.\n *\n * @remarks\n * Lite keys the list by array identity and re-preloads the shadow pipeline every time a **new**\n * array arrives, skipping the generator until that finishes. Callers therefore build the list once\n * per change, never per frame.\n *\n * @param generator - The shadow generator.\n * @param casters - The meshes that cast into it.\n *\n * @internal\n */\nexport function setShadowCasters(generator: ShadowGenerator, casters: readonly Mesh[]): void {\n setShadowTaskCasterMeshes(generator, casters);\n}\n\n/**\n * Rebuilds every material group of a registered scene so renderables pick up the current light and\n * shadow topology.\n *\n * @remarks\n * Renderables bake the per-mesh light index list, the single- versus multi-light shader\n * permutation, and each generator's shadow bind group at build time; none of that follows a light\n * being added, removed, or given a generator (`index.d.ts` 9465). The call is a no-op before the\n * scene's first build, and it is expensive, so the component layer coalesces every topology change\n * in a frame into one call.\n *\n * @param scene - The scene to rebuild.\n * @returns A promise that resolves when the rebuild has finished.\n *\n * @internal\n */\nexport function rebuildRenderables(scene: SceneContext): Promise<void> {\n return rebuildSceneRenderables(scene);\n}\n\n/**\n * Releases a shadow generator's GPU resources and unlinks it from its light.\n *\n * @remarks\n * `removeFromScene` recognises a shadow generator by its private `_shadowType`/`_light` fields\n * (`lib/scene/scene-remove.js`), clears `light.shadowGenerator`, marks the scene's light topology\n * dirty, and queues the generator's task for disposal after the GPU has drained.\n *\n * @param scene - The scene the generator was rendering into.\n * @param generator - The generator to release.\n *\n * @internal\n */\nexport function disposeShadowGenerator(scene: SceneContext, generator: ShadowGenerator): void {\n removeFromScene(scene, generator);\n}\n\n/**\n * Maps the shared settings onto an exponential shadow map's configuration.\n *\n * @param settings - The declared settings.\n * @returns Lite's configuration, with every field the caller left out omitted.\n *\n * @internal\n */\nexport function toEsmConfig(settings: ShadowSettings): EsmDirectionalShadowGeneratorConfig {\n const config: { mapSize?: number; bias?: number; darkness?: number } = {};\n if (settings.mapSize !== undefined) {\n config.mapSize = settings.mapSize;\n }\n if (settings.bias !== undefined) {\n config.bias = settings.bias;\n }\n if (settings.darkness !== undefined) {\n config.darkness = settings.darkness;\n }\n return config;\n}\n\n/**\n * Maps the shared settings onto a percentage-closer-filtered directional shadow map's configuration.\n *\n * @param settings - The declared settings.\n * @returns Lite's configuration.\n *\n * @internal\n */\nexport function toPcfConfig(settings: ShadowSettings): PcfDirectionalShadowGeneratorConfig {\n const config: { mapSize?: number; bias?: number; normalBias?: number; darkness?: number } = {};\n if (settings.mapSize !== undefined) {\n config.mapSize = settings.mapSize;\n }\n if (settings.bias !== undefined) {\n config.bias = settings.bias;\n }\n if (settings.normalBias !== undefined) {\n config.normalBias = settings.normalBias;\n }\n if (settings.darkness !== undefined) {\n config.darkness = settings.darkness;\n }\n return config;\n}\n\n/**\n * Maps the shared settings onto a cascaded shadow map's configuration.\n *\n * @remarks\n * `cascades` becomes `numCascades` and `maxDistance` becomes `shadowMaxZ`; Lite clamps the cascade\n * count to four (`index.d.ts` 3515).\n *\n * @param settings - The declared settings.\n * @returns Lite's configuration.\n *\n * @internal\n */\nexport function toCsmConfig(settings: ShadowSettings): CsmDirectionalShadowGeneratorConfig {\n const config: {\n mapSize?: number;\n bias?: number;\n darkness?: number;\n numCascades?: number;\n shadowMaxZ?: number;\n } = {};\n if (settings.mapSize !== undefined) {\n config.mapSize = settings.mapSize;\n }\n if (settings.bias !== undefined) {\n config.bias = settings.bias;\n }\n if (settings.darkness !== undefined) {\n config.darkness = settings.darkness;\n }\n if (settings.cascades !== undefined) {\n config.numCascades = settings.cascades;\n }\n if (settings.maxDistance !== undefined) {\n config.shadowMaxZ = settings.maxDistance;\n }\n return config;\n}\n\n/**\n * Maps the shared settings onto a spot light's shadow configuration.\n *\n * @param settings - The declared settings.\n * @returns Lite's configuration.\n *\n * @internal\n */\nexport function toSpotConfig(settings: ShadowSettings): PcfSpotlightShadowGeneratorConfig {\n const config: { mapSize?: number; bias?: number; normalBias?: number; darkness?: number; far?: number } = {};\n if (settings.mapSize !== undefined) {\n config.mapSize = settings.mapSize;\n }\n if (settings.bias !== undefined) {\n config.bias = settings.bias;\n }\n if (settings.normalBias !== undefined) {\n config.normalBias = settings.normalBias;\n }\n if (settings.darkness !== undefined) {\n config.darkness = settings.darkness;\n }\n if (settings.maxDistance !== undefined) {\n config.far = settings.maxDistance;\n }\n return config;\n}\n","import {\n createCsmDirectionalShadowGenerator,\n createEsmDirectionalShadowGenerator,\n createPcfDirectionalShadowGenerator,\n createPcfSpotlightShadowGenerator,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../../errors/ignifx-error.js\";\nimport { toCsmConfig, toEsmConfig, toPcfConfig, toSpotConfig } from \"../shadow.js\";\nimport type { ShadowSettings, ShadowTechnique } from \"../shadow.js\";\nimport type { DirectionalLight, EngineContext, ShadowGenerator, SpotLight } from \"@babylonjs/lite\";\n\n/**\n * The four shadow-generator factories (`docs/architecture/07-rendering.md` §2.2). Each allocates a\n * depth texture and a comparison sampler through `engine._device`\n * (`lib/shadow/pcf-directional-shadow-generator.js`), so they are GPU-only. Everything a generator\n * needs afterwards — caster lists, attachment, disposal — is in `../shadow.ts`.\n *\n * Everything here is `@internal`.\n *\n * ## Which techniques exist (verified against `@babylonjs/lite@1.27.0`)\n *\n * Directional lights get ESM (`index.d.ts` 2482), PCF (2846) or CSM (2329); spot lights get PCF\n * only (2856). There is no point-light generator and no area light, which is why `../shadow.ts`\n * rejects those with `IGX-0703`. The `technique` a spot light declares is therefore ignored, not an\n * error: PCF is the only thing Lite can do for it.\n */\n\n/**\n * Builds the shadow generator a light's declared settings ask for.\n *\n * @param engine - The engine that owns the shadow map.\n * @param light - The directional or spot light that will cast.\n * @param settings - The declared technique and its tuning.\n * @returns The generator. Attach it with `attachShadowGenerator` and give it casters with\n * `setShadowCasters`, both from `../shadow.ts`.\n *\n * @example\n * ```ts\n * const generator = createShadowGeneratorForLight(engine, sun, { technique: \"pcf\", mapSize: 2048 });\n * attachShadowGenerator(sun, generator);\n * setShadowCasters(generator, casters);\n * ```\n *\n * @internal\n */\nexport function createShadowGeneratorForLight(\n engine: EngineContext,\n light: DirectionalLight | SpotLight,\n settings: ShadowSettings,\n): ShadowGenerator {\n if (light.lightType === \"spot\") {\n return createPcfSpotlightShadowGenerator(engine, light, toSpotConfig(settings));\n }\n return createDirectionalGenerator(engine, light, settings);\n}\n\n/**\n * Builds the directional generator for a technique.\n *\n * @param engine - The engine that owns the shadow map.\n * @param light - The directional light.\n * @param settings - The declared technique and its tuning.\n * @returns The generator.\n */\nfunction createDirectionalGenerator(\n engine: EngineContext,\n light: DirectionalLight,\n settings: ShadowSettings,\n): ShadowGenerator {\n const technique: ShadowTechnique = settings.technique;\n switch (technique) {\n case \"esm\":\n return createEsmDirectionalShadowGenerator(engine, light, toEsmConfig(settings));\n case \"pcf\":\n return createPcfDirectionalShadowGenerator(engine, light, toPcfConfig(settings));\n case \"csm\":\n return createCsmDirectionalShadowGenerator(engine, light, toCsmConfig(settings));\n default:\n return assertNever(technique, \"shadow technique\");\n }\n}\n","import { createShadowGeneratorForLight } from \"../../lite/gpu/shadow-generator.js\";\nimport {\n assertShadowsSupported,\n attachShadowGenerator,\n detachShadowGenerator,\n disposeShadowGenerator,\n setShadowCasters,\n} from \"../../lite/shadow.js\";\nimport type { LiteMesh } from \"../../lite/gpu/mesh.js\";\nimport type { AdapterLight } from \"../../lite/light.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { LiteShadowGenerator, ShadowSettings } from \"../../lite/shadow.js\";\nimport type { LightShadowSettings } from \"../light.js\";\n\n/**\n * The device-only half of `Light`'s shadow support\n * (`docs/architecture/07-rendering.md` §2.2).\n *\n * A shadow generator allocates a depth texture and a comparison sampler through `engine._device`\n * (`src/lite/gpu/shadow-generator.ts`), so nothing here can run under the null engine. It lives\n * under `src/render/gpu/`, which the root Vitest coverage config excludes for exactly that reason;\n * the browser project measures it. What stays on the component is the *decision* — whether shadows\n * are wanted, whether the feature is on, and the warning when it is not — which Node tests cover.\n */\n\n/**\n * Builds and attaches a shadow generator for a light.\n *\n * @param engine - The engine that owns the shadow map.\n * @param light - The light that should cast.\n * @param settings - The declared technique and its tuning.\n * @returns The generator.\n * @throws IgnifxError with code `IGX-0703` for a light kind Babylon Lite cannot shadow.\n *\n * @internal\n */\nexport function attachShadows(\n engine: LiteEngine,\n light: AdapterLight,\n settings: LightShadowSettings,\n): LiteShadowGenerator {\n assertShadowsSupported(light.lightType);\n // `assertShadowsSupported` has just established that the light is directional or spot, the two\n // kinds every generator factory accepts (coding standards §5.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const generator = createShadowGeneratorForLight(engine, light as never, toShadowSettings(settings));\n attachShadowGenerator(light, generator);\n return generator;\n}\n\n/**\n * Detaches a generator from its light and releases its GPU resources.\n *\n * @param scene - The scene the generator was rendering into.\n * @param light - The light it was attached to, or `null` when the light is already gone.\n * @param generator - The generator to release.\n *\n * @internal\n */\nexport function detachShadows(scene: LiteScene, light: AdapterLight | null, generator: LiteShadowGenerator): void {\n if (light !== null) {\n detachShadowGenerator(light);\n }\n disposeShadowGenerator(scene, generator);\n}\n\n/**\n * Replaces the meshes a generator renders into its shadow map.\n *\n * @param generator - The generator.\n * @param casters - The meshes that cast into it.\n *\n * @internal\n */\nexport function setShadowCasterMeshes(generator: LiteShadowGenerator, casters: readonly LiteMesh[]): void {\n setShadowCasters(generator, casters);\n}\n\n/**\n * Reads the component's `shadows` record as the adapter's settings shape, omitting the values that\n * mean \"take Lite's default\".\n *\n * @param declared - The component's record.\n * @returns The adapter's settings.\n */\nfunction toShadowSettings(declared: LightShadowSettings): ShadowSettings {\n const settings: {\n technique: LightShadowSettings[\"technique\"];\n mapSize?: number;\n bias?: number;\n normalBias?: number;\n darkness?: number;\n cascades?: number;\n maxDistance?: number;\n } = {\n technique: declared.technique,\n mapSize: declared.mapSize,\n bias: declared.bias,\n normalBias: declared.normalBias,\n darkness: declared.darkness,\n cascades: declared.cascades,\n };\n if (declared.maxDistance > 0) {\n settings.maxDistance = declared.maxDistance;\n }\n return settings;\n}\n","import { createGpuPicker, disposePicker, enableDetailedPicking, pickAsync } from \"@babylonjs/lite\";\nimport { readNodeTag } from \"../node.js\";\nimport type { NodeTag } from \"../node.js\";\nimport type { GpuPicker, Mesh, PickingInfo, PickOptions, SceneContext } from \"@babylonjs/lite\";\n\n/**\n * GPU picking half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §3): the\n * pixel-exact pick behind `app.renderer.pickAsync`.\n *\n * Everything here is `@internal`.\n *\n * ## How the pick runs (verified against `@babylonjs/lite@1.27.0` `lib/picking/gpu-picker.js`)\n *\n * - `createGpuPicker(scene)` allocates nothing; the 1×1 pick targets and staging buffers are created\n * on the first pick and reused, and they are re-created when the engine's device changes (after a\n * device loss).\n * - The picker draws every candidate mesh into a one-pixel target with its identity in the colour\n * attachment, then reads it back. `pickable === false` meshes and anything the `filter` predicate\n * rejects are excluded from the candidate list entirely, so they neither occlude nor return.\n * - The pixel is mapped through the camera's **pixel** viewport, and a pick outside that viewport\n * returns a miss rather than a clamped hit.\n * - **Picks are serialised per picker.** `pickAsync` chains each call onto the previous one's\n * promise — including a rejected one — because the picker owns exactly one set of staging\n * buffers. Concurrent picks are therefore correct but not concurrent; a picker per pointer is the\n * way to overlap them.\n * - A scene with no camera resolves to a miss immediately.\n */\n\n/**\n * The Babylon Lite GPU picker an app owns, re-exported under an ignifx name (coding standards §4).\n *\n * @internal\n */\nexport type LiteGpuPicker = GpuPicker;\n\n/**\n * Creates a picker for a scene.\n *\n * @param scene - The scene to pick in.\n * @returns The picker. Release it with {@link disposeScenePicker}.\n *\n * @example\n * ```ts\n * const picker = createScenePicker(scene);\n * const hit = await pickScenePixel(picker, event.offsetX, event.offsetY);\n * ```\n *\n * @internal\n */\nexport function createScenePicker(scene: SceneContext): GpuPicker {\n return createGpuPicker(scene);\n}\n\n/**\n * Picks the object under one CSS pixel of the canvas.\n *\n * @remarks\n * Coordinates are in CSS pixels relative to the canvas; Lite scales them by the backing-store ratio\n * itself. The returned info carries `pickedPoint` and `pickedNormal` only when detailed picking is\n * on ({@link enableScenePickerDetail}); without it, `pickedMesh` and `distance` are what a pick\n * yields.\n *\n * @param picker - The picker.\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param options - A mesh filter, identities to ignore, or a WGSL discard rule.\n * @returns The hit. Calls on one picker run one at a time.\n *\n * @internal\n */\nexport function pickScenePixel(picker: GpuPicker, x: number, y: number, options?: PickOptions): Promise<PickingInfo> {\n return pickAsync(picker, x, y, options);\n}\n\n/**\n * Picks the object under one CSS pixel, considering only the meshes whose ignifx tag a predicate\n * accepts.\n *\n * @remarks\n * The predicate is stated over the *tag* rather than over Lite's `Mesh` so that the component layer\n * can filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). A rejected mesh is\n * excluded from the candidate list entirely, so it neither occludes nor returns.\n *\n * @param picker - The picker.\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param accept - Decides whether a mesh may be picked, from the ignifx tag its node carries.\n * @returns The hit.\n *\n * @internal\n */\nexport function pickScenePixelWhere(\n picker: GpuPicker,\n x: number,\n y: number,\n accept: (tag: NodeTag | null) => boolean,\n): Promise<PickingInfo> {\n const options: PickOptions = { filter: (mesh: Mesh): boolean => accept(readNodeTag(mesh)) };\n return pickAsync(picker, x, y, options);\n}\n\n/**\n * Turns on triangle-exact picking, so hits carry a point, a normal, and barycentric coordinates.\n *\n * @remarks\n * It costs an extra render target and a second readback per pick, so it is opt-in: the common\n * \"which entity did I click\" question does not need it.\n *\n * @param picker - The picker to upgrade.\n *\n * @internal\n */\nexport function enableScenePickerDetail(picker: GpuPicker): void {\n enableDetailedPicking(picker);\n}\n\n/**\n * Releases a picker's GPU resources.\n *\n * @param picker - The picker to release.\n *\n * @internal\n */\nexport function disposeScenePicker(picker: GpuPicker): void {\n disposePicker(picker);\n}\n","import {\n getRenderTaskGpuTimings,\n isGpuTimingSupported,\n resizeEngine,\n setGpuTimingEnabled,\n setSurfaceSize,\n waitForGpuIdle,\n} from \"@babylonjs/lite\";\nimport type { EngineContext, RenderTaskGpuTimings, SurfaceContext } from \"@babylonjs/lite\";\n\n/**\n * The half of render diagnostics that needs a device (`docs/architecture/07-rendering.md` §1\n * and §5). The pure option mapping and the counters that are plain properties are in\n * `../render-diagnostics.ts`.\n *\n * Everything here is `@internal`.\n *\n * ## Why these need a device (verified against `@babylonjs/lite@1.27.0`)\n *\n * - `isGpuTimingSupported` and `getRenderTaskGpuTimings` both start with\n * `engine._device.features.has(\"timestamp-query\")` (`lib/engine/engine.js`,\n * `lib/engine/gpu-task-timing.js`). SwiftShader does not expose that feature, so on the CI\n * software adapter the snapshot's `status` is `\"unsupported\"` — which is why coding standards §10\n * says GPU-timing assertions are skipped there.\n * - `setSurfaceSize` writes `canvas.width`/`canvas.height` (`lib/engine/surface.js`), and a null\n * engine has no canvas at all.\n * - `resizeEngine` walks the engine's surfaces and re-reads each canvas's client size; for an\n * `OffscreenCanvas` it is a no-op, because an offscreen canvas has no layout box — that is why\n * `docs/architecture/07-rendering.md` §1 routes offscreen rendering through\n * {@link setSurfaceSizePx}.\n */\n\n/**\n * Re-reads every attached canvas's CSS size and resizes its swapchain accordingly.\n *\n * @remarks\n * Lite already does this at the start of every frame of its own render loop\n * (`lib/engine/engine.js`, `startEngine`). Calling it by hand is only needed after changing\n * `maxDevicePixelRatio` outside a frame.\n *\n * @param engine - The engine to resize.\n *\n * @internal\n */\nexport function resizeToCanvas(engine: EngineContext): void {\n resizeEngine(engine);\n}\n\n/**\n * Sets a surface's backing-store size explicitly, in device pixels.\n *\n * @remarks\n * This is the `OffscreenCanvas` path: an offscreen canvas has no layout, so the host thread that\n * owns the visible canvas pushes the size in. Every rendering context on the surface is asked to\n * rebuild its canvas-sized resources.\n *\n * On a **laid-out DOM canvas** the size set here survives exactly one frame: Lite's render loop\n * calls `resizeEngine` at the start of every frame and puts the backing store back to\n * `clientWidth × clientHeight × min(devicePixelRatio, maxDevicePixelRatio)`\n * (`lib/engine/engine.js`, `startEngine`; measured 2026-09-05). Resolution scaling on a DOM canvas\n * therefore goes through `maxDevicePixelRatio`, not through this call — which is exactly what\n * `docs/architecture/07-rendering.md` §1 prescribes.\n *\n * @param surface - The surface to resize. The engine is its own primary surface.\n * @param widthPx - The width, in device pixels.\n * @param heightPx - The height, in device pixels.\n *\n * @internal\n */\nexport function setSurfaceSizePx(surface: SurfaceContext, widthPx: number, heightPx: number): void {\n setSurfaceSize(surface, widthPx, heightPx);\n}\n\n/**\n * Clamps the device pixel ratio a surface's swapchain backing store is sized at.\n *\n * @remarks\n * `SurfaceContext.maxDevicePixelRatio` is documented as \"mutable at runtime — set before the next\n * `resizeSurface` to take effect\" (`index.d.ts` 12591), which is what makes `renderer.pixelRatio`\n * and `renderer.resolutionScale` live quality knobs rather than creation-time options\n * (`docs/architecture/07-rendering.md` §1). The caller follows it with {@link resizeToCanvas} when\n * it wants the change to land before the next frame.\n *\n * @param surface - The surface to clamp. The engine is its own primary surface.\n * @param maxDevicePixelRatio - The clamp; `Infinity` is unclamped.\n *\n * @internal\n */\nexport function setSurfaceMaxDevicePixelRatio(surface: SurfaceContext, maxDevicePixelRatio: number): void {\n surface.maxDevicePixelRatio = maxDevicePixelRatio;\n}\n\n/**\n * Reads the clamp currently in force on a surface.\n *\n * @param surface - The surface to read.\n * @returns The clamp; `Infinity` when it is unclamped.\n *\n * @internal\n */\nexport function readSurfaceMaxDevicePixelRatio(surface: SurfaceContext): number {\n return surface.maxDevicePixelRatio;\n}\n\n/**\n * Reads a surface's current backing-store size, in device pixels.\n *\n * @remarks\n * `SurfaceContext.canvas` is the `RenderCanvas` the swapchain is configured against\n * (`index.d.ts` 12591), so its `width`/`height` are the render target's pixel dimensions — which is\n * what a camera needs for its aspect ratio and for screen/world conversions. A null engine has no\n * canvas, so the component layer only calls this on a device-backed app.\n *\n * @param surface - The surface to measure. The engine is its own primary surface.\n * @param out - Receives the size.\n * @param out.width - Receives the width, in device pixels.\n * @param out.height - Receives the height, in device pixels.\n * @returns `out`, for chaining.\n *\n * @internal\n */\nexport function readSurfaceSizePx(\n surface: SurfaceContext,\n out: { width: number; height: number },\n): { width: number; height: number } {\n const canvas = surface.canvas;\n out.width = canvas.width;\n out.height = canvas.height;\n return out;\n}\n\n/**\n * Reports whether the device can measure GPU time at all.\n *\n * @param engine - The engine to probe.\n * @returns `true` when the device exposes WebGPU timestamp queries.\n *\n * @internal\n */\nexport function isGpuTimingAvailable(engine: EngineContext): boolean {\n return isGpuTimingSupported(engine);\n}\n\n/**\n * Turns whole-frame GPU timing on, so `readGpuFrameTimeMs` starts reporting.\n *\n * @remarks\n * Silently does nothing when the device has no timestamp query support. `disableGpuTiming` in\n * `../render-diagnostics.ts` is the other direction and needs no device.\n *\n * @param engine - The engine to measure.\n *\n * @internal\n */\nexport function enableGpuTiming(engine: EngineContext): void {\n setGpuTimingEnabled(engine, true);\n}\n\n/**\n * Reads the latest per-task GPU timing snapshot.\n *\n * @remarks\n * Check `status` first: `\"unsupported\"` on a device without timestamp queries, `\"disabled\"` until\n * per-task timing is switched on, `\"pending\"` until the first readback lands, `\"error\"` when the\n * readback failed. `tasks` is in frame execution order and its names are the frame graph's own —\n * `\"shadow\"`, `\"scene\"`, and whatever a post-process task was named.\n *\n * @param engine - The engine to read.\n * @returns The snapshot.\n *\n * @internal\n */\nexport function readRenderTaskGpuTimings(engine: EngineContext): RenderTaskGpuTimings {\n return getRenderTaskGpuTimings(engine);\n}\n\n/**\n * Waits until every command buffer submitted so far has finished on the GPU.\n *\n * @remarks\n * Two uses. First, it is the fence a test needs before asserting that a released resource is really\n * gone: Lite defers every teardown to `retireGpuResources`, which only runs after a frame has\n * flushed the retirement batch and the queue has drained\n * (`lib/engine/gpu-resource-retirement.js`). Second, it is the natural point to sample a benchmark\n * at, because it is the only public GPU fence Lite offers.\n *\n * @param engine - The engine to wait on.\n * @returns A promise that resolves when the queue is idle.\n *\n * @internal\n */\nexport function waitForGpuWork(engine: EngineContext): Promise<void> {\n return waitForGpuIdle(engine);\n}\n","import { captureScreenshot } from \"@babylonjs/lite\";\nimport type { CapturedFrame } from \"../screenshot.js\";\nimport type { SurfaceContext } from \"@babylonjs/lite\";\n\n/**\n * Frame capture (`docs/architecture/07-rendering.md` §5). The readers over the result are pure and\n * live in `../screenshot.ts`; taking the capture needs a running render loop, so it is here.\n *\n * Everything here is `@internal`.\n *\n * ## Timing (verified against `@babylonjs/lite@1.27.0` `lib/engine/screenshot.js`)\n *\n * `captureScreenshot(surface)` does **not** read the swapchain when it is called. It pushes a\n * pending request onto the surface and lazily loads the readback service; the request is served at\n * the end of the next rendered frame, from `renderFrame`'s command encoder\n * (`lib/engine/engine.js`). Two consequences for tests:\n *\n * 1. The promise never settles unless the engine's `requestAnimationFrame` loop is running. Under\n * the null engine, or after `stopEngine`, awaiting it hangs.\n * 2. Because the first call also has to import the readback module, the frame it lands on is not\n * necessarily the very next one. A capture therefore reflects \"a frame at or after this call\",\n * which is what a visual assertion wants anyway.\n */\n\n/**\n * Captures the surface's next presented frame.\n *\n * @param surface - The surface to capture. The engine is its own primary surface.\n * @returns The frame, as tightly packed RGBA8 with the top row first. Read it with `samplePixel`\n * from `../screenshot.ts`.\n *\n * @example\n * ```ts\n * const frame = await captureFrame(engine);\n * samplePixel(frame, frame.width >> 1, frame.height >> 1, pixel);\n * ```\n *\n * @internal\n */\nexport function captureFrame(surface: SurfaceContext): Promise<CapturedFrame> {\n return captureScreenshot(surface);\n}\n","import { addToScene, createMeshFromData, removeFromScene, setSubtreeVisible } from \"@babylonjs/lite\";\nimport type { EngineContext, Material, Mesh, SceneContext } from \"@babylonjs/lite\";\n\n/**\n * Material warm-up (`docs/architecture/07-rendering.md` §1.1, ADR-0014). Spike S2.2 measured what\n * \"warming up\" has to mean in Babylon Lite; this module is the answer.\n *\n * Everything here is `@internal`, and it needs a device.\n *\n * ## What Lite compiles, and when (verified against `@babylonjs/lite@1.27.0`)\n *\n * A scene groups its meshes by `material._buildGroup` — a **per-family singleton**, one function\n * for every PBR material in the process, one for every Standard material, one for every Shader\n * material (`lib/material/pbr/pbr-material.js`, `lib/material/standard/create-standard-material.js`,\n * `lib/material/shader/shader-material.js`). `addToScene` looks the group up, and:\n *\n * - before `registerScene`, it queues a deferred builder that `buildScene` runs, which sets the\n * group's `rebuildSingle` (`group.r`);\n * - after `registerScene`, `processMaterialSwaps` takes one of two paths\n * (`lib/scene/scene-material-swap.js`). If `group.r` exists — the family was built at\n * registration — the mesh is rebuilt **synchronously** inside the frame and draws on the next one.\n * If it does not, the mesh goes to `scene-runtime-mesh-build.js`, which dynamically imports a\n * module, runs the group builder from scratch and, for PBR, recompiles every PBR pipeline in the\n * scene (`rebuildScenePbrPipelines`). That is the multi-frame stall.\n *\n * So warming up a *material* is the wrong unit: what has to exist at `registerScene` is one mesh\n * per material **family**. That is cheap — one hidden triangle each — and it is what\n * {@link warmUpMaterials} installs. Lite has no compile or precompile API to call instead; there is\n * no public way to await the runtime build either (`scene._runtimeBuilds` is private).\n *\n * Hiding is enough: `visible` is read when a renderable is drawn, not when it is built, so a hidden\n * probe still forces its family's group builder to run.\n */\n\n/**\n * The three vertices of the probe triangle: small enough to be sub-pixel even if it were drawn. Each\n * probe gets its own copy rather than cloning a shared template, because `cloneTransformNode` is\n * typed to return a `SceneNode` and narrowing it back to a `Mesh` would need a type assertion for a\n * saving of three vertices.\n */\nconst PROBE_POSITIONS: readonly number[] = [0, 0, 0, 1e-6, 0, 0, 0, 1e-6, 0];\n\n/** One outward normal per probe vertex. */\nconst PROBE_NORMALS: readonly number[] = [0, 0, -1, 0, 0, -1, 0, 0, -1];\n\n/** The probe triangle's single face. */\nconst PROBE_INDICES: readonly number[] = [0, 1, 2];\n\n/** One UV pair per probe vertex. */\nconst PROBE_UVS: readonly number[] = [0, 0, 1, 0, 0, 1];\n\n/**\n * The hidden probes a warm-up installed, so they can be discarded later.\n *\n * @internal\n */\nexport interface MaterialWarmUp {\n /** One hidden probe per material, in the order the materials were given. */\n readonly probes: readonly Mesh[];\n}\n\n/**\n * Forces Lite to build a renderable group for every material family in `materials`, so that meshes\n * added after `registerScene` take the synchronous rebuild path instead of the runtime-build path.\n *\n * @remarks\n * Call **before** `registerRenderScene`. One probe per material is installed, which is more than\n * strictly needed — one per family would do — but it costs one degenerate triangle each, it is\n * exact about which feature combinations get compiled at registration, and it does not depend on\n * ignifx knowing how Lite partitions families.\n *\n * The probes are hidden, not removed: leaving them in the scene for the app's lifetime is the\n * intended steady state, because removing the last mesh of a family does **not** remove its group\n * from the scene, but keeping them makes that guarantee independent of Lite's internals.\n *\n * @param engine - The engine that owns the probe geometry.\n * @param scene - The scene to warm up.\n * @param materials - The materials whose families must be compiled at registration.\n * @returns The installed probes. Pass them to {@link discardMaterialWarmUp} to take them out.\n *\n * @example\n * ```ts\n * const warmUp = warmUpMaterials(engine, scene, bootMaterials);\n * await registerRenderScene(scene, { shadows });\n * // a mesh added now draws on the next frame instead of several frames later\n * ```\n *\n * @internal\n */\nexport function warmUpMaterials(\n engine: EngineContext,\n scene: SceneContext,\n materials: readonly Material[],\n): MaterialWarmUp {\n const probes: Mesh[] = [];\n for (let i = 0; i < materials.length; i++) {\n const material = materials[i];\n if (material === undefined) {\n continue;\n }\n const probe = createMeshFromData(\n engine,\n \"ignifx:warm-up\",\n Float32Array.from(PROBE_POSITIONS),\n Float32Array.from(PROBE_NORMALS),\n Uint32Array.from(PROBE_INDICES),\n Float32Array.from(PROBE_UVS),\n );\n probe.material = material;\n probe.pickable = false;\n probe.receiveShadows = false;\n setSubtreeVisible(probe, false);\n addToScene(scene, probe);\n probes.push(probe);\n }\n return { probes };\n}\n\n/**\n * Removes a warm-up's probes and releases the geometry they shared.\n *\n * @remarks\n * The material groups the probes created stay on the scene — Lite never removes a group — so\n * discarding a warm-up does not undo it. This exists so a test can prove the probes are gone, and\n * so a long-lived app can reclaim the one triangle.\n *\n * @param scene - The scene the probes were added to.\n * @param warmUp - The handle {@link warmUpMaterials} returned.\n *\n * @internal\n */\nexport function discardMaterialWarmUp(scene: SceneContext, warmUp: MaterialWarmUp): void {\n const probes = warmUp.probes;\n for (let i = 0; i < probes.length; i++) {\n const probe = probes[i];\n if (probe !== undefined) {\n removeFromScene(scene, probe);\n }\n }\n}\n","import { enableErrorDecoding, setGpuTimingEnabled } from \"@babylonjs/lite\";\nimport type { EngineContext, EngineOptions } from \"@babylonjs/lite\";\n\n/**\n * Render diagnostics and engine option mapping (`docs/architecture/07-rendering.md` §1 and §5) —\n * the half that needs no GPU device. `setSurfaceSize`, GPU timing readback, and the resize that\n * re-reads the canvas live in `./gpu/render-diagnostics-gpu.ts`.\n *\n * Everything here is `@internal`.\n *\n * ## Two corrections to `docs/architecture/07-rendering.md` §1\n *\n * 1. It lists `powerPreference` among \"engine options exposed by `createApp`\". Babylon Lite 1.27.0\n * has no such option: `EngineOptions` (`index.d.ts` 4709) and `SurfaceOptions`\n * (`index.d.ts` 12622) do not declare it, and `lib/engine/engine.js` line 47 hard-codes\n * `requestAdapter({ powerPreference: \"high-performance\" })`. The only way in is a private\n * `_adapterOptionsHook`, so ignifx does not expose the option.\n * 2. `SurfaceOptions` also carries `format`, which the document does not mention. It overrides the\n * swapchain format and must not be an `*-srgb` one — `srgb: true` is how you ask for sRGB\n * encoding.\n */\n\n/**\n * Installs Babylon Lite's own error-message decoder, so a Lite failure reports prose instead of a\n * numeric code (`docs/architecture/07-rendering.md` §5).\n *\n * @remarks\n * Development only: the decoder is a lookup table Lite would otherwise leave out of the bundle, and\n * §5 asks production builds to lazy-import `decodeError` from `app.onError` instead. The call is\n * process-global and idempotent, and it needs no device.\n *\n * @internal\n */\nexport function enableLiteErrorDecoding(): void {\n enableErrorDecoding();\n}\n\n/**\n * The renderer options `createApp` accepts, in ignifx spelling\n * (`docs/architecture/07-rendering.md` §1).\n *\n * @internal\n */\nexport interface RendererOptions {\n /** MSAA sample count for the main pass. WebGPU allows only 1 or 4; Lite defaults to 4. */\n readonly msaaSamples?: 1 | 4;\n /** The canvas alpha mode. `\"premultiplied\"` lets HTML content show through a translucent clear colour. */\n readonly alphaMode?: GPUCanvasAlphaMode;\n /** Render through an sRGB swapchain view so alpha blending is gamma-correct. */\n readonly srgb?: boolean;\n /** Clamps the device pixel ratio the swapchain is sized at. `Infinity` means native. */\n readonly pixelRatio?: number;\n /** A 0.25–1 multiplier on the resolution, implemented by lowering the effective pixel ratio. */\n readonly resolutionScale?: number;\n /** Float64 intermediate precision for world matrices, for large worlds. */\n readonly useHighPrecisionMatrix?: boolean;\n /** Eye-relative upload for large-world coordinates. Requires `useHighPrecisionMatrix`. */\n readonly useFloatingOrigin?: boolean;\n /** Extra WebGPU device limits to request, such as a larger `maxColorAttachmentBytesPerSample`. */\n readonly requiredLimits?: Record<string, GPUSize64 | undefined>;\n}\n\n/** The smallest resolution scale `docs/architecture/07-rendering.md` §1 allows. */\nconst MIN_RESOLUTION_SCALE = 0.25;\n\n/** The largest resolution scale, i.e. no downscaling. */\nconst MAX_RESOLUTION_SCALE = 1;\n\n/**\n * Translates ignifx renderer options into the `EngineOptions & SurfaceOptions` union `createEngine`\n * takes.\n *\n * @remarks\n * `pixelRatio` and `resolutionScale` collapse into Lite's single `maxDevicePixelRatio`: the scale\n * multiplies the clamp, and a clamp of `Infinity` is first resolved against the host's own device\n * pixel ratio so that scaling `Infinity` still means something. The scale is clamped to\n * 0.25 – 1 rather than rejected, because it is a live quality knob, not API misuse.\n *\n * @param options - The declared renderer options.\n * @param devicePixelRatio - The host's device pixel ratio, used only when `pixelRatio` is omitted\n * or infinite and a `resolutionScale` is present.\n * @returns Options for `createEngine`. Fields the caller left out are omitted so Lite's own\n * defaults apply.\n *\n * @example\n * ```ts\n * const engine = await createEngine(canvas, toLiteEngineOptions({ msaaSamples: 1, resolutionScale: 0.5 }, 2));\n * ```\n *\n * @internal\n */\nexport function toLiteEngineOptions(options: RendererOptions, devicePixelRatio: number): EngineOptions {\n const result: {\n msaaSamples?: 1 | 4;\n alphaMode?: GPUCanvasAlphaMode;\n srgb?: boolean;\n maxDevicePixelRatio?: number;\n useHighPrecisionMatrix?: boolean;\n useFloatingOrigin?: boolean;\n requiredLimits?: Record<string, GPUSize64 | undefined>;\n } = {};\n if (options.msaaSamples !== undefined) {\n result.msaaSamples = options.msaaSamples;\n }\n if (options.alphaMode !== undefined) {\n result.alphaMode = options.alphaMode;\n }\n if (options.srgb !== undefined) {\n result.srgb = options.srgb;\n }\n if (options.useHighPrecisionMatrix !== undefined) {\n result.useHighPrecisionMatrix = options.useHighPrecisionMatrix;\n }\n if (options.useFloatingOrigin !== undefined) {\n result.useFloatingOrigin = options.useFloatingOrigin;\n }\n if (options.requiredLimits !== undefined) {\n result.requiredLimits = options.requiredLimits;\n }\n const maxDevicePixelRatio = resolveMaxDevicePixelRatio(options, devicePixelRatio);\n if (maxDevicePixelRatio !== null) {\n result.maxDevicePixelRatio = maxDevicePixelRatio;\n }\n return result;\n}\n\n/**\n * Folds `pixelRatio` and `resolutionScale` into the one clamp Lite understands.\n *\n * @param options - The declared renderer options.\n * @param devicePixelRatio - The host's device pixel ratio.\n * @returns The clamp to pass to Lite, or `null` when the caller asked for neither.\n *\n * @internal\n */\nexport function resolveMaxDevicePixelRatio(options: RendererOptions, devicePixelRatio: number): number | null {\n const { pixelRatio, resolutionScale } = options;\n if (resolutionScale === undefined) {\n return pixelRatio ?? null;\n }\n const scale = Math.min(Math.max(resolutionScale, MIN_RESOLUTION_SCALE), MAX_RESOLUTION_SCALE);\n const base = pixelRatio === undefined || !Number.isFinite(pixelRatio) ? devicePixelRatio : pixelRatio;\n return base * scale;\n}\n\n/**\n * The number of GPU draw calls the engine issued in its last rendered frame, summed across every\n * surface.\n *\n * @param engine - The engine to read. A null engine always reports `0`.\n * @returns The draw call count.\n *\n * @internal\n */\nexport function readDrawCallCount(engine: EngineContext): number {\n return engine.drawCallCount;\n}\n\n/**\n * The GPU time the last measured frame took, in milliseconds.\n *\n * @remarks\n * `0` until GPU timing is enabled and a measured frame has completed, and the value trails the\n * current frame by one or two because the timestamp readback is asynchronous and off the render\n * critical path (`index.d.ts` 4676). Reading it therefore does not perturb it.\n *\n * @param engine - The engine to read.\n * @returns The frame time, in milliseconds.\n *\n * @internal\n */\nexport function readGpuFrameTimeMs(engine: EngineContext): number {\n return engine.gpuFrameTimeMs;\n}\n\n/**\n * Turns whole-frame GPU timing off and resets the reported frame time to zero.\n *\n * @remarks\n * Only the \"off\" direction is here: turning timing **on** probes\n * `engine._device.features.has(\"timestamp-query\")` and so needs a real device\n * (`lib/engine/engine.js`). That half lives in `./gpu/render-diagnostics-gpu.ts`.\n *\n * @param engine - The engine to stop measuring.\n *\n * @internal\n */\nexport function disableGpuTiming(engine: EngineContext): void {\n setGpuTimingEnabled(engine, false);\n}\n","import {\n enableAsyncShaderPipelineCompilation,\n enableBoneControl,\n enableGltfCameras,\n enableMaterialPlugins,\n enableMaterialStencil,\n enablePbrLightmap,\n enableStandardSkeleton,\n registerScene,\n registerSceneWithShadowSupport,\n unregisterScene,\n} from \"@babylonjs/lite\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { EngineContext, SceneContext } from \"@babylonjs/lite\";\n\n/**\n * Feature opt-ins and scene registration (`docs/architecture/07-rendering.md` §1.1). Lite compiles\n * its shader permutations and builds its frame graph at `registerScene`, so every feature that\n * changes what gets compiled has to be switched on **before** that call. ignifx therefore declares\n * the whole set up front, applies it here during `app.start()`, and rejects late toggles.\n *\n * Everything here is `@internal`.\n *\n * ## What each opt-in actually does (verified against `@babylonjs/lite@1.27.0`)\n *\n * | Call | What it installs | Device needed |\n * | --- | --- | --- |\n * | `enableStandardSkeleton()` | a Standard-pipeline skinning fragment, preloaded (`lib/material/standard/enable-standard-mesh-features.js`) | no |\n * | `enableBoneControl()` | the skeleton builder the glTF loader calls (`lib/skeleton/bone-control.js`) | no |\n * | `enableMaterialStencil()` | stencil resolvers on the PBR, Standard and Shader pipelines (`lib/material/enable-material-stencil.js`) | no |\n * | `enablePbrLightmap()` | a PBR fragment extension, loaded lazily — **async** (`lib/material/pbr/enable-pbr-lightmap.js`) | no |\n * | `enableMaterialPlugins(scene)` | plugin bridges plus one scene before-render hook (`lib/material/plugin/enable-material-plugins.js`) | no |\n * | `enableAsyncShaderPipelineCompilation(engine)` | a per-engine recipe table plus a `registerScene` hook (`lib/material/shader/enable-async-shader-pipeline-compilation.js`) | no |\n * | `enableGltfCameras()` | a glTF loader feature (`lib/loader-gltf/gltf-feature-camera.js`) | no |\n * | `postProcessing` | nothing here: it picks the scene's render path at `createSceneContext` (`./scene.ts`) | **yes** |\n * | `enableDeviceLostSceneRecovery(engine)` | reads `engine._device.features` immediately | **yes** — `./gpu/device-loss.ts` |\n *\n * Every one of them except the last is idempotent, process-global (not per engine, apart from the\n * async-pipeline table), and safe under the null engine. None of them **throws** when called late:\n * `enableMaterialStencil` simply installs its resolver, and pipelines already compiled keep the\n * behaviour they were compiled with. Lite gives no signal at all, which is exactly why ignifx has\n * to police the ordering itself with {@link assertRenderingFeatureAvailable} (`IGX-0704`).\n */\n\n/**\n * The rendering features `ignifx.config.ts` can switch on, in the order they are applied.\n *\n * @internal\n */\nexport const RENDERING_FEATURE_NAMES = [\n \"shadows\",\n \"postProcessing\",\n \"skeletons\",\n \"boneControl\",\n \"stencil\",\n \"lightmaps\",\n \"materialPlugins\",\n \"asyncPipelines\",\n \"deviceLostRecovery\",\n] as const;\n\n/**\n * The union of the rendering feature names.\n *\n * @internal\n */\nexport type RenderingFeatureName = (typeof RENDERING_FEATURE_NAMES)[number];\n\n/**\n * The rendering feature block of `createApp`/`ignifx.config.ts`\n * (`docs/architecture/07-rendering.md` §1.1).\n *\n * @internal\n */\nexport type RenderingFeatures = {\n readonly [Name in RenderingFeatureName]: boolean;\n};\n\n/**\n * Every feature off — the state an app that declares no `rendering.features` block starts from.\n *\n * @internal\n */\nexport const NO_RENDERING_FEATURES: RenderingFeatures = {\n shadows: false,\n postProcessing: false,\n skeletons: false,\n boneControl: false,\n stencil: false,\n lightmaps: false,\n materialPlugins: false,\n asyncPipelines: false,\n deviceLostRecovery: false,\n};\n\n/**\n * Applies the process- and scene-global feature opt-ins a world declared, before its scene is\n * registered.\n *\n * @remarks\n * Three features are deliberately **not** applied here. `shadows` chooses between `registerScene`\n * and `registerSceneWithShadowSupport` in {@link registerRenderScene}. `postProcessing` is decided\n * even earlier — at `createSceneContext`, which is where `defaultRenderTask: false` has to be said\n * (`./scene.ts`), because Lite exposes no way to retarget the default render task afterwards.\n * `deviceLostRecovery` needs a real device, so `app.start()` calls `enableSceneDeviceLossRecovery`\n * from `./gpu/device-loss.ts` before it creates any resource.\n *\n * @param engine - The engine the world renders on.\n * @param scene - The world's render scene.\n * @param features - The declared feature block.\n * @returns A promise that resolves when every opt-in — including the lazily loaded lightmap\n * extension — is installed.\n *\n * @example\n * ```ts\n * await applyRenderingFeatures(engine, scene, { ...NO_RENDERING_FEATURES, shadows: true, skeletons: true });\n * await registerRenderScene(scene, { shadows: true });\n * ```\n *\n * @internal\n */\nexport async function applyRenderingFeatures(\n engine: EngineContext,\n scene: SceneContext,\n features: RenderingFeatures,\n): Promise<void> {\n if (features.skeletons) {\n enableStandardSkeleton();\n }\n if (features.boneControl) {\n enableBoneControl();\n }\n if (features.stencil) {\n enableMaterialStencil();\n }\n if (features.materialPlugins) {\n enableMaterialPlugins(scene);\n }\n if (features.asyncPipelines) {\n enableAsyncShaderPipelineCompilation(engine);\n }\n if (features.lightmaps) {\n await enablePbrLightmap();\n }\n}\n\n/**\n * Enables glTF camera import. Must run before the first `loadGltf`.\n *\n * @remarks\n * Separate from {@link applyRenderingFeatures} because it is an **asset** opt-in, driven by an\n * asset's `.meta.json` rather than by the renderer block\n * (`docs/architecture/07-rendering.md` §2.4).\n *\n * @internal\n */\nexport function enableGltfCameraImport(): void {\n enableGltfCameras();\n}\n\n/**\n * Registers a world's render scene with Lite, picking the shadow-capable entry point when the\n * world declared shadows.\n *\n * @remarks\n * `registerSceneWithShadowSupport` unshifts a task named `\"shadow\"` at the front of the frame graph\n * (`lib/scene/scene-core.js`, `ensureShadowTask`); `registerScene` never does, and nothing public\n * adds one afterwards. Registering the same scene twice is a no-op — Lite checks whether the scene\n * is already a rendering context of its surface.\n *\n * @param scene - The scene to register.\n * @param options - Registration options.\n * @param options.shadows - Whether any shadow-casting light exists at start.\n * @returns A promise that resolves when the scene's material groups are built, its pipelines are\n * compiled, and its frame graph is recorded.\n *\n * @internal\n */\nexport function registerRenderScene(scene: SceneContext, options: { readonly shadows: boolean }): Promise<void> {\n return options.shadows ? registerSceneWithShadowSupport(scene) : registerScene(scene);\n}\n\n/**\n * Detaches a scene from its surface so the engine stops rendering it, without disposing it.\n *\n * @remarks\n * This is the first half of Lite's documented \"change the light topology\" flow:\n * `unregisterRenderScene` → mutate lights → {@link registerRenderScene} again, which re-runs the\n * group builders (`index.d.ts` 9465).\n *\n * @param scene - The scene to detach.\n *\n * @internal\n */\nexport function unregisterRenderScene(scene: SceneContext): void {\n unregisterScene(scene);\n}\n\n/**\n * Refuses a rendering feature toggle that arrives after the scene was registered.\n *\n * @param feature - The feature being toggled.\n * @param isSceneRegistered - Whether `app.start()` has already registered the render scene.\n * @throws IgnifxError with code `IGX-0704` when the scene is already registered.\n *\n * @example\n * ```ts\n * assertRenderingFeatureAvailable(\"stencil\", app.isStarted); // throws IGX-0704 after start\n * ```\n *\n * @internal\n */\nexport function assertRenderingFeatureAvailable(feature: RenderingFeatureName, isSceneRegistered: boolean): void {\n if (!isSceneRegistered) {\n return;\n }\n throw new IgnifxError(\n CoreErrorCode.renderingFeatureTooLate,\n `The rendering feature ${feature} must be enabled before the scene is registered.`,\n {\n context: { feature },\n hint: \"Declare it in the rendering.features block of createApp() or ignifx.config.ts.\",\n },\n );\n}\n","import {\n createNullEngine,\n createSceneContext,\n disposeScene,\n type EngineContext,\n type SceneContext,\n} from \"@babylonjs/lite\";\n\n/**\n * Scene-construction half of the Babylon Lite adapter: the engine/scene pairs a world is built on\n * (`docs/architecture/00-overview.md` §3, ADR-0003). Everything here is `@internal`; the kernel's\n * `World` owns these objects and exposes them only through its documented `.lite` escape hatch.\n *\n * A world needs up to two Lite scenes: the render scene (a default render task, driven by\n * `startRenderLoop`) and, when physics is registered, a null-engine simulation scene stepped by\n * ignifx's own fixed-timestep loop. {@link createHeadlessScene} builds the second one in every mode\n * and the first one too when the app is headless.\n */\n\n/**\n * A GPU-free engine and scene pair.\n *\n * @internal\n */\nexport interface HeadlessScene {\n /** The Lite null engine. It is its own surface. */\n readonly engine: EngineContext;\n /** A scene with no default render task, advanced with `runFrame`. */\n readonly scene: SceneContext;\n}\n\n/**\n * Creates a null engine and a scene with no default render task — the pair every unit test, server,\n * and physics simulation scene runs on (`CONSTITUTION.md` §3.8).\n *\n * @returns The engine and scene. Release the scene with {@link disposeSceneOnly}.\n *\n * @example\n * ```ts\n * const { engine, scene } = createHeadlessScene();\n * runFrame(engine, scene, 1 / 60);\n * disposeSceneOnly(scene);\n * ```\n *\n * @internal\n */\nexport function createHeadlessScene(): HeadlessScene {\n const engine = createNullEngine();\n return { engine, scene: createSceneContext(engine, { defaultRenderTask: false }) };\n}\n\n/**\n * Creates the scene a world actually draws, with or without Lite's default render task.\n *\n * @remarks\n * The engine comes from `createRenderEngine` in `./render.ts`; this module deliberately does not\n * create engines, so the WebGPU capability probe stays in one place.\n *\n * `defaultRenderTask` is the one thing about a scene that cannot be changed afterwards: the task is\n * built inside `createSceneContext` with its render target baked in, and Lite exposes no handle to\n * it (`./gpu/render-path.ts`). A project that declares `rendering.features.postProcessing` gets no\n * default task and `installOffscreenRenderPath` builds the replacement.\n *\n * @param engine - A WebGPU engine.\n * @param options - Scene options.\n * @param options.offscreen - `true` to omit the default render task, for the offscreen path.\n * @returns The scene. Register it and start the loop with `startRenderLoop`.\n *\n * @internal\n */\nexport function createRenderScene(engine: EngineContext, options?: { readonly offscreen?: boolean }): SceneContext {\n return createSceneContext(engine, { defaultRenderTask: options?.offscreen !== true });\n}\n\n/**\n * How many lights a scene currently holds.\n *\n * @remarks\n * `SceneContext.lights` is a plain array Lite appends to in `addToScene`, so reading its length\n * needs no device. The renderer consults it before installing warm-up probes: a probe registered\n * into a scene with **no** lights leaves every later mesh of that family undrawn (measured on\n * SwiftShader 2026-09-05; see `test/render/warm-up.browser.test.ts`).\n *\n * @param scene - The scene to read.\n * @returns The light count.\n *\n * @internal\n */\nexport function sceneLightCount(scene: SceneContext): number {\n return scene.lights.length;\n}\n\n/**\n * Releases a scene's resources without touching its engine.\n *\n * @remarks\n * Disposing only the scene is deliberate and, for a null engine, complete. Verified against\n * `@babylonjs/lite@1.27.0` (ADR-0009 Validation): `createNullEngine()` returns an engine that is its\n * own surface but owns no `_context` and no `_device`, while `disposeEngine()` unconditionally\n * calls `surface._context.unconfigure()` and `engine._device.destroy()` — so calling it on a null\n * engine throws. A null engine holds no GPU resources, so there is nothing else to release. A\n * WebGPU engine is disposed through `disposeRenderEngine` in `./render.ts` instead, after its\n * scenes.\n *\n * @param scene - The scene to release.\n *\n * @internal\n */\nexport function disposeSceneOnly(scene: SceneContext): void {\n disposeScene(scene);\n}\n\n/**\n * The Babylon Lite engine handle an ignifx app owns, re-exported under an ignifx name so that\n * feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches, and it\n * is excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteEngine = EngineContext;\n\n/**\n * The Babylon Lite scene a world renders into (or simulates on), re-exported under an ignifx name\n * for the same reason as {@link LiteEngine}.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteScene = SceneContext;\n","import { createScenePicker, pickScenePixel, pickScenePixelWhere } from \"../../lite/gpu/picker.js\";\nimport {\n enableGpuTiming,\n readRenderTaskGpuTimings,\n readSurfaceSizePx,\n resizeToCanvas,\n setSurfaceMaxDevicePixelRatio,\n} from \"../../lite/gpu/render-diagnostics-gpu.js\";\nimport { warmUpMaterials } from \"../../lite/gpu/warm-up.js\";\nimport type { LiteGpuPicker } from \"../../lite/gpu/picker.js\";\nimport type { MaterialWarmUp } from \"../../lite/gpu/warm-up.js\";\nimport type { NodeTag } from \"../../lite/node.js\";\nimport type { LitePickInfo } from \"../../lite/picking.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { MaterialAsset } from \"../material-asset.js\";\nimport type { RenderTaskTiming, RenderTaskTimings } from \"../renderer.js\";\n\n/**\n * The device-only half of `app.renderer` (`docs/architecture/07-rendering.md` §1, §3, §5).\n *\n * Everything here fails or answers nothing under the null engine — a picker needs a device and a\n * rendered frame, a warm-up probe needs vertex buffers, GPU timing needs `timestamp-query`, and a\n * surface's backing store needs a canvas — so it lives under `src/render/gpu/`, which the root\n * Vitest coverage config excludes for the same reason it excludes `src/lite/gpu/`. `RendererImpl`\n * keeps every headless guard, and the browser project measures these lines.\n */\n\n/**\n * Creates the app's one GPU picker.\n *\n * @param scene - The scene to pick in.\n * @returns The picker.\n *\n * @internal\n */\nexport function createPicker(scene: LiteScene): LiteGpuPicker {\n return createScenePicker(scene);\n}\n\n/**\n * Picks the object under one CSS pixel, optionally restricted to the meshes a predicate accepts.\n *\n * @param picker - The app's picker.\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param accept - The tag predicate, or `null` to consider every mesh.\n * @returns Lite's picking info.\n *\n * @internal\n */\nexport function pickPixel(\n picker: LiteGpuPicker,\n x: number,\n y: number,\n accept: ((tag: NodeTag | null) => boolean) | null,\n): Promise<LitePickInfo> {\n return accept === null ? pickScenePixel(picker, x, y) : pickScenePixelWhere(picker, x, y, accept);\n}\n\n/**\n * Installs one hidden probe per material so their families are compiled at `registerScene`\n * (ADR-0014).\n *\n * @param engine - The engine that owns the probe geometry.\n * @param scene - The scene to warm up.\n * @param materials - The materials whose families must be compiled.\n * @returns The installed probes.\n *\n * @internal\n */\nexport function warmUpMaterialAssets(\n engine: LiteEngine,\n scene: LiteScene,\n materials: readonly MaterialAsset[],\n): MaterialWarmUp {\n const lite = [];\n for (let index = 0; index < materials.length; index += 1) {\n const material = materials[index];\n if (material !== undefined) {\n lite.push(material.lite.material);\n }\n }\n return warmUpMaterials(engine, scene, lite);\n}\n\n/**\n * Writes the effective device pixel ratio clamp onto the surface and resizes it.\n *\n * @param engine - The engine, which is its own primary surface.\n * @param maxDevicePixelRatio - The clamp to apply.\n *\n * @internal\n */\nexport function applySurfaceScale(engine: LiteEngine, maxDevicePixelRatio: number): void {\n setSurfaceMaxDevicePixelRatio(engine, maxDevicePixelRatio);\n resizeToCanvas(engine);\n}\n\n/**\n * Reads the render target's current size in device pixels, without allocating.\n *\n * @param engine - The engine, which is its own primary surface.\n * @param out - Receives the size.\n *\n * @param out.width - Receives the width, in device pixels.\n * @param out.height - Receives the height, in device pixels.\n * @internal\n */\nexport function readTargetSizePx(engine: LiteEngine, out: { width: number; height: number }): void {\n readSurfaceSizePx(engine, out);\n}\n\n/**\n * Turns whole-frame GPU timing on.\n *\n * @param engine - The engine to measure.\n *\n * @internal\n */\nexport function startGpuTiming(engine: LiteEngine): void {\n enableGpuTiming(engine);\n}\n\n/**\n * Reads the latest per-task GPU timing snapshot, in ignifx's own shape.\n *\n * @param engine - The engine to read.\n * @returns The snapshot.\n *\n * @internal\n */\nexport function readTaskTimings(engine: LiteEngine): RenderTaskTimings {\n const snapshot = readRenderTaskGpuTimings(engine);\n const tasks: RenderTaskTiming[] = [];\n const measured = snapshot.tasks;\n for (let index = 0; index < measured.length; index += 1) {\n const task = measured[index];\n if (task !== undefined) {\n tasks.push({ name: task.name, durationMs: task.durationMs });\n }\n }\n return { status: snapshot.status, tasks };\n}\n","import {\n createPbrMaterial,\n createShaderMaterial,\n createStandardMaterial,\n enableMaterialTracking,\n markMaterialUboDirty,\n rebuildMaterial,\n setPbrAlphaCutoff,\n setPbrEmissive,\n setPbrUnlit,\n setStandardBumpTexture,\n setStandardEmissiveTexture,\n setStandardOpacityTexture,\n setStandardSpecularTexture,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport type {\n Material,\n PbrMaterialProps,\n SceneContext,\n ShaderMaterial,\n ShaderMaterialOptions,\n StandardMaterialProps,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * Material half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.6): the three\n * material kinds a `MaterialAsset` can produce, built from plain ignifx props.\n *\n * Everything here is `@internal`, and every colour that reaches it is **linear** — the sRGB decode\n * belongs to the asset layer.\n *\n * ## What a Lite material is (verified against `@babylonjs/lite@1.27.0`)\n *\n * - A material is plain data plus one private `_buildGroup` function; `createPbrMaterial` is\n * literally `{ ...props, _buildGroup, _uboVersion: 0 }` (`lib/material/pbr/pbr-material.js`), so\n * none of these factories touches the GPU and all of them run under the null engine.\n * - **The build group is a per-family singleton.** `getPbrGroupBuilder()`, `getStandardGroupBuilder()`\n * and `getShaderGroupBuilder()` each memoise one function for the whole process\n * (`lib/material/pbr/pbr-material.js`, `lib/material/standard/create-standard-material.js`,\n * `lib/material/shader/shader-material.js` line 123), and a scene keys its renderable groups by\n * that function (`lib/scene/scene-core.js`, `addToScene`). \"Material family\" in\n * `docs/architecture/07-rendering.md` §1.1 therefore means *pbr*, *standard*, *shader* or *node* —\n * **not** an individual material. Only node materials get a per-material builder\n * (`lib/material/node/node-material.js`). This is what makes {@link warmUpMaterialFamilies} in\n * `./gpu/warm-up.ts` cheap: one hidden mesh per family covers every material in it.\n * - Scalar and vector edits only need `markMaterialUboDirty` (`index.d.ts` 6974), which bumps\n * `_uboVersion`. Anything that changes the compiled feature set — binding or clearing a texture,\n * flipping `doubleSided`, changing culling — needs {@link rebuildMaterialPipelines}.\n */\n\n/**\n * The Babylon Lite material a `MaterialAsset` owns, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMaterial = Material;\n\n/**\n * A Babylon Lite physically based material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LitePbrMaterial = PbrMaterialProps;\n\n/**\n * A Babylon Lite Babylon-Standard material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteStandardMaterial = StandardMaterialProps;\n\n/** glTF's default alpha cutoff, used when a `\"mask\"` material declares none. */\nconst DEFAULT_ALPHA_CUTOFF = 0.5;\n\n/**\n * How a material's alpha channel is interpreted, in glTF's vocabulary.\n *\n * @internal\n */\nexport const MATERIAL_ALPHA_MODES = [\"opaque\", \"mask\", \"blend\"] as const;\n\n/**\n * The union of the alpha modes a material can declare.\n *\n * @internal\n */\nexport type MaterialAlphaMode = (typeof MATERIAL_ALPHA_MODES)[number];\n\n/**\n * The physically based material properties an ignifx `.material.json` declares\n * (`docs/architecture/06-serialization-and-scene-format.md` §6). Every field is optional; an\n * omitted field leaves Lite's own default in place.\n *\n * @internal\n */\nexport interface PbrMaterialInput {\n /** A human-readable name, used for glTF material overrides and diagnostics. */\n readonly name?: string;\n /** Linear base colour and alpha, multiplied with the base colour texture. */\n readonly baseColor?: readonly [number, number, number, number];\n /** The base colour texture. Load it with an sRGB format. */\n readonly baseColorTexture?: Texture2D;\n /** Metallic factor, 0 to 1. */\n readonly metallic?: number;\n /** Roughness factor, 0 to 1. */\n readonly roughness?: number;\n /** The packed occlusion/roughness/metallic texture (glTF `ORM`). */\n readonly metallicRoughnessTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** Normal map strength. */\n readonly normalScale?: number;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** A separate occlusion texture, sampled on UV1 when the ORM texture is not used for it. */\n readonly occlusionTexture?: Texture2D;\n /** How strongly ambient occlusion darkens the surface, 0 to 1. */\n readonly occlusionStrength?: number;\n /** How the alpha channel is interpreted. */\n readonly alphaMode?: MaterialAlphaMode;\n /** The cutoff below which a `\"mask\"` material discards a fragment. */\n readonly alphaCutoff?: number;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n /** How strongly the environment map contributes. */\n readonly environmentIntensity?: number;\n}\n\n/**\n * The Babylon-Standard material properties an ignifx `.material.json` declares, for the cheap\n * non-PBR path (`docs/architecture/07-rendering.md` §2.6).\n *\n * @internal\n */\nexport interface StandardMaterialInput {\n /** A human-readable name. */\n readonly name?: string;\n /** Linear diffuse colour. */\n readonly diffuse?: readonly [number, number, number];\n /** The diffuse texture. */\n readonly diffuseTexture?: Texture2D;\n /** Linear specular colour. */\n readonly specular?: readonly [number, number, number];\n /** Specular exponent; higher values give a tighter highlight. */\n readonly specularPower?: number;\n /** The specular texture. */\n readonly specularTexture?: Texture2D;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** The opacity texture. */\n readonly opacityTexture?: Texture2D;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** The cutoff below which a fragment is discarded. `0` disables the alpha test. */\n readonly alphaCutoff?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n}\n\n/**\n * Builds a Lite PBR material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material. It holds no GPU resource of its own; the textures it references do.\n *\n * @example\n * ```ts\n * const gold = createPbrMaterialFromProps({ baseColor: [1, 0.77, 0.34, 1], metallic: 1, roughness: 0.25 });\n * ```\n *\n * @internal\n */\nexport function createPbrMaterialFromProps(input: PbrMaterialInput): PbrMaterialProps {\n const props: Partial<PbrMaterialProps> = {};\n if (input.name !== undefined) {\n props.name = input.name;\n }\n if (input.baseColor !== undefined) {\n props.baseColorFactor = [input.baseColor[0], input.baseColor[1], input.baseColor[2], input.baseColor[3]];\n }\n if (input.baseColorTexture !== undefined) {\n props.baseColorTexture = input.baseColorTexture;\n }\n if (input.metallic !== undefined) {\n props.metallicFactor = input.metallic;\n }\n if (input.roughness !== undefined) {\n props.roughnessFactor = input.roughness;\n }\n if (input.metallicRoughnessTexture !== undefined) {\n props.ormTexture = input.metallicRoughnessTexture;\n }\n if (input.normalTexture !== undefined) {\n props.normalTexture = input.normalTexture;\n }\n if (input.normalScale !== undefined) {\n props.normalTextureScale = input.normalScale;\n }\n if (input.emissiveTexture !== undefined) {\n props.emissiveTexture = input.emissiveTexture;\n }\n if (input.occlusionTexture !== undefined) {\n props.occlusionTexture = input.occlusionTexture;\n }\n if (input.occlusionStrength !== undefined) {\n props.occlusionStrength = input.occlusionStrength;\n }\n if (input.alpha !== undefined) {\n props.alpha = input.alpha;\n }\n if (input.doubleSided !== undefined) {\n props.doubleSided = input.doubleSided;\n }\n if (input.environmentIntensity !== undefined) {\n props.environmentIntensity = input.environmentIntensity;\n }\n if (input.alphaMode === \"blend\") {\n props.alphaBlend = true;\n }\n const material = createPbrMaterial(props);\n if (input.alphaMode === \"mask\") {\n setPbrAlphaCutoff(material, input.alphaCutoff ?? DEFAULT_ALPHA_CUTOFF);\n }\n if (input.emissive !== undefined) {\n setPbrEmissive(material, [input.emissive[0], input.emissive[1], input.emissive[2]]);\n }\n if (input.unlit === true) {\n setPbrUnlit(material);\n }\n return material;\n}\n\n/**\n * Builds a Lite Standard material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material.\n *\n * @internal\n */\nexport function createStandardMaterialFromProps(input: StandardMaterialInput): StandardMaterialProps {\n const material = createStandardMaterial();\n if (input.name !== undefined) {\n material.name = input.name;\n }\n if (input.diffuse !== undefined) {\n writeTriple(material.diffuseColor, input.diffuse);\n }\n if (input.specular !== undefined) {\n writeTriple(material.specularColor, input.specular);\n }\n if (input.emissive !== undefined) {\n writeTriple(material.emissiveColor, input.emissive);\n }\n if (input.specularPower !== undefined) {\n material.specularPower = input.specularPower;\n }\n if (input.alpha !== undefined) {\n material.alpha = input.alpha;\n }\n if (input.alphaCutoff !== undefined) {\n material.alphaCutOff = input.alphaCutoff;\n }\n if (input.doubleSided !== undefined) {\n material.backFaceCulling = !input.doubleSided;\n }\n if (input.unlit !== undefined) {\n material.disableLighting = input.unlit;\n }\n if (input.diffuseTexture !== undefined) {\n material.diffuseTexture = input.diffuseTexture;\n }\n if (input.specularTexture !== undefined) {\n setStandardSpecularTexture(material, input.specularTexture);\n }\n if (input.emissiveTexture !== undefined) {\n setStandardEmissiveTexture(material, input.emissiveTexture);\n }\n if (input.normalTexture !== undefined) {\n setStandardBumpTexture(material, input.normalTexture);\n }\n if (input.opacityTexture !== undefined) {\n setStandardOpacityTexture(material, input.opacityTexture);\n }\n return material;\n}\n\n/**\n * Builds a custom WGSL material.\n *\n * @remarks\n * Lite validates the declaration eagerly — a missing `position` attribute, a duplicate uniform\n * name, or an empty source throws immediately (`lib/material/shader/shader-material.js`) — but\n * compiles nothing until the material is first drawn, so this is safe under the null engine.\n *\n * @param options - The WGSL sources and the declared attribute, uniform, and sampler layout.\n * @returns The material.\n *\n * @internal\n */\nexport function createWgslMaterial(options: ShaderMaterialOptions): ShaderMaterial {\n return createShaderMaterial(options);\n}\n\n/**\n * The material a `MeshRenderer` uses when it declares none: a neutral, fully rough dielectric.\n *\n * @returns A fresh material. Callers share one instance per app rather than one per renderer.\n *\n * @internal\n */\nexport function createDefaultMaterial(): PbrMaterialProps {\n return createPbrMaterialFromProps({\n name: \"ignifx:default\",\n baseColor: [1, 1, 1, 1],\n metallic: 0,\n roughness: 0.9,\n });\n}\n\n/**\n * Replaces a PBR material's linear base colour.\n *\n * @param material - The material to change.\n * @param r - The linear red component.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n * @param a - The alpha component.\n *\n * @internal\n */\nexport function setPbrBaseColor(material: PbrMaterialProps, r: number, g: number, b: number, a: number): void {\n const factor = material.baseColorFactor;\n if (factor === undefined) {\n material.baseColorFactor = [r, g, b, a];\n } else {\n factor[0] = r;\n factor[1] = g;\n factor[2] = b;\n factor[3] = a;\n }\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a PBR material's metallic and roughness factors.\n *\n * @param material - The material to change.\n * @param metallic - The metallic factor, 0 to 1.\n * @param roughness - The roughness factor, 0 to 1.\n *\n * @internal\n */\nexport function setPbrMetallicRoughness(material: PbrMaterialProps, metallic: number, roughness: number): void {\n material.metallicFactor = metallic;\n material.roughnessFactor = roughness;\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a material's overall alpha.\n *\n * @param material - The PBR or Standard material to change.\n * @param alpha - The new alpha, 0 to 1.\n *\n * @internal\n */\nexport function setMaterialAlpha(material: PbrMaterialProps | StandardMaterialProps, alpha: number): void {\n material.alpha = alpha;\n markMaterialDirty(material);\n}\n\n/**\n * Marks a material's uniform block for re-upload on the next frame.\n *\n * @remarks\n * This is the cheap path and covers every scalar, vector, and colour edit. It does **not** cover\n * changes that alter the compiled feature set; those go through {@link rebuildMaterialPipelines}.\n *\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function markMaterialDirty(material: Material): void {\n markMaterialUboDirty(material);\n}\n\n/**\n * Rebuilds the renderables of a material whose compiled feature set changed.\n *\n * @remarks\n * Needed after binding or clearing a texture, changing culling, or toggling a sub-feature\n * (`index.d.ts` 9413). `rebuildFrameGraph` is left off so a component can batch several material\n * edits and rebuild the frame graph once.\n *\n * @param scene - The scene the material renders in.\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function rebuildMaterialPipelines(scene: SceneContext, material: Material): void {\n rebuildMaterial(scene, material);\n}\n\n/**\n * Installs automatic dirty tracking on a material, so property writes mark its uniform block\n * without an explicit {@link markMaterialDirty}.\n *\n * @remarks\n * Lite installs the tracker by rewriting the material's property descriptors, and the module that\n * does it is loaded lazily, so this is asynchronous (`index.d.ts` 4480,\n * `lib/material/observable-material.js`). Opt-in only: it costs an accessor call per write, which\n * the zero-allocation rules (coding standards §7) do not want on every material.\n *\n * @param material - The PBR or Standard material to track.\n * @returns A promise that resolves once the tracker is installed.\n *\n * @internal\n */\nexport function enableMaterialChangeTracking(material: PbrMaterialProps | StandardMaterialProps): Promise<void> {\n return enableMaterialTracking(material);\n}\n\n/**\n * Reports whether Lite will alpha-blend a material declared with this alpha mode.\n *\n * @param mode - The declared alpha mode.\n * @returns `true` for `\"blend\"`, `false` for `\"opaque\"` and `\"mask\"`.\n *\n * @internal\n */\nexport function isBlendedAlphaMode(mode: MaterialAlphaMode): boolean {\n switch (mode) {\n case \"opaque\":\n case \"mask\":\n return false;\n case \"blend\":\n return true;\n default:\n return assertNever(mode, \"material alpha mode\");\n }\n}\n\n/**\n * Writes three components into a Lite colour tuple in place.\n *\n * @param target - The tuple Lite owns.\n * @param source - The values to copy.\n */\nfunction writeTriple(target: [number, number, number], source: readonly [number, number, number]): void {\n target[0] = source[0];\n target[1] = source[1];\n target[2] = source[2];\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n createDefaultMaterial,\n createPbrMaterialFromProps,\n createStandardMaterialFromProps,\n markMaterialDirty,\n MATERIAL_ALPHA_MODES,\n setMaterialAlpha,\n setPbrBaseColor,\n setPbrMetallicRoughness,\n} from \"../lite/material.js\";\nimport { Color } from \"../math/color.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { LiteTexture2D } from \"../lite/gpu/texture.js\";\nimport type { LiteMaterial, LitePbrMaterial, LiteStandardMaterial, MaterialAlphaMode } from \"../lite/material.js\";\nimport type { ColorLike } from \"../math/types.js\";\n\n/**\n * `MaterialAsset` and the `ignifx.material` file format\n * (`docs/architecture/07-rendering.md` §2.6, `06-serialization-and-scene-format.md` §6).\n *\n * ## Decisions the documents left open\n *\n * - **The file is flat.** §2.6 lists the PBR properties directly, so a `.material.json` carries the\n * format header, a `type` discriminator, and the properties of that type at the top level. There\n * is no per-type sub-object to reach through.\n * - **Colours in the file are sRGB.** `06-serialization-and-scene-format.md` §3 is explicit that\n * colours are sRGB in memory and in files and that the conversion to linear \"belongs to the\n * renderer\". This module is that boundary: `baseColor`, `emissive`, `diffuse`, and `specular` are\n * decoded here and handed to the adapter linear. Factors that are not colours — `metallic`,\n * `roughness`, `alpha` — are unitless and pass through.\n * - **`\"type\": \"shader\"` is Phase 7.** §2.6 lists it, and Lite's `createShaderMaterial` exists, but\n * its declaration takes a WGSL attribute/uniform/sampler layout whose shape is Lite's own\n * (`ShaderMaterialOptions`, `index.d.ts`); publishing that verbatim would put a Lite type in the\n * public API, which `CONSTITUTION.md` §3.4 forbids, and mirroring it is a design job of its own.\n * A file that declares it is rejected with `IGX-0708` naming the phase.\n * - **PBR extensions (`clearcoat`, `sheen`, `transmission`, …) are Phase 7** for the same reason:\n * each is a sub-record with its own textures, and §2.6 wants them opt-in so unused shader code is\n * tree-shaken. The loader reports an unknown top-level key rather than silently dropping it.\n *\n * ## Headless\n *\n * `createPbrMaterial` and `createStandardMaterial` are pure data plus one build-group function\n * (ADR-0002 Validation), so a material loads **completely** under the null engine; only the textures\n * it references come back empty. That is what makes the material half of a scene testable in Node.\n */\n\n/**\n * The asset type materials are registered under.\n *\n * @public\n */\nexport const MATERIAL_ASSET_TYPE = \"material\";\n\n/**\n * The `format` header every `.material.json` carries.\n *\n * @public\n */\nexport const MATERIAL_FILE_FORMAT = \"ignifx.material\";\n\n/**\n * The only `.material.json` `formatVersion` this build reads.\n *\n * @public\n */\nexport const MATERIAL_FORMAT_VERSION = 1;\n\n/**\n * The address suffix that selects the material loader.\n *\n * @public\n */\nexport const MATERIAL_FILE_EXTENSION = \".material.json\";\n\n/**\n * The material families `.material.json` can declare\n * (`docs/architecture/07-rendering.md` §2.6).\n *\n * @public\n */\nexport const MATERIAL_KINDS = [\"pbr\", \"standard\", \"shader\"] as const;\n\n/**\n * The union of the material families.\n *\n * @public\n */\nexport type MaterialKind = (typeof MATERIAL_KINDS)[number];\n\n/**\n * How a material interprets its alpha channel, in glTF's vocabulary.\n *\n * @public\n */\nexport type MaterialAlphaModeName = MaterialAlphaMode;\n\n/**\n * The alpha modes a material may declare, in the order the inspector lists them.\n *\n * @public\n */\nexport const MATERIAL_ALPHA_MODE_NAMES: readonly MaterialAlphaModeName[] = MATERIAL_ALPHA_MODES;\n\n/**\n * The properties a `\"pbr\"` material declares. Every colour is sRGB; every factor is unitless.\n *\n * @public\n */\nexport interface PbrMaterialDefinition {\n /** The family discriminator. */\n readonly kind: \"pbr\";\n /** A human-readable name; glTF material overrides match on it. */\n readonly name: string;\n /** sRGB base colour and alpha, multiplied with the base colour texture. */\n readonly baseColor: ColorLike;\n /** Metallic factor, 0 to 1. */\n readonly metallic: number;\n /** Roughness factor, 0 to 1. */\n readonly roughness: number;\n /** Normal map strength. */\n readonly normalScale: number;\n /** sRGB emissive colour. */\n readonly emissive: ColorLike;\n /** How strongly ambient occlusion darkens the surface, 0 to 1. */\n readonly occlusionStrength: number;\n /** How the alpha channel is interpreted. */\n readonly alphaMode: MaterialAlphaModeName;\n /** The cutoff below which a `\"mask\"` material discards a fragment. */\n readonly alphaCutoff: number;\n /** Overall material alpha, 0 to 1. */\n readonly alpha: number;\n /** Whether back faces are drawn. */\n readonly doubleSided: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit: boolean;\n /** How strongly the environment map contributes. */\n readonly environmentIntensity: number;\n /** The addresses of the textures the material samples, by slot; absent slots are unset. */\n readonly textures: Readonly<Record<string, string>>;\n}\n\n/**\n * The properties a `\"standard\"` material declares — the cheap non-PBR path\n * (`docs/architecture/07-rendering.md` §2.6).\n *\n * @public\n */\nexport interface StandardMaterialDefinition {\n /** The family discriminator. */\n readonly kind: \"standard\";\n /** A human-readable name. */\n readonly name: string;\n /** sRGB diffuse colour. */\n readonly diffuse: ColorLike;\n /** sRGB specular colour. */\n readonly specular: ColorLike;\n /** Specular exponent; higher values give a tighter highlight. */\n readonly specularPower: number;\n /** sRGB emissive colour. */\n readonly emissive: ColorLike;\n /** Overall material alpha, 0 to 1. */\n readonly alpha: number;\n /** The cutoff below which a fragment is discarded. `0` disables the alpha test. */\n readonly alphaCutoff: number;\n /** Whether back faces are drawn. */\n readonly doubleSided: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit: boolean;\n /** The addresses of the textures the material samples, by slot. */\n readonly textures: Readonly<Record<string, string>>;\n}\n\n/**\n * The parsed body of a `.material.json`, discriminated by `kind`.\n *\n * @public\n */\nexport type MaterialDefinition = PbrMaterialDefinition | StandardMaterialDefinition;\n\n/**\n * The texture slots a `\"pbr\"` material may name, in the order the loader resolves them.\n *\n * @public\n */\nexport const PBR_TEXTURE_SLOTS: readonly string[] = Object.freeze([\n \"baseColorTexture\",\n \"metallicRoughnessTexture\",\n \"normalTexture\",\n \"emissiveTexture\",\n \"occlusionTexture\",\n]);\n\n/**\n * The texture slots a `\"standard\"` material may name.\n *\n * @public\n */\nexport const STANDARD_TEXTURE_SLOTS: readonly string[] = Object.freeze([\n \"diffuseTexture\",\n \"specularTexture\",\n \"emissiveTexture\",\n \"normalTexture\",\n \"opacityTexture\",\n]);\n\n/**\n * The Babylon Lite objects a {@link MaterialAsset} owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @public\n */\nexport interface MaterialAssetLiteHandles {\n /** The Lite material. Present in headless mode too: a material is plain data. */\n readonly material: LiteMaterial;\n}\n\n/**\n * A material a `MeshRenderer` or a `Model` draws with\n * (`docs/architecture/07-rendering.md` §2.6).\n *\n * @remarks\n * Materials are shared: many renderers reference one asset, and editing it changes all of them.\n * {@link MaterialAsset.clone} is the per-renderer variation escape hatch — it rebuilds the Lite\n * material from the same declaration, so the copy starts identical and drifts on its own.\n *\n * @example\n * ```ts\n * const gold = await app.assets.loadAsync<MaterialAsset>(\"materials/gold.material.json\");\n * using warm = gold.value.clone(app);\n * warm.value.setBaseColor({ r: 1, g: 0.6, b: 0.2, a: 1 });\n * ```\n *\n * @public\n */\nexport class MaterialAsset {\n /** The type name the asset service registers materials under. */\n static assetType: string = MATERIAL_ASSET_TYPE;\n\n /** The declaration this material was built from; {@link MaterialAsset.clone} replays it. */\n readonly definition: MaterialDefinition;\n\n /** The texture handles the material samples, in slot order. It does not own them. */\n readonly textures: readonly AssetHandle<TextureAsset>[];\n\n readonly #material: LitePbrMaterial | LiteStandardMaterial;\n\n readonly #pbr: LitePbrMaterial | null;\n\n readonly #standard: LiteStandardMaterial;\n\n /**\n * Wraps a built Lite material. Use {@link createMaterialAsset}; the loader constructs these.\n *\n * @param definition - The declaration it was built from.\n * @param material - The Lite material.\n * @param textures - The texture handles the material samples.\n *\n * @internal\n */\n constructor(\n definition: MaterialDefinition,\n material: LitePbrMaterial | LiteStandardMaterial,\n textures: readonly AssetHandle<TextureAsset>[],\n ) {\n this.definition = definition;\n this.textures = textures;\n this.#material = material;\n // The two Lite material shapes are structurally distinct, and `definition.kind` is what the\n // factory branched on a moment ago, so the narrowing is a restatement rather than a guess\n // (coding standards §5.2).\n if (definition.kind === \"pbr\") {\n this.#pbr = material;\n this.#standard = createStandardMaterialFromProps({});\n } else {\n this.#pbr = null;\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n this.#standard = material as LiteStandardMaterial;\n }\n }\n\n /**\n * The material's human-readable name.\n *\n * @returns The declared name.\n */\n get name(): string {\n return this.definition.name;\n }\n\n /**\n * The material family.\n *\n * @returns `\"pbr\"` or `\"standard\"`.\n */\n get kind(): MaterialKind {\n return this.definition.kind;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch.\n *\n * @returns The Lite material.\n */\n get lite(): MaterialAssetLiteHandles {\n return { material: this.#material };\n }\n\n /**\n * Replaces the base colour — the PBR `baseColorFactor`, or a Standard material's `diffuseColor`.\n *\n * @remarks\n * The colour is sRGB, like every colour in ignifx's public API; the linear value the shader reads\n * is derived here. The change marks the material's uniform block dirty, which is the cheap path:\n * no pipeline is recompiled (`src/lite/material.ts`).\n *\n * @param color - The new sRGB colour. Alpha is used by PBR and ignored by Standard, which carries\n * its own `alpha`.\n */\n setBaseColor(color: ColorLike): void {\n const linear = toLinear(color);\n const pbr = this.#pbr;\n if (pbr !== null) {\n setPbrBaseColor(pbr, linear.r, linear.g, linear.b, color.a);\n return;\n }\n const standard = this.#standard;\n const diffuse = standard.diffuseColor;\n diffuse[0] = linear.r;\n diffuse[1] = linear.g;\n diffuse[2] = linear.b;\n markMaterialDirty(standard);\n }\n\n /**\n * Replaces the metallic and roughness factors of a `\"pbr\"` material. A Standard material has\n * neither, so the call is ignored.\n *\n * @param metallic - The metallic factor, 0 to 1.\n * @param roughness - The roughness factor, 0 to 1.\n */\n setMetallicRoughness(metallic: number, roughness: number): void {\n const pbr = this.#pbr;\n if (pbr !== null) {\n setPbrMetallicRoughness(pbr, metallic, roughness);\n }\n }\n\n /**\n * Replaces the material's overall alpha.\n *\n * @param alpha - The new alpha, 0 to 1.\n */\n setAlpha(alpha: number): void {\n setMaterialAlpha(this.#material, alpha);\n }\n\n /**\n * Builds an independent copy of this material from the same declaration — the per-renderer\n * variation path of `docs/architecture/07-rendering.md` §2.6.\n *\n * @remarks\n * The copy shares the original's *textures* (they are addressed assets, and the handles are\n * retained by whoever loaded them) and nothing else: it is a second Lite material in the same\n * family, so it costs no extra shader compilation.\n *\n * @param app - The app whose asset service publishes the copy.\n * @returns The copy's handle, with one holder — the caller.\n */\n clone(app: App): AssetHandle<MaterialAsset> {\n return createMaterialAsset(app, this.definition, this.textures);\n }\n}\n\n/**\n * Builds a Lite material from a declaration and publishes it as an in-memory asset.\n *\n * @param app - The app whose asset service publishes it.\n * @param definition - The declaration.\n * @param textures - The texture handles the declaration's slots resolved to, in slot order.\n * @returns The handle, with one holder — the caller.\n *\n * @example\n * ```ts\n * using red = createMaterialAsset(app, pbrMaterialDefinition({ name: \"red\", baseColor: { r: 1, g: 0, b: 0, a: 1 } }), []);\n * ```\n *\n * @public\n */\nexport function createMaterialAsset(\n app: App,\n definition: MaterialDefinition,\n textures: readonly AssetHandle<TextureAsset>[],\n): AssetHandle<MaterialAsset> {\n return app.assets.register(buildMaterialAsset(definition, textures), { type: MATERIAL_ASSET_TYPE });\n}\n\n/**\n * Builds the Lite material a declaration describes and wraps it, **without** publishing it.\n *\n * @remarks\n * This is what the `.material.json` loader returns: the asset service is already about to create\n * the handle for that address, so registering a second, in-memory one would double the entry. Code\n * that builds a material out of nowhere wants {@link createMaterialAsset} instead.\n *\n * @param definition - The declaration.\n * @param textures - The texture handles the declaration's slots resolved to, in slot order.\n * @returns The asset.\n *\n * @internal\n */\nexport function buildMaterialAsset(\n definition: MaterialDefinition,\n textures: readonly AssetHandle<TextureAsset>[],\n): MaterialAsset {\n const bySlot = indexTextures(definition, textures);\n const material =\n definition.kind === \"pbr\" ? buildPbrMaterial(definition, bySlot) : buildStandardMaterial(definition, bySlot);\n return new MaterialAsset(definition, material, textures);\n}\n\n/**\n * The material a `MeshRenderer` draws with when it declares none: a neutral, fully rough\n * dielectric (`docs/architecture/07-rendering.md` §2.3).\n *\n * @param app - The app whose asset service publishes it.\n * @returns The handle, with one holder — the caller, which is the renderer service.\n *\n * @internal\n */\nexport function createDefaultMaterialAsset(app: App): AssetHandle<MaterialAsset> {\n const definition = pbrMaterialDefinition({ name: \"ignifx:default\", metallic: 0, roughness: 0.9 });\n return app.assets.register(new MaterialAsset(definition, createDefaultMaterial(), []), {\n type: MATERIAL_ASSET_TYPE,\n });\n}\n\n/**\n * Fills in a PBR declaration's defaults, so callers name only what they mean to change.\n *\n * @param overrides - The properties to set.\n * @returns A complete declaration.\n *\n * @example\n * ```ts\n * pbrMaterialDefinition({ name: \"gold\", metallic: 1, roughness: 0.25 });\n * ```\n *\n * @public\n */\nexport function pbrMaterialDefinition(\n overrides: Partial<Omit<PbrMaterialDefinition, \"kind\">> = {},\n): PbrMaterialDefinition {\n return {\n kind: \"pbr\",\n name: overrides.name ?? \"\",\n baseColor: overrides.baseColor ?? { r: 1, g: 1, b: 1, a: 1 },\n metallic: overrides.metallic ?? 1,\n roughness: overrides.roughness ?? 1,\n normalScale: overrides.normalScale ?? 1,\n emissive: overrides.emissive ?? { r: 0, g: 0, b: 0, a: 1 },\n occlusionStrength: overrides.occlusionStrength ?? 1,\n alphaMode: overrides.alphaMode ?? \"opaque\",\n alphaCutoff: overrides.alphaCutoff ?? 0.5,\n alpha: overrides.alpha ?? 1,\n doubleSided: overrides.doubleSided ?? false,\n unlit: overrides.unlit ?? false,\n environmentIntensity: overrides.environmentIntensity ?? 1,\n textures: overrides.textures ?? {},\n };\n}\n\n/**\n * Fills in a Standard declaration's defaults.\n *\n * @param overrides - The properties to set.\n * @returns A complete declaration.\n *\n * @public\n */\nexport function standardMaterialDefinition(\n overrides: Partial<Omit<StandardMaterialDefinition, \"kind\">> = {},\n): StandardMaterialDefinition {\n return {\n kind: \"standard\",\n name: overrides.name ?? \"\",\n diffuse: overrides.diffuse ?? { r: 1, g: 1, b: 1, a: 1 },\n specular: overrides.specular ?? { r: 1, g: 1, b: 1, a: 1 },\n specularPower: overrides.specularPower ?? 64,\n emissive: overrides.emissive ?? { r: 0, g: 0, b: 0, a: 1 },\n alpha: overrides.alpha ?? 1,\n alphaCutoff: overrides.alphaCutoff ?? 0,\n doubleSided: overrides.doubleSided ?? false,\n unlit: overrides.unlit ?? false,\n textures: overrides.textures ?? {},\n };\n}\n\n/**\n * Refuses a material family this build cannot construct.\n *\n * @param kind - The `type` the file declared.\n * @param address - The address, for the message.\n * @throws IgnifxError with code `IGX-0708` for `\"shader\"`, which Phase 7 owns.\n *\n * @internal\n */\nexport function assertMaterialKindSupported(kind: MaterialKind, address: string): void {\n if (kind !== \"shader\") {\n return;\n }\n throw new IgnifxError(\n CoreErrorCode.unsupportedMaterialKind,\n `${address} declares a shader material, which this build cannot construct.`,\n {\n context: { asset: address, kind },\n hint: 'WGSL materials arrive in Phase 7; declare \"pbr\" or \"standard\" for now.',\n },\n );\n}\n\n/**\n * Groups a declaration's resolved textures by slot name.\n *\n * @param definition - The declaration, whose `textures` map is slot to address.\n * @param textures - The handles, in the order the loader resolved the slots.\n * @returns Slot name to Lite texture, skipping slots whose asset is headless or missing.\n */\nfunction indexTextures(\n definition: MaterialDefinition,\n textures: readonly AssetHandle<TextureAsset>[],\n): ReadonlyMap<string, LiteTexture2D> {\n const bySlot = new Map<string, LiteTexture2D>();\n const slots = Object.keys(definition.textures);\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index];\n const handle = textures[index];\n if (slot === undefined || handle === undefined || handle.state !== \"loaded\") {\n continue;\n }\n const texture = handle.value.lite.texture;\n if (texture !== null) {\n bySlot.set(slot, texture);\n }\n }\n return bySlot;\n}\n\n/**\n * Builds the Lite PBR material a declaration describes, converting its sRGB colours to linear.\n *\n * @param definition - The declaration.\n * @param textures - Slot name to Lite texture.\n * @returns The Lite material.\n */\nfunction buildPbrMaterial(\n definition: PbrMaterialDefinition,\n textures: ReadonlyMap<string, LiteTexture2D>,\n): LitePbrMaterial {\n const base = toLinear(definition.baseColor);\n const emissive = toLinear(definition.emissive);\n const input: {\n name: string;\n baseColor: readonly [number, number, number, number];\n metallic: number;\n roughness: number;\n normalScale: number;\n emissive: readonly [number, number, number];\n occlusionStrength: number;\n alphaMode: MaterialAlphaMode;\n alphaCutoff: number;\n alpha: number;\n doubleSided: boolean;\n unlit: boolean;\n environmentIntensity: number;\n baseColorTexture?: LiteTexture2D;\n metallicRoughnessTexture?: LiteTexture2D;\n normalTexture?: LiteTexture2D;\n emissiveTexture?: LiteTexture2D;\n occlusionTexture?: LiteTexture2D;\n } = {\n name: definition.name,\n baseColor: [base.r, base.g, base.b, definition.baseColor.a],\n metallic: definition.metallic,\n roughness: definition.roughness,\n normalScale: definition.normalScale,\n emissive: [emissive.r, emissive.g, emissive.b],\n occlusionStrength: definition.occlusionStrength,\n alphaMode: definition.alphaMode,\n alphaCutoff: definition.alphaCutoff,\n alpha: definition.alpha,\n doubleSided: definition.doubleSided,\n unlit: definition.unlit,\n environmentIntensity: definition.environmentIntensity,\n };\n assignTexture(textures, \"baseColorTexture\", (texture) => {\n input.baseColorTexture = texture;\n });\n assignTexture(textures, \"metallicRoughnessTexture\", (texture) => {\n input.metallicRoughnessTexture = texture;\n });\n assignTexture(textures, \"normalTexture\", (texture) => {\n input.normalTexture = texture;\n });\n assignTexture(textures, \"emissiveTexture\", (texture) => {\n input.emissiveTexture = texture;\n });\n assignTexture(textures, \"occlusionTexture\", (texture) => {\n input.occlusionTexture = texture;\n });\n return createPbrMaterialFromProps(input);\n}\n\n/**\n * Builds the Lite Standard material a declaration describes.\n *\n * @param definition - The declaration.\n * @param textures - Slot name to Lite texture.\n * @returns The Lite material.\n */\nfunction buildStandardMaterial(\n definition: StandardMaterialDefinition,\n textures: ReadonlyMap<string, LiteTexture2D>,\n): LiteStandardMaterial {\n const diffuse = toLinear(definition.diffuse);\n const specular = toLinear(definition.specular);\n const emissive = toLinear(definition.emissive);\n const input: {\n name: string;\n diffuse: readonly [number, number, number];\n specular: readonly [number, number, number];\n specularPower: number;\n emissive: readonly [number, number, number];\n alpha: number;\n alphaCutoff: number;\n doubleSided: boolean;\n unlit: boolean;\n diffuseTexture?: LiteTexture2D;\n specularTexture?: LiteTexture2D;\n emissiveTexture?: LiteTexture2D;\n normalTexture?: LiteTexture2D;\n opacityTexture?: LiteTexture2D;\n } = {\n name: definition.name,\n diffuse: [diffuse.r, diffuse.g, diffuse.b],\n specular: [specular.r, specular.g, specular.b],\n specularPower: definition.specularPower,\n emissive: [emissive.r, emissive.g, emissive.b],\n alpha: definition.alpha,\n alphaCutoff: definition.alphaCutoff,\n doubleSided: definition.doubleSided,\n unlit: definition.unlit,\n };\n assignTexture(textures, \"diffuseTexture\", (texture) => {\n input.diffuseTexture = texture;\n });\n assignTexture(textures, \"specularTexture\", (texture) => {\n input.specularTexture = texture;\n });\n assignTexture(textures, \"emissiveTexture\", (texture) => {\n input.emissiveTexture = texture;\n });\n assignTexture(textures, \"normalTexture\", (texture) => {\n input.normalTexture = texture;\n });\n assignTexture(textures, \"opacityTexture\", (texture) => {\n input.opacityTexture = texture;\n });\n return createStandardMaterialFromProps(input);\n}\n\n/**\n * Calls `assign` with the texture bound to a slot, when one is.\n *\n * @param textures - Slot name to Lite texture.\n * @param slot - The slot to read.\n * @param assign - Writes the texture onto the adapter input.\n */\nfunction assignTexture(\n textures: ReadonlyMap<string, LiteTexture2D>,\n slot: string,\n assign: (texture: LiteTexture2D) => void,\n): void {\n const texture = textures.get(slot);\n if (texture !== undefined) {\n assign(texture);\n }\n}\n\n/**\n * Converts an sRGB colour's RGB channels to linear. Alpha is already linear and is not touched.\n *\n * @param color - The sRGB colour.\n * @returns The linear channels.\n */\nfunction toLinear(color: ColorLike): { readonly r: number; readonly g: number; readonly b: number } {\n return {\n r: Color.srgbToLinear(color.r),\n g: Color.srgbToLinear(color.g),\n b: Color.srgbToLinear(color.b),\n };\n}\n","import { NO_RENDERING_FEATURES, RENDERING_FEATURE_NAMES } from \"../lite/render-features.js\";\nimport { bool, color, enumOf, f64, map, record, str, u32 } from \"../schema/field-kinds.js\";\nimport { defineSchema } from \"../schema/schema.js\";\nimport type { RendererOptions } from \"../lite/render-diagnostics.js\";\nimport type { RenderingFeatureName, RenderingFeatures } from \"../lite/render-features.js\";\nimport type { ColorLike } from \"../math/types.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `rendering` project settings section (`docs/architecture/04-extensions.md` §5,\n * `07-rendering.md` §1 and §1.1): the engine options the swapchain is created with, and the feature\n * opt-ins that have to be applied before the scene is registered.\n *\n * Three decisions the documents left open, and one place they are wrong:\n *\n * - **There is no `powerPreference`.** `07-rendering.md` §1 lists it among \"engine options exposed\n * by `createApp`\". Babylon Lite 1.27.0 has no such option — `lib/engine/engine.js` hard-codes\n * `requestAdapter({ powerPreference: \"high-performance\" })` and neither `EngineOptions`\n * (`index.d.ts` 4709) nor `SurfaceOptions` (12622) declares it — so ignifx does not expose one.\n * The correction is recorded in `src/lite/render-diagnostics.ts` as well.\n * - **`maxDevicePixelRatio` defaults to `0`, not `Infinity`.** §1 says the default is \"`Infinity`,\n * i.e. native DPR\", and that is the behaviour; but a settings section is validated JSON, and\n * `Infinity` is not a JSON number (`06-serialization-and-scene-format.md` §3 rejects non-finite\n * values with `IGX-0601`). `0` is the spelling of \"do not clamp\", and it is what the section\n * documents.\n * - **`brdfLut` lives here.** Lite's `loadEnvironment` takes a **required** `brdfUrl`\n * (`index.d.ts` 6779): it decodes the split-sum lookup table from a pre-baked RGBD PNG rather than\n * computing it. No document says where a game gets that file, so the section carries the address\n * and every `Environment` component resolves it through the asset service. An `Environment` may\n * override it per instance.\n * - **`resolutionScale` is not a setting.** §1 makes it a live quality knob (`app.renderer\n * .resolutionScale`), so it is a `Renderer` property with no settings counterpart; a project that\n * wants a fixed one writes `maxDevicePixelRatio`.\n */\n\n/**\n * The canvas alpha modes Lite accepts, in the order the inspector lists them.\n *\n * @public\n */\nexport const CANVAS_ALPHA_MODES = [\"opaque\", \"premultiplied\"] as const;\n\n/**\n * The union of the canvas alpha modes.\n *\n * @public\n */\nexport type CanvasAlphaMode = (typeof CANVAS_ALPHA_MODES)[number];\n\n/**\n * The rendering features a project switches on (`docs/architecture/07-rendering.md` §1.1). Every one\n * of them changes what Lite compiles at `registerScene`, so they are declared up front and a late\n * toggle is `IGX-0704`.\n *\n * @public\n */\nexport interface RenderingFeatureSettings {\n /** Register the scene with a shadow pass, so a `Light` can cast. */\n readonly shadows: boolean;\n /**\n * Render the scene into an offscreen target and composite it, so a `PostProcessStack` has\n * something it is allowed to sample. Off by default: it costs one full-screen blit per frame.\n */\n readonly postProcessing: boolean;\n /** Compile the Standard pipeline's skinning fragment, for skinned meshes. */\n readonly skeletons: boolean;\n /** Build the glTF loader's skeleton handles, needed before loading a skinned asset. */\n readonly boneControl: boolean;\n /** Install stencil resolvers on the PBR, Standard, and Shader pipelines. */\n readonly stencil: boolean;\n /** Load the PBR lightmap fragment extension. */\n readonly lightmaps: boolean;\n /** Install the material plugin bridges and the scene hook they need. */\n readonly materialPlugins: boolean;\n /** Compile shader pipelines asynchronously instead of blocking the first draw. */\n readonly asyncPipelines: boolean;\n /** Rebuild scenes and their resources after the WebGPU device is lost. */\n readonly deviceLostRecovery: boolean;\n}\n\n/**\n * The resolved `rendering` settings section\n * (`docs/architecture/04-extensions.md` §5, `07-rendering.md` §1).\n *\n * @example\n * ```ts\n * const app = await createApp({\n * canvas,\n * settings: { rendering: { features: { shadows: true }, msaaSamples: 1 } },\n * });\n * ```\n *\n * @public\n */\nexport interface RenderingSettings {\n /** The feature opt-ins, applied during `app.start()` before the scene is registered. */\n readonly features: RenderingFeatureSettings;\n /** MSAA sample count for the main pass. WebGPU allows 1 or 4; anything else is read as 4. */\n readonly msaaSamples: number;\n /** How the canvas composites with the page. `\"premultiplied\"` lets HTML show through. */\n readonly alphaMode: CanvasAlphaMode;\n /** Render through an sRGB swapchain view so alpha blending is gamma-correct. */\n readonly srgb: boolean;\n /** An explicit swapchain texture format; empty means Lite's own choice. Never an `*-srgb` one. */\n readonly format: string;\n /** Clamp on the device pixel ratio the swapchain is sized at. `0` means \"do not clamp\". */\n readonly maxDevicePixelRatio: number;\n /** Float64 intermediate precision for world matrices, for large worlds. */\n readonly useHighPrecisionMatrix: boolean;\n /** Eye-relative upload for large-world coordinates. Requires `useHighPrecisionMatrix`. */\n readonly useFloatingOrigin: boolean;\n /** Extra WebGPU device limits to request, such as a larger `maxColorAttachmentBytesPerSample`. */\n readonly requiredLimits: Readonly<Record<string, number>>;\n /**\n * The colour the scene is cleared to each frame, in sRGB.\n *\n * @remarks\n * Applied to the render scene as it is created, which makes it the floor of a three-step\n * precedence (`docs/architecture/07-rendering.md` §2.1, §2.5): `Camera.clearColor` on the main\n * camera wins whenever it is not `null`, an `Environment.clearColor` wins over this setting, and\n * this setting wins over Babylon Lite's own mid grey.\n */\n readonly clearColor: ColorLike;\n /** The address of the RGBD BRDF lookup table `loadEnvironment` requires. */\n readonly brdfLut: string;\n}\n\n/**\n * The name the `rendering` project settings section is registered under.\n *\n * @public\n */\nexport const RENDERING_SETTINGS_SECTION = \"rendering\";\n\n/**\n * The BRDF lookup table address an `Environment` uses when neither it nor the project names one.\n *\n * @public\n */\nexport const DEFAULT_BRDF_LUT_ADDRESS = \"environments/brdf-lut.png\";\n\n/** Lite's own MSAA default (`index.d.ts` 4709). */\nconst DEFAULT_MSAA_SAMPLES = 4;\n\n/** The only other sample count WebGPU allows for a multisampled attachment. */\nconst SINGLE_SAMPLE = 1;\n\n/** The clear colour a project that names none gets: opaque black. */\nconst DEFAULT_CLEAR_COLOR = \"#000000\";\n\n/**\n * The settings a project that declares no `rendering` section runs with: every feature off, Lite's\n * own swapchain defaults, and an unclamped device pixel ratio.\n *\n * @returns A fresh, complete section. It is built on demand rather than frozen at module scope\n * because `requiredLimits` and `clearColor` are mutable objects a caller must not share\n * (`CONSTITUTION.md` §3.5).\n *\n * @example\n * ```ts\n * const defaults = defaultRenderingSettings();\n * defaults.features.shadows; // false\n * ```\n *\n * @public\n */\nexport function defaultRenderingSettings(): RenderingSettings {\n return {\n features: { ...NO_RENDERING_FEATURES },\n msaaSamples: DEFAULT_MSAA_SAMPLES,\n alphaMode: \"opaque\",\n srgb: false,\n format: \"\",\n maxDevicePixelRatio: 0,\n useHighPrecisionMatrix: false,\n useFloatingOrigin: false,\n requiredLimits: {},\n clearColor: { r: 0, g: 0, b: 0, a: 1 },\n brdfLut: DEFAULT_BRDF_LUT_ADDRESS,\n };\n}\n\n/**\n * Builds the schema the `rendering` section is validated against.\n *\n * @returns The schema. Built on demand: a schema field is a function call, and module scope holds\n * declarations only (`CONSTITUTION.md` §3.5).\n *\n * @internal\n */\nexport function renderingSettingsSchema(): Schema {\n return defineSchema({\n features: record({\n shadows: bool(false, { tooltip: \"Register the scene with a shadow pass.\" }),\n postProcessing: bool(false, { tooltip: \"Render through an offscreen target, for PostProcessStack.\" }),\n skeletons: bool(false, { tooltip: \"Compile the skinning fragment for skinned meshes.\" }),\n boneControl: bool(false, { tooltip: \"Build glTF skeleton handles while loading.\" }),\n stencil: bool(false, { tooltip: \"Install stencil resolvers on every material pipeline.\" }),\n lightmaps: bool(false, { tooltip: \"Load the PBR lightmap fragment extension.\" }),\n materialPlugins: bool(false, { tooltip: \"Install the material plugin bridges.\" }),\n asyncPipelines: bool(false, { tooltip: \"Compile shader pipelines asynchronously.\" }),\n deviceLostRecovery: bool(false, { tooltip: \"Rebuild resources after a WebGPU device loss.\" }),\n }),\n msaaSamples: u32(DEFAULT_MSAA_SAMPLES, { min: 1, max: 4, tooltip: \"MSAA sample count: 1 or 4.\" }),\n alphaMode: enumOf(CANVAS_ALPHA_MODES, \"opaque\", { tooltip: \"How the canvas composites with the page.\" }),\n srgb: bool(false, { tooltip: \"Render through an sRGB swapchain view.\" }),\n format: str(\"\", { tooltip: \"An explicit swapchain format; empty means Lite's own choice.\" }),\n maxDevicePixelRatio: f64(0, { min: 0, tooltip: \"Device pixel ratio clamp; 0 does not clamp.\" }),\n useHighPrecisionMatrix: bool(false, { tooltip: \"Float64 world matrices, for large worlds.\" }),\n useFloatingOrigin: bool(false, { tooltip: \"Eye-relative upload; needs useHighPrecisionMatrix.\" }),\n requiredLimits: map(f64(0, { min: 0 }), { tooltip: \"Extra WebGPU device limits to request.\" }),\n clearColor: color(DEFAULT_CLEAR_COLOR, {\n tooltip: \"The colour the scene is cleared to, in sRGB. A Camera or Environment overrides it.\",\n }),\n brdfLut: str(DEFAULT_BRDF_LUT_ADDRESS, { tooltip: \"Address of the RGBD BRDF lookup table.\" }),\n });\n}\n\n/**\n * Reads the declared feature block as the adapter's own flag record.\n *\n * @remarks\n * Every name is filled in, and anything that is not literally `true` is `false`. That is not\n * defensiveness: the settings store merges a project's section over the registered defaults\n * **shallowly** (`src/settings/settings-store.ts`), so a project that writes\n * `rendering: { features: { shadows: true } }` replaces the whole record and the other seven names\n * arrive `undefined`. Reading them as \"off\" is the only interpretation that matches what the\n * project wrote.\n *\n * @param settings - The resolved section.\n * @returns One boolean per feature name, in the adapter's order.\n *\n * @internal\n */\nexport function toRenderingFeatures(settings: RenderingSettings): RenderingFeatures {\n const declared: Partial<RenderingFeatureSettings> = settings.features;\n const features: Record<string, boolean> = {};\n for (let index = 0; index < RENDERING_FEATURE_NAMES.length; index += 1) {\n const name: RenderingFeatureName | undefined = RENDERING_FEATURE_NAMES[index];\n if (name !== undefined) {\n features[name] = declared[name] === true;\n }\n }\n // Boundary assertion (coding standards §5.2): the loop wrote exactly the keys of\n // `RENDERING_FEATURE_NAMES`, which is what `RenderingFeatures` is a mapped type over.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return features as RenderingFeatures;\n}\n\n/**\n * Translates the section into the options the adapter hands `createEngine`.\n *\n * @remarks\n * `maxDevicePixelRatio: 0` is dropped rather than passed as a clamp of zero, which would size the\n * swapchain at nothing. `format: \"\"` is dropped for the same reason. `msaaSamples` is narrowed to\n * the two counts WebGPU allows; the schema already rejects anything outside 1–4, and 2 and 3 read\n * as 4 rather than failing an app over a quality knob.\n *\n * @param settings - The resolved section.\n * @param resolutionScale - The live `renderer.resolutionScale`, multiplied into the clamp by\n * `toLiteEngineOptions`.\n * @returns The adapter's renderer options.\n *\n * @internal\n */\nexport function toRendererOptions(settings: RenderingSettings, resolutionScale: number): RendererOptions {\n const options: {\n msaaSamples?: 1 | 4;\n alphaMode?: GPUCanvasAlphaMode;\n srgb?: boolean;\n pixelRatio?: number;\n resolutionScale?: number;\n useHighPrecisionMatrix?: boolean;\n useFloatingOrigin?: boolean;\n requiredLimits?: Record<string, GPUSize64 | undefined>;\n } = {\n msaaSamples: settings.msaaSamples === SINGLE_SAMPLE ? SINGLE_SAMPLE : DEFAULT_MSAA_SAMPLES,\n alphaMode: settings.alphaMode,\n srgb: settings.srgb,\n useHighPrecisionMatrix: settings.useHighPrecisionMatrix,\n useFloatingOrigin: settings.useFloatingOrigin,\n };\n if (settings.maxDevicePixelRatio > 0) {\n options.pixelRatio = settings.maxDevicePixelRatio;\n }\n if (resolutionScale !== 1) {\n options.resolutionScale = resolutionScale;\n }\n const limits = settings.requiredLimits;\n if (Object.keys(limits).length > 0) {\n options.requiredLimits = { ...limits };\n }\n return options;\n}\n\n/**\n * The swapchain format the section asks for, when it asks for one.\n *\n * @remarks\n * Kept apart from {@link toRendererOptions} because Lite declares `format` on `SurfaceOptions`\n * (`index.d.ts` 12622) rather than on `EngineOptions`, and the adapter's `RendererOptions` covers\n * only the latter. `createApp` merges the two.\n *\n * @param settings - The resolved section.\n * @returns The format, or `null` when the project named none.\n *\n * @internal\n */\nexport function toSurfaceFormat(settings: RenderingSettings): string | null {\n return settings.format === \"\" ? null : settings.format;\n}\n","import { createServiceKey } from \"../app/types.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { toComponentHandle, toEntityHandle } from \"../handles/handle.js\";\nimport { setSceneClearColor } from \"../lite/gpu/environment.js\";\nimport { disposeScenePicker } from \"../lite/gpu/picker.js\";\nimport { setSurfaceSizePx } from \"../lite/gpu/render-diagnostics-gpu.js\";\nimport { captureFrame } from \"../lite/gpu/screenshot-capture.js\";\nimport { discardMaterialWarmUp } from \"../lite/gpu/warm-up.js\";\nimport { readPickedTag } from \"../lite/picking.js\";\nimport { disableGpuTiming, readDrawCallCount, readGpuFrameTimeMs } from \"../lite/render-diagnostics.js\";\nimport { assertRenderingFeatureAvailable } from \"../lite/render-features.js\";\nimport { sceneLightCount } from \"../lite/scene.js\";\nimport { Color } from \"../math/color.js\";\nimport { clamp } from \"../math/math-utils.js\";\nimport {\n applySurfaceScale,\n createPicker,\n pickPixel,\n readTargetSizePx,\n readTaskTimings,\n startGpuTiming,\n warmUpMaterialAssets,\n} from \"./gpu/renderer-gpu.js\";\nimport {\n buildMaterialAsset,\n createDefaultMaterialAsset,\n MATERIAL_ASSET_TYPE,\n standardMaterialDefinition,\n} from \"./material-asset.js\";\nimport { toRenderingFeatures } from \"./rendering-settings.js\";\nimport type { MaterialAsset } from \"./material-asset.js\";\nimport type { RenderingFeatureSettings, RenderingSettings } from \"./rendering-settings.js\";\nimport type { App, ServiceNameKey } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { DiagnosticsGroup } from \"../diagnostics/diagnostics-group.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { LiteGpuPicker } from \"../lite/gpu/picker.js\";\nimport type { ScenePresenter } from \"../lite/gpu/render-path.js\";\nimport type { MaterialWarmUp } from \"../lite/gpu/warm-up.js\";\nimport type { NodeTag } from \"../lite/node.js\";\nimport type { LitePickInfo } from \"../lite/picking.js\";\nimport type { RenderingFeatureName, RenderingFeatures } from \"../lite/render-features.js\";\nimport type { LiteEngine, LiteScene } from \"../lite/scene.js\";\nimport type { ColorLike } from \"../math/types.js\";\nimport type { RenderSurface } from \"../platform/webgpu.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * `app.renderer` (`docs/architecture/07-rendering.md` §1, §3, §5, ADR-0014): the service that owns\n * everything about rendering that is not attached to an entity — surface sizing, the feature gate,\n * material warm-up, picking, screenshots, and the render diagnostics counters.\n *\n * It is also where the render layer keeps its per-app state, which is why the components and the\n * `PreRender` system reach it through {@link rendererInternals} rather than through a second\n * service. One object, one lifetime, one place to look.\n *\n * ## Decisions the documents left open\n *\n * - **`requireFeature` before start turns the feature on.** §1.1 says extensions \"declare the\n * features they need through `ctx.requireRenderingFeature(name)` at registration\" and that late\n * toggles are `IGX-0704`. Registration happens before `app.start()` applies the opt-ins, so the\n * call is a *declaration* then and a refusal afterwards. That is the only reading under which an\n * extension can need a feature the project did not think to list.\n * - **A headless pick resolves to `null`, it does not throw.** The GPU picker needs a device and a\n * rendered frame. §6 says headless components \"keep their state\" and skip GPU work, so a pick is\n * a miss rather than an error; `world.raycastRender` is the CPU path that still answers.\n * - **A headless screenshot rejects.** `captureScreenshot` never settles without a running render\n * loop (ADR-0002 Validation), so awaiting one under the null engine would hang forever. §5 asks\n * for `IGX-0707`, and rejecting is the only way a caller finds out.\n */\n\n/**\n * The render diagnostics group name (`docs/architecture/15-devtools-and-diagnostics.md` §3).\n *\n * @public\n */\nexport const RENDER_DIAGNOSTICS_GROUP = \"render\";\n\n/**\n * The key `app.renderer` is registered and looked up under.\n *\n * @remarks\n * The service is a *core* member of `App`, not an extension contribution, so it does not go through\n * `defineAppProperty`. It is still a service, because the core extension is what builds it — it\n * needs the resolved `rendering` settings section, which only exists once `register` has run — and\n * the service table is how a value built during registration reaches the app.\n *\n * @internal\n */\nexport const RendererService: ServiceNameKey<Renderer> = createServiceKey<Renderer>(\"ignifx/renderer\");\n\n/**\n * The counters the `render` diagnostics group publishes, in index order.\n *\n * @public\n */\nexport const RENDER_DIAGNOSTICS_COUNTERS: readonly string[] = Object.freeze([\n \"drawCalls\",\n \"gpuFrameTimeMs\",\n \"cameras\",\n \"lights\",\n \"meshes\",\n \"renderableRebuilds\",\n]);\n\n/** The feature record while the service still owns it: `requireFeature` writes into it before start. */\ntype MutableRenderingFeatures = { -readonly [Name in RenderingFeatureName]: boolean };\n\n/** The smallest resolution scale `docs/architecture/07-rendering.md` §1 allows. */\nconst MIN_RESOLUTION_SCALE = 0.25;\n\n/** The largest resolution scale, i.e. no downscaling. */\nconst MAX_RESOLUTION_SCALE = 1;\n\n/**\n * A rendering feature a project or an extension asks for\n * (`docs/architecture/07-rendering.md` §1.1).\n *\n * @public\n */\nexport type RenderingFeature = keyof RenderingFeatureSettings;\n\n/**\n * What a GPU pick found (`docs/architecture/07-rendering.md` §3).\n *\n * @public\n */\nexport interface RenderPick {\n /** The entity that owns the mesh the ray hit. */\n readonly entity: Entity;\n /** The component that created the mesh, when it was not the entity's own transform. */\n readonly component: Component | null;\n /** The world-space hit point, or `null` unless detailed picking is on. */\n readonly point: readonly [number, number, number] | null;\n /** The world-space surface normal, or `null` unless detailed picking is on. */\n readonly normal: readonly [number, number, number] | null;\n /** How far along the ray the hit is, in metres. */\n readonly distance: number;\n}\n\n/**\n * How a GPU pick is restricted (`docs/architecture/07-rendering.md` §3).\n *\n * @public\n */\nexport interface RenderPickOptions {\n /**\n * Restricts the pick to the entities this accepts. A rejected entity neither occludes nor\n * returns, which is what makes a \"pick only the pickups\" query exact rather than approximate.\n *\n * @param entity - The candidate.\n * @returns `true` to consider the entity.\n */\n readonly filter?: (entity: Entity) => boolean;\n}\n\n/**\n * A captured frame (`docs/architecture/07-rendering.md` §5).\n *\n * @remarks\n * Tightly packed RGBA8, four bytes per pixel, row-major with the **top** row first — the layout\n * `ImageData` wants. Alpha is forced to 255 because the swapchain is presented opaque, and the\n * values are the final presented 8-bit colours, so comparing two captures compares what the player\n * saw.\n *\n * @public\n */\nexport interface RenderCapture {\n /** The capture width, in device pixels. */\n readonly width: number;\n /** The capture height, in device pixels. */\n readonly height: number;\n /** `width * height * 4` bytes of RGBA8. */\n readonly data: Uint8ClampedArray;\n}\n\n/**\n * One frame-graph task's measured GPU time (`docs/architecture/07-rendering.md` §5).\n *\n * @public\n */\nexport interface RenderTaskTiming {\n /** The task's name in the frame graph: `\"shadow\"`, `\"scene\"`, or a post-process task's own. */\n readonly name: string;\n /** How long the task took on the GPU, in milliseconds. */\n readonly durationMs: number;\n}\n\n/**\n * A per-task GPU timing snapshot (`docs/architecture/07-rendering.md` §5).\n *\n * @public\n */\nexport interface RenderTaskTimings {\n /**\n * Whether the numbers mean anything: `\"unsupported\"` on a device with no timestamp queries — the\n * CI software adapter is one — `\"disabled\"` until `profileTasks` is on, `\"pending\"` until the\n * first readback lands, `\"error\"` when it failed, `\"ok\"` otherwise.\n */\n readonly status: string;\n /** The tasks, in frame execution order. Empty unless `status` is `\"ok\"`. */\n readonly tasks: readonly RenderTaskTiming[];\n}\n\n/**\n * The rendering service, reached as `app.renderer`\n * (`docs/architecture/07-rendering.md` §1, §3, §5).\n *\n * @example\n * ```ts\n * app.renderer.resolutionScale = 0.75;\n * const hit = await app.renderer.pickAsync(event.offsetX, event.offsetY);\n * hit?.entity.name;\n * ```\n *\n * @public\n */\nexport interface Renderer {\n /**\n * The clamp on the device pixel ratio the swapchain is sized at; `0` does not clamp. Writing it\n * resizes the backing store before the next frame.\n */\n pixelRatio: number;\n /**\n * A live quality multiplier on the resolution, clamped to 0.25–1 and implemented by lowering the\n * effective device pixel ratio (`docs/architecture/07-rendering.md` §1).\n */\n resolutionScale: number;\n /** Whether per-task GPU timings are collected. Off by default; it costs timestamp queries. */\n profileTasks: boolean;\n /** Which rendering features are on. Read-only once `app.start()` has registered the scene. */\n readonly features: Readonly<RenderingFeatureSettings>;\n /**\n * The canvas the app draws into, or `null` under a headless app.\n *\n * @remarks\n * An extension that adds a second rendering context — `@ignifx/2d`'s sprite renderer — creates it\n * on this surface and registers it after the render scene (`07-rendering.md` §1).\n */\n readonly surface: RenderSurface | null;\n /** GPU draw calls in the last rendered frame. `0` under a headless app. */\n readonly drawCalls: number;\n /** How long the last measured frame took on the GPU, in milliseconds. `0` until timing is on. */\n readonly gpuFrameTimeMs: number;\n /**\n * Sets the swapchain's backing-store size explicitly, in device pixels — the `OffscreenCanvas`\n * path (`docs/architecture/07-rendering.md` §1).\n *\n * @remarks\n * On a laid-out DOM canvas the size survives exactly one frame: Lite's render loop re-reads the\n * layout size at the start of every frame. Use {@link Renderer.pixelRatio} there instead.\n *\n * @param width - The width, in device pixels.\n * @param height - The height, in device pixels.\n */\n setSize(width: number, height: number): void;\n /**\n * Compiles the material families of the given materials now, so a mesh that uses one of them\n * later draws on the next frame instead of several frames after that (ADR-0014).\n *\n * @remarks\n * `app.start()` already does this for every material in the `boot` preload group. Call it by hand\n * for a spawn-heavy game that loads a material mid-level and wants to pay the cost at a moment of\n * its choosing.\n *\n * @param materials - The materials whose families must be compiled.\n */\n warmUp(materials: readonly MaterialAsset[]): void;\n /**\n * Picks the object under one CSS pixel of the canvas, exactly, on the GPU\n * (`docs/architecture/07-rendering.md` §3).\n *\n * @remarks\n * Picks are serialised per app: Lite's picker owns one set of staging buffers and chains each\n * call onto the previous one's promise. A headless app has no picker and always misses.\n *\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param options - An entity filter.\n * @returns What was hit, or `null` for a miss.\n */\n pickAsync(x: number, y: number, options?: RenderPickOptions): Promise<RenderPick | null>;\n /**\n * Captures the next presented frame (`docs/architecture/07-rendering.md` §5).\n *\n * @returns The frame, as tightly packed RGBA8 with the top row first.\n * @throws IgnifxError with code `IGX-0707` when no render loop is running, because the capture\n * would never settle.\n */\n captureScreenshot(): Promise<RenderCapture>;\n /**\n * The latest per-task GPU timing snapshot. Check `status` before reading `tasks`.\n *\n * @returns The snapshot.\n */\n taskTimings(): RenderTaskTimings;\n /**\n * Declares that a rendering feature must be on — what an extension calls from `register`\n * (`docs/architecture/07-rendering.md` §1.1).\n *\n * @param feature - The feature the caller needs.\n * @throws IgnifxError with code `IGX-0704` when the render scene has already been registered, at\n * which point Lite has compiled what it is going to compile.\n */\n requireFeature(feature: RenderingFeature): void;\n}\n\n/**\n * The rendering service of one app, and the render layer's per-app state.\n *\n * @internal\n */\nexport class RendererImpl implements Renderer {\n /** The resolved `rendering` settings section. */\n readonly settings: RenderingSettings;\n\n /** `true` once a topology change needs one `rebuildSceneRenderables` this frame. */\n needsRenderableRebuild = false;\n\n /** `true` once a `castShadows` or caster-set change needs the caster lists rebuilt this frame. */\n needsCasterRebuild = false;\n\n /** `true` once a camera was added, removed, enabled, disabled, or re-prioritised. */\n needsCameraSelect = true;\n\n /** `true` once the world has been told it has no enabled camera, so `IGX-0706` is logged once. */\n hasLoggedNoCamera = false;\n\n /** How many times the sync system has rebuilt the scene's renderables; a diagnostics counter. */\n renderableRebuilds = 0;\n\n readonly #app: App;\n\n readonly #features: MutableRenderingFeatures;\n\n readonly #counters: DiagnosticsGroup;\n\n readonly #countersDrawCalls: number;\n\n readonly #countersGpuTime: number;\n\n readonly #countersCameras: number;\n\n readonly #countersLights: number;\n\n readonly #countersMeshes: number;\n\n readonly #countersRebuilds: number;\n\n #picker: LiteGpuPicker | null = null;\n\n #warmUp: MaterialWarmUp | null = null;\n\n #syncSystem: { sync(world: World): void } | null = null;\n\n #handles: { readonly engine: LiteEngine; readonly scene: LiteScene } | null = null;\n\n #presenter: ScenePresenter | null = null;\n\n #defaultMaterial: AssetHandle<MaterialAsset> | null = null;\n\n #resolutionScale = 1;\n\n #pixelRatio: number;\n\n #profileTasks = false;\n\n #isSceneRegistered = false;\n\n #isLoopRunning = false;\n\n /**\n * Creates the rendering service.\n *\n * @param app - The app it belongs to.\n * @param settings - The resolved `rendering` section.\n */\n constructor(app: App, settings: RenderingSettings) {\n this.#app = app;\n this.settings = settings;\n this.#features = toRenderingFeatures(settings);\n this.#pixelRatio = settings.maxDevicePixelRatio;\n const counters = app.diagnostics.registerGroup(RENDER_DIAGNOSTICS_GROUP, RENDER_DIAGNOSTICS_COUNTERS);\n this.#counters = counters;\n this.#countersDrawCalls = counters.index(\"drawCalls\");\n this.#countersGpuTime = counters.index(\"gpuFrameTimeMs\");\n this.#countersCameras = counters.index(\"cameras\");\n this.#countersLights = counters.index(\"lights\");\n this.#countersMeshes = counters.index(\"meshes\");\n this.#countersRebuilds = counters.index(\"renderableRebuilds\");\n }\n\n /**\n * The app the service belongs to.\n *\n * @returns The app.\n */\n get app(): App {\n return this.#app;\n }\n\n /**\n * The Lite scene the world renders into.\n *\n * @returns The scene.\n */\n get scene(): LiteScene {\n return this.#handles?.scene ?? this.#app.lite.scene;\n }\n\n /**\n * The Lite engine, which is also the app's primary surface.\n *\n * @returns The engine.\n */\n get engine(): LiteEngine {\n return this.#handles?.engine ?? this.#app.lite.engine;\n }\n\n /**\n * Whether the app runs on the null engine.\n *\n * @returns `true` when there is no device and no surface.\n */\n get isHeadless(): boolean {\n return this.#app.isHeadless;\n }\n\n /**\n * The canvas the app draws into.\n *\n * @returns The surface, or `null` under the null engine.\n */\n get surface(): RenderSurface | null {\n return this.isHeadless ? null : this.engine.canvas;\n }\n\n /**\n * The offscreen render path, when the project declared `rendering.features.postProcessing`.\n *\n * @remarks\n * `null` under a headless app, and `null` when the feature is off — in which case a\n * `PostProcessStack` has nothing legal to sample and reports `IGX-0710`.\n *\n * @returns The presenter, or `null`.\n */\n get presenter(): ScenePresenter | null {\n return this.#presenter;\n }\n\n /**\n * Whether `app.start()` has registered the render scene, after which Lite has compiled what it is\n * going to compile.\n *\n * @returns `true` once the scene is registered.\n */\n get isSceneRegistered(): boolean {\n return this.#isSceneRegistered;\n }\n\n /**\n * The feature flags in their adapter form, for `applyRenderingFeatures`.\n *\n * @returns One boolean per adapter feature name.\n */\n get renderingFeatures(): RenderingFeatures {\n return this.#features;\n }\n\n /**\n * Which rendering features are on.\n *\n * @returns The flags. The object is the service's own; treat it as read-only.\n */\n get features(): Readonly<RenderingFeatureSettings> {\n return this.#features;\n }\n\n /**\n * The device pixel ratio clamp; `0` does not clamp.\n *\n * @returns The clamp.\n */\n get pixelRatio(): number {\n return this.#pixelRatio;\n }\n\n set pixelRatio(value: number) {\n this.#pixelRatio = Math.max(0, value);\n this.#applySurfaceScale();\n }\n\n /**\n * The live resolution multiplier, 0.25 to 1.\n *\n * @returns The multiplier.\n */\n get resolutionScale(): number {\n return this.#resolutionScale;\n }\n\n set resolutionScale(value: number) {\n this.#resolutionScale = clamp(value, MIN_RESOLUTION_SCALE, MAX_RESOLUTION_SCALE);\n this.#applySurfaceScale();\n }\n\n /**\n * Whether per-task GPU timings are collected.\n *\n * @returns `true` when timing is on.\n */\n get profileTasks(): boolean {\n return this.#profileTasks;\n }\n\n set profileTasks(value: boolean) {\n this.#profileTasks = value;\n if (this.isHeadless) {\n return;\n }\n if (value) {\n startGpuTiming(this.engine);\n } else {\n disableGpuTiming(this.engine);\n }\n }\n\n /**\n * GPU draw calls in the last rendered frame.\n *\n * @returns The count; `0` under a headless app.\n */\n get drawCalls(): number {\n return readDrawCallCount(this.engine);\n }\n\n /**\n * How long the last measured frame took on the GPU.\n *\n * @returns The time in milliseconds; `0` until timing is on and a frame has completed.\n */\n get gpuFrameTimeMs(): number {\n return readGpuFrameTimeMs(this.engine);\n }\n\n /**\n * Sets the swapchain's backing-store size explicitly, in device pixels.\n *\n * @param width - The width, in device pixels.\n * @param height - The height, in device pixels.\n */\n setSize(width: number, height: number): void {\n if (this.isHeadless) {\n return;\n }\n setSurfaceSizePx(this.engine, width, height);\n }\n\n /**\n * Compiles the material families the engine can produce, before the scene is registered\n * (ADR-0014).\n *\n * @remarks\n * ADR-0014 says `app.start()` \"collects the materials of every asset in the `boot` preload group\"\n * and warms those. It cannot: a preloaded asset's handle settles at the `PreUpdate` delivery\n * point of a frame (`05-assets-and-loading.md` §4), and `start()` runs before the first frame, so\n * awaiting the boot batch there would deadlock — which is exactly why the core extension does not\n * await it either.\n *\n * What the ADR actually measured makes the deadlock unnecessary. Lite stamps **every** PBR\n * material in the process with one `_buildGroup` singleton, and every Standard material with\n * another, so the unit that has to exist at `registerScene` is the *family*, not the asset: \"there\n * are four families to worry about, not one per asset\". This warms the two families a Phase 2\n * app can produce, plus any material already in the cache, which reaches the ADR's outcome — a\n * mesh added later takes the synchronous rebuild path — with two degenerate triangles and no\n * ordering problem.\n *\n * @internal\n */\n warmUpAtStart(): void {\n if (this.isHeadless || sceneLightCount(this.scene) === 0) {\n // A probe registered into a scene with **no** lights leaves every later mesh of that family\n // undrawn — the render pass presents nothing at all (measured on SwiftShader 2026-09-05, and\n // pinned by `test/render/warm-up.browser.test.ts`). A lightless scene draws nothing anyway\n // until a light arrives, and a mesh added then takes Lite's runtime build path, which is\n // correct; skipping the probes there costs a few frames on the first spawn and is the only\n // safe reading of ADR-0014 for a world that is still empty at `start()`.\n return;\n }\n const materials: MaterialAsset[] = [this.defaultMaterial(), buildMaterialAsset(standardProbe(), [])];\n for (const handle of this.#app.assets.manifest.entries) {\n const cached = this.#app.assets.get(handle.address);\n if (cached !== null && cached.state === \"loaded\" && cached.type === MATERIAL_ASSET_TYPE) {\n // Boundary assertion (coding standards §5.2): the cache is untyped, and the type name is\n // what says this entry holds a material.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n materials.push(cached.value as MaterialAsset);\n }\n }\n this.warmUp(materials);\n }\n\n /**\n * Compiles the material families of the given materials now (ADR-0014).\n *\n * @param materials - The materials whose families must be compiled.\n */\n warmUp(materials: readonly MaterialAsset[]): void {\n if (this.isHeadless || materials.length === 0) {\n return;\n }\n this.#warmUp = warmUpMaterialAssets(this.engine, this.scene, materials);\n }\n\n /**\n * Picks the object under one CSS pixel of the canvas.\n *\n * @param x - The CSS pixel x, from the canvas's left edge.\n * @param y - The CSS pixel y, from the canvas's top edge.\n * @param options - An entity filter.\n * @returns What was hit, or `null` for a miss.\n */\n async pickAsync(x: number, y: number, options?: RenderPickOptions): Promise<RenderPick | null> {\n if (this.isHeadless) {\n return null;\n }\n const picker = (this.#picker ??= createPicker(this.scene));\n const filter = options?.filter;\n const info: LitePickInfo = await pickPixel(\n picker,\n x,\n y,\n filter === undefined ? null : (tag: NodeTag | null): boolean => acceptsEntityTag(this.#app.world, tag, filter),\n );\n return this.resolvePick(info);\n }\n\n /**\n * Captures the next presented frame.\n *\n * @returns The frame.\n * @throws IgnifxError with code `IGX-0707` when no render loop is running.\n */\n async captureScreenshot(): Promise<RenderCapture> {\n if (this.isHeadless || !this.#isLoopRunning) {\n throw new IgnifxError(\n CoreErrorCode.screenshotNeedsRenderLoop,\n \"captureScreenshot() needs a running render loop; a headless app never presents a frame.\",\n {\n context: { member: \"app.renderer.captureScreenshot()\" },\n hint: \"Call it after app.start() on a canvas-backed app; headless apps have no swapchain.\",\n },\n );\n }\n return captureFrame(this.engine);\n }\n\n /**\n * The latest per-task GPU timing snapshot.\n *\n * @returns The snapshot.\n */\n taskTimings(): RenderTaskTimings {\n return this.isHeadless ? { status: \"unsupported\", tasks: [] } : readTaskTimings(this.engine);\n }\n\n /**\n * Declares that a rendering feature must be on.\n *\n * @param feature - The feature the caller needs.\n * @throws IgnifxError with code `IGX-0704` after the render scene has been registered.\n */\n requireFeature(feature: RenderingFeature): void {\n assertRenderingFeatureAvailable(feature, this.#isSceneRegistered);\n this.#features[feature] = true;\n }\n\n /**\n * The material a `MeshRenderer` draws with when it declares none\n * (`docs/architecture/07-rendering.md` §2.3): a neutral, fully rough dielectric.\n *\n * @remarks\n * Built on first use and shared by every renderer, so an app that always names its materials\n * never pays for it, and one that never does pays once. The service holds the only reference and\n * releases it on disposal.\n *\n * @returns The default material.\n *\n * @internal\n */\n defaultMaterial(): MaterialAsset {\n this.#defaultMaterial ??= createDefaultMaterialAsset(this.#app);\n return this.#defaultMaterial.value;\n }\n\n /**\n * Reads the render target's current size in device pixels, without allocating.\n *\n * @remarks\n * A headless app has no canvas to measure, so it reports a 1x1 target: every screen conversion\n * then degenerates predictably instead of dividing by zero (`07-rendering.md` §6).\n *\n * @param out - Receives the size.\n *\n * @param out.width - Receives the width, in device pixels.\n * @param out.height - Receives the height, in device pixels.\n * @internal\n */\n readTargetSize(out: { width: number; height: number }): void {\n if (this.isHeadless) {\n out.width = 1;\n out.height = 1;\n return;\n }\n readTargetSizePx(this.engine, out);\n }\n\n /**\n * Resolves a Lite pick result back to the entity and component that own the mesh.\n *\n * @param info - Lite's picking info, from the GPU picker or a CPU ray cast.\n * @returns What was hit, or `null` for a miss or a mesh ignifx did not create.\n *\n * @internal\n */\n resolvePick(info: LitePickInfo): RenderPick | null {\n if (!info.hit) {\n return null;\n }\n const tag = readPickedTag(info);\n if (tag === null) {\n return null;\n }\n const world = this.#app.world;\n const entity = world.getEntityByHandle(toEntityHandle(tag.entity));\n if (entity === null) {\n return null;\n }\n const component = tag.component;\n return {\n entity,\n component: component === undefined ? null : world.getComponentByHandle(toComponentHandle(component)),\n point: info.pickedPoint,\n normal: info.pickedNormalWorld ?? info.pickedNormal,\n distance: info.distance,\n };\n }\n\n /**\n * Records the Lite objects the app owns, so the service keeps working while the app is being\n * torn down.\n *\n * @remarks\n * `app.lite` refuses to answer once `dispose()` has started (`IGX-0106`), and the render layer's\n * own teardown — a component's `onDetach`, the service's disposer — runs inside that window.\n * Caching the pair the moment `createApp` builds it is what keeps a disposal from turning into a\n * cascade of `IGX-0106`s.\n *\n * @param engine - The app's engine.\n * @param scene - The app's render scene.\n * @param presenter - The offscreen render path, when `rendering.features.postProcessing` built\n * one; `null` otherwise, in which case a `PostProcessStack` reports `IGX-0710`.\n *\n * @internal\n */\n attachHandles(engine: LiteEngine, scene: LiteScene, presenter: ScenePresenter | null = null): void {\n this.#handles = { engine, scene };\n this.#presenter = presenter;\n // `rendering.clearColor` is applied here, the moment the scene exists, and never again: it is\n // the *floor* of the precedence order in {@link RendererImpl.applyClearColor}, so anything a\n // component writes later simply lands on top of it. Doing it per frame would fight the camera.\n this.applyClearColor(this.settings.clearColor);\n }\n\n /**\n * Writes an sRGB colour onto the render scene's clear colour, decoded to linear.\n *\n * @remarks\n * The one place `scene.clearColor` is written, so the precedence\n * `docs/architecture/07-rendering.md` §2.1 and §2.5 describe is decided by *who calls it and\n * when*, from strongest to weakest:\n *\n * 1. **`Camera.clearColor` on the main camera**, when it is not `null`. The `PreRender` system\n * writes it every frame the camera renders, so it always wins.\n * 2. **`Environment.clearColor`** of the winning environment, written whenever the field changes.\n * 3. **The `rendering.clearColor` setting**, written once by {@link RendererImpl.attachHandles}\n * as the scene is created — before a frame has run, and therefore before either component.\n * 4. Babylon Lite's own default, a mid grey, when the project declared no section at all. The\n * ignifx default is opaque black (`src/render/rendering-settings.ts`), so Lite's grey is only\n * ever seen by code that bypasses `createApp`.\n *\n * Colours are stored in sRGB in every settings section and every component field, and Lite's\n * `scene.clearColor` is linear, so each component is decoded on the way through.\n *\n * @param value - The sRGB colour, `0` to `1` per channel.\n *\n * @internal\n */\n applyClearColor(value: ColorLike): void {\n setSceneClearColor(\n this.scene,\n Color.srgbToLinear(value.r),\n Color.srgbToLinear(value.g),\n Color.srgbToLinear(value.b),\n value.a,\n );\n }\n\n /**\n * Reconciles the world with the Lite scene once, before the scene is registered.\n *\n * @remarks\n * `app.start()` calls it so that a world built before the app started — the documented flow, in\n * which `world.loadScene(...)` precedes `start()` — registers with its cameras, lights, and\n * meshes already in place. Everything added afterwards goes through Lite's runtime material-swap\n * path instead (`docs/architecture/07-rendering.md` §1.1).\n *\n * @param world - The world to reconcile.\n *\n * @internal\n */\n syncBeforeRegister(world: World): void {\n this.#syncSystem?.sync(world);\n }\n\n /**\n * Records the `PreRender` system, so `app.start()` can run one reconciliation before the scene is\n * registered without knowing what that system is.\n *\n * @param system - The render-sync system the core extension registered.\n *\n * @param system.sync - Reconciles one world against the scene, exactly as a `PreRender` tick would.\n * @internal\n */\n attachSyncSystem(system: { sync(world: World): void }): void {\n this.#syncSystem = system;\n }\n\n /**\n * Records that the render scene has been registered, which closes the feature gate.\n *\n * @internal\n */\n markSceneRegistered(): void {\n this.#isSceneRegistered = true;\n }\n\n /**\n * Records whether Babylon Lite's render loop is driving frames, which is what decides whether a\n * screenshot can ever settle.\n *\n * @param isRunning - `true` between `startRenderLoop` and `stopRenderLoop`.\n *\n * @internal\n */\n setLoopRunning(isRunning: boolean): void {\n this.#isLoopRunning = isRunning;\n }\n\n /**\n * Publishes the render diagnostics counters. The `PreRender` system calls it once per frame.\n *\n * @param cameras - How many `Camera` components exist.\n * @param lights - How many `Light` components exist.\n * @param meshes - How many `MeshRenderer` components exist.\n *\n * @internal\n */\n publishCounters(cameras: number, lights: number, meshes: number): void {\n const counters = this.#counters;\n counters.set(this.#countersDrawCalls, this.drawCalls);\n counters.set(this.#countersGpuTime, this.gpuFrameTimeMs);\n counters.set(this.#countersCameras, cameras);\n counters.set(this.#countersLights, lights);\n counters.set(this.#countersMeshes, meshes);\n counters.set(this.#countersRebuilds, this.renderableRebuilds);\n }\n\n /**\n * Releases the picker and the warm-up probes. The core extension registers it as a disposer.\n *\n * @internal\n */\n dispose(): void {\n const picker = this.#picker;\n this.#picker = null;\n if (picker !== null) {\n disposeScenePicker(picker);\n }\n const warmUp = this.#warmUp;\n this.#warmUp = null;\n if (warmUp !== null && !this.isHeadless) {\n discardMaterialWarmUp(this.scene, warmUp);\n }\n const material = this.#defaultMaterial;\n this.#defaultMaterial = null;\n material?.release();\n }\n\n /** Writes the effective device pixel ratio clamp onto the surface and resizes it. */\n #applySurfaceScale(): void {\n if (this.isHeadless) {\n return;\n }\n const base = this.#pixelRatio > 0 ? this.#pixelRatio : hostDevicePixelRatio();\n applySurfaceScale(this.engine, base * this.#resolutionScale);\n }\n}\n\n/**\n * Asks whether a tagged Lite node belongs to an entity a caller's filter accepts — the shared half\n * of `renderer.pickAsync`'s and `world.raycastRender`'s entity predicates.\n *\n * @param world - The world being picked in.\n * @param tag - The ignifx tag the candidate node carries, or `null` when it has none.\n * @param filter - The caller's entity predicate.\n * @returns `true` when the node may be picked.\n *\n * @internal\n */\nexport function acceptsEntityTag(world: World, tag: NodeTag | null, filter: (entity: Entity) => boolean): boolean {\n if (tag === null) {\n return false;\n }\n const entity = world.getEntityByHandle(toEntityHandle(tag.entity));\n return entity !== null && filter(entity);\n}\n\n/**\n * The declaration of the Standard-family probe material the start-up warm-up installs.\n *\n * @returns A neutral Standard declaration.\n */\nfunction standardProbe(): ReturnType<typeof standardMaterialDefinition> {\n return standardMaterialDefinition({ name: \"ignifx:warm-up-standard\" });\n}\n\n/**\n * The host's device pixel ratio, or `1` on a host that has no `window`.\n *\n * @returns The ratio.\n */\nfunction hostDevicePixelRatio(): number {\n return \"devicePixelRatio\" in globalThis ? globalThis.devicePixelRatio : 1;\n}\n\n/**\n * Reaches the engine-owned half of `app.renderer` from the render components, the `PreRender`\n * system, and the kernel, all of which only ever see the public {@link Renderer} interface.\n *\n * @param renderer - The service, normally `app.renderer`.\n * @returns The same object, typed as its implementation.\n * @throws IgnifxError with code `IGX-0702` when the object was not created by ignifx.\n *\n * @internal\n */\nexport function rendererInternals(renderer: Renderer): RendererImpl {\n if (renderer instanceof RendererImpl) {\n return renderer;\n }\n throw new IgnifxError(CoreErrorCode.invalidRuntime, \"app.renderer was not created by this copy of @ignifx/core.\", {\n context: { member: \"app.renderer\" },\n hint: \"Reach the service through the app that created it.\",\n });\n}\n","import { Component } from \"../component/component.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport {\n addLightToScene,\n createDirectionalLightInWorld,\n createHemisphericLightInWorld,\n createPointLightInWorld,\n createSpotLightInWorld,\n removeLightFromScene,\n setHemisphericGroundColor,\n setLightColor,\n setLightExcludedMeshIds,\n setLightIncludedMeshIds,\n setLightIntensity,\n setLightRange,\n setSpotAngle,\n setSpotExponent,\n syncLightWorldPose,\n} from \"../lite/light.js\";\nimport { readWorldMatrix, worldMatrixVersion } from \"../lite/node.js\";\nimport { SHADOW_TECHNIQUES } from \"../lite/shadow.js\";\nimport { Color } from \"../math/color.js\";\nimport { array, bool, color, entityRef, enumOf, f32, record, u32 } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport { attachShadows, detachShadows, setShadowCasterMeshes } from \"./gpu/light-shadows.js\";\nimport { rendererInternals } from \"./renderer.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { ComponentHooks } from \"../component/component.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { LiteMesh } from \"../lite/gpu/mesh.js\";\nimport type { AdapterLight, RangedLight } from \"../lite/light.js\";\nimport type { LiteShadowGenerator } from \"../lite/shadow.js\";\nimport type { ColorLike } from \"../math/types.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `Light` component (`docs/architecture/07-rendering.md` §2.2): the four light kinds Babylon\n * Lite offers, driven from the entity's transform.\n *\n * ## The Lite light is not parented; the entity's world pose is written onto it\n *\n * Every other render component mirrors its entity by parenting a Lite object under the entity's\n * node. A light cannot: Lite composes a light's world matrix as `parentWorld ×\n * localMatrixFromDirection(light.direction, light.position)` and the shader reads that world\n * matrix, while the shadow frustum is fitted from `light.direction`/`light.position` *directly*\n * (`src/lite/light.ts` has the citations). Parenting the light and also writing a world direction\n * onto it rotated the light twice; parenting it and leaving the local direction alone made it shade\n * one way and cast another. Both were visible in the Phase 2 visual suite, and both are recorded in\n * ADR-0002's \"Corrections after the visual suite\".\n *\n * So the adapter creates the light with `parent = null`, and {@link Light.sync} writes the entity's\n * **world** pose onto the light in every frame the entity's `worldMatrixVersion` moved — its forward\n * axis for a directional or spot light, its **up** axis for a hemispheric light's sky direction, and\n * its position for anything that has one. One pose, read identically by the shader, the lights\n * uniform buffer, and the shadow frustum. It also re-marks the light for the lights UBO, which Lite\n * bumps only from a light's own observable writes — so the pose write is the dirty nudge as well.\n *\n * ## Decisions the documents left open\n *\n * - **`includeOnly`/`exclude` are entity references, matched to mesh ids.** §2.2's table maps them\n * onto `includedOnlyMeshIds`/`excludedMeshIds`, which are sets of `Mesh.id` **strings**\n * (`lib/render/lights-ubo.js`). A `MeshRenderer` gives its clone the entity's uid as that id, so\n * the component turns the referenced entities into a set of uids. An entity with no renderer\n * contributes nothing, which is the harmless reading.\n * - **A spot light's `technique` is ignored, not rejected.** Lite has one spot generator, PCF\n * (`index.d.ts` 2856). Rejecting a declared `\"csm\"` on a spot light would fail a scene over a\n * value that has one sensible interpretation.\n * - **Shadows need the `shadows` rendering feature.** `registerSceneWithShadowSupport` is the only\n * call that grows a shadow pass, and nothing public adds one later (`src/lite/shadow.ts`), so a\n * light that asks for shadows without the feature is a no-op with a logged warning rather than a\n * throw: the game still runs, unlit by shadows.\n */\n\n/** The light kinds a `Light` can be. */\n/**\n * The `as const` name table behind the public union of the same name.\n *\n * @public\n */\nexport const LIGHT_TYPES = [\"directional\", \"point\", \"spot\", \"hemispheric\"] as const;\n\n/**\n * The union of the light kinds.\n *\n * @public\n */\nexport type LightType = (typeof LIGHT_TYPES)[number];\n\n/**\n * The union of the shadow techniques a directional light can use.\n *\n * @public\n */\nexport type ShadowTechniqueName = (typeof SHADOW_TECHNIQUES)[number];\n\n/**\n * The `shadows` record a `Light` declares (`docs/architecture/07-rendering.md` §2.2).\n *\n * @public\n */\nexport interface LightShadowSettings {\n /** Whether this light casts shadows. */\n enabled: boolean;\n /** The technique; spot lights ignore it and always use PCF, the only one Lite offers them. */\n technique: ShadowTechniqueName;\n /** Shadow map resolution, in texels per side. */\n mapSize: number;\n /** Depth bias applied while sampling. */\n bias: number;\n /** Offset along the surface normal, PCF only. */\n normalBias: number;\n /** How dark a fully shadowed texel is: `0` is black, `1` is unshadowed. */\n darkness: number;\n /** Cascade count, CSM only; Lite clamps it to four. */\n cascades: number;\n /** The distance beyond which nothing is shadowed, in metres; `0` takes Lite's default. */\n maxDistance: number;\n}\n\n/** How many elements a 4x4 matrix has. */\nconst MATRIX_LENGTH = 16;\n\n/** Where the world-space up axis starts inside a column-major world matrix. */\nconst UP_COLUMN = 4;\n\n/** Where the world-space forward axis starts inside a column-major world matrix. */\nconst FORWARD_COLUMN = 8;\n\n/** Where the world-space translation starts inside a column-major world matrix. */\nconst TRANSLATION_COLUMN = 12;\n\n/**\n * A light source (`docs/architecture/07-rendering.md` §2.2).\n *\n * @remarks\n * The entity's transform defines the light: a directional or spot light points along the entity's\n * local `+Z`, a point light sits at its origin, and a hemispheric light's sky direction is its local\n * `+Y`.\n *\n * @example\n * ```ts\n * const sun = world.createEntity(\"Sun\");\n * sun.transform.lookAt({ x: 0, y: 0, z: 0 });\n * sun.addComponent(Light, { type: \"directional\", intensity: 3, shadows: { enabled: true } });\n * ```\n *\n * @public\n */\nexport class Light extends Component implements ComponentHooks {\n /** The namespaced registration id. */\n static typeId = \"ignifx/Light\";\n\n /** At most one light per entity: two lights from one transform want two entities. */\n static allowMultiple = false;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = lightSchema();\n\n declare type: LightType;\n\n declare color: ColorLike;\n\n declare intensity: number;\n\n declare range: number;\n\n declare spotAngle: number;\n\n declare spotExponent: number;\n\n declare groundColor: ColorLike;\n\n declare shadows: LightShadowSettings;\n\n declare includeOnly: (Entity | null)[];\n\n declare exclude: (Entity | null)[];\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(Light.schema));\n }\n\n readonly #worldMatrix = new Float64Array(MATRIX_LENGTH);\n\n #light: AdapterLight | null = null;\n\n #generator: LiteShadowGenerator | null = null;\n\n #appliedType: LightType | null = null;\n\n #appliedColor = \"\";\n\n #appliedGroundColor = \"\";\n\n #appliedIntensity = Number.NaN;\n\n #appliedRange = Number.NaN;\n\n #appliedSpotAngle = Number.NaN;\n\n #appliedSpotExponent = Number.NaN;\n\n #appliedShadows = false;\n\n #appliedIncludeSize = -1;\n\n #appliedExcludeSize = -1;\n\n #entityVersion = -1;\n\n #hasWarnedAboutShadows = false;\n\n /**\n * The Babylon Lite light this component owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The light and its shadow generator, either of which may be `null`.\n */\n get lite(): { readonly light: AdapterLight | null; readonly shadowGenerator: LiteShadowGenerator | null } {\n return { light: this.#light, shadowGenerator: this.#generator };\n }\n\n /**\n * Whether this light currently casts shadows — which needs the `shadows` rendering feature, a\n * light kind Lite can shadow, and `shadows.enabled`.\n *\n * @returns `true` when a shadow generator is attached.\n */\n get isCastingShadows(): boolean {\n return this.#generator !== null;\n }\n\n /** Records that the component exists; the Lite light is built on the first sync. */\n onAttach(): void {\n this.#appliedType = null;\n }\n\n /** Removes the light from the scene and releases its shadow generator. */\n onDetach(): void {\n this.#teardown(rendererInternals(this.app.renderer));\n }\n\n /**\n * Writes every field that changed onto the Lite light, keeps the lights uniform buffer honest for\n * a moving parent, and re-fits a shadow frustum that follows one. The `PreRender` system calls it.\n *\n * @param renderer - The rendering service, for the scene and the feature flags.\n * @returns `true` when the call changed the scene's light topology, which the system coalesces\n * into one `rebuildSceneRenderables`.\n *\n * @internal\n */\n sync(renderer: RendererImpl): boolean {\n let topologyChanged = this.#ensureLight(renderer);\n const light = this.#light;\n if (light === null) {\n return topologyChanged;\n }\n this.#applyColors(light);\n this.#applyScalars(light);\n this.#applyFilters(light);\n topologyChanged = this.#applyShadows(renderer) || topologyChanged;\n this.#followEntity(light);\n return topologyChanged;\n }\n\n /**\n * Replaces the meshes this light renders into its shadow map.\n *\n * @remarks\n * Lite keys the caster list by array identity and re-preloads the shadow pipeline every time a\n * **new** array arrives, parking the generator until that finishes (`src/lite/shadow.ts`). The\n * `PreRender` system therefore builds one array per frame in which the caster set actually\n * changed, and hands the same array to every casting light.\n *\n * @param casters - The meshes that cast into it.\n *\n * @internal\n */\n setShadowCasters(casters: readonly LiteMesh[]): void {\n const generator = this.#generator;\n if (generator !== null) {\n setShadowCasterMeshes(generator, casters);\n }\n }\n\n /**\n * Builds the Lite light, replacing it when `type` changed.\n *\n * @param renderer - The rendering service, for the scene.\n * @returns `true` when a light was added to or removed from the scene.\n */\n #ensureLight(renderer: RendererImpl): boolean {\n const type: LightType = this.type;\n if (this.#appliedType === type && this.#light !== null) {\n return false;\n }\n this.#teardown(renderer);\n const light = createLightOfType(type, this.intensity);\n this.#light = light;\n this.#appliedType = type;\n this.#appliedColor = \"\";\n this.#appliedGroundColor = \"\";\n this.#appliedIntensity = this.intensity;\n this.#appliedRange = Number.NaN;\n this.#appliedSpotAngle = Number.NaN;\n this.#appliedSpotExponent = Number.NaN;\n this.#entityVersion = -1;\n addLightToScene(renderer.scene, light);\n return true;\n }\n\n /**\n * Writes the sRGB colour fields onto the light, decoded to linear.\n *\n * @param light - The Lite light.\n */\n #applyColors(light: AdapterLight): void {\n const key = colorKey(this.color);\n if (key !== this.#appliedColor) {\n this.#appliedColor = key;\n setLightColor(\n light,\n Color.srgbToLinear(this.color.r),\n Color.srgbToLinear(this.color.g),\n Color.srgbToLinear(this.color.b),\n );\n }\n if (light.lightType !== \"hemispheric\") {\n return;\n }\n const ground = colorKey(this.groundColor);\n if (ground !== this.#appliedGroundColor) {\n this.#appliedGroundColor = ground;\n setHemisphericGroundColor(\n light,\n Color.srgbToLinear(this.groundColor.r),\n Color.srgbToLinear(this.groundColor.g),\n Color.srgbToLinear(this.groundColor.b),\n );\n }\n }\n\n /**\n * Writes the numeric fields that apply to this light kind.\n *\n * @param light - The Lite light.\n */\n #applyScalars(light: AdapterLight): void {\n if (this.#appliedIntensity !== this.intensity) {\n this.#appliedIntensity = this.intensity;\n setLightIntensity(light, this.intensity);\n }\n if (isRanged(light) && this.#appliedRange !== this.range) {\n this.#appliedRange = this.range;\n setLightRange(light, this.range);\n }\n if (light.lightType !== \"spot\") {\n return;\n }\n if (this.#appliedSpotAngle !== this.spotAngle) {\n this.#appliedSpotAngle = this.spotAngle;\n setSpotAngle(light, this.spotAngle);\n }\n if (this.#appliedSpotExponent !== this.spotExponent) {\n this.#appliedSpotExponent = this.spotExponent;\n setSpotExponent(light, this.spotExponent);\n }\n }\n\n /**\n * Rebuilds the include and exclude mesh-id sets when either list changed length.\n *\n * @remarks\n * Length is the change signal rather than a deep compare: the lists are inspector-edited entity\n * references, they are short, and a swap that keeps the length is rare enough that costing a\n * `Set` rebuild per frame to catch it would be the wrong trade (coding standards §7).\n *\n * @param light - The Lite light.\n */\n #applyFilters(light: AdapterLight): void {\n if (this.#appliedIncludeSize !== this.includeOnly.length) {\n this.#appliedIncludeSize = this.includeOnly.length;\n setLightIncludedMeshIds(light, this.includeOnly.length === 0 ? null : toMeshIds(this.includeOnly));\n }\n if (this.#appliedExcludeSize !== this.exclude.length) {\n this.#appliedExcludeSize = this.exclude.length;\n setLightExcludedMeshIds(light, this.exclude.length === 0 ? null : toMeshIds(this.exclude));\n }\n }\n\n /**\n * Attaches or detaches the shadow generator the `shadows` record asks for.\n *\n * @param renderer - The rendering service, for the engine and the feature flags.\n * @returns `true` when a generator was attached or detached.\n */\n #applyShadows(renderer: RendererImpl): boolean {\n const light = this.#light;\n const wanted = this.shadows.enabled && renderer.features.shadows && !renderer.isHeadless;\n if (light === null || wanted === this.#appliedShadows) {\n this.#warnAboutShadows(renderer);\n return false;\n }\n this.#appliedShadows = wanted;\n if (!wanted) {\n this.#releaseGenerator(renderer);\n return true;\n }\n this.#generator = attachShadows(renderer.engine, light, this.shadows);\n return true;\n }\n\n /**\n * Says once, at warning level, that a light asked for shadows the project did not enable.\n *\n * @param renderer - The rendering service, for the feature flags and the log.\n */\n #warnAboutShadows(renderer: RendererImpl): void {\n // Headless does **not** suppress this: \"the project forgot the opt-in\" is a configuration\n // problem, and a headless test is exactly where a project should find out about it.\n if (this.#hasWarnedAboutShadows || !this.shadows.enabled || renderer.features.shadows) {\n return;\n }\n this.#hasWarnedAboutShadows = true;\n renderer.app.log.warn(\n \"{entity} asks for shadows, but the rendering.features.shadows opt-in is off, so it casts none.\",\n this.entity.name,\n );\n }\n\n /**\n * Writes the entity's world pose onto the unparented Lite light, in any frame in which the entity\n * moved.\n *\n * @remarks\n * Unconditional — not only for a caster. The shader, the lights uniform buffer, and the shadow\n * frustum all read this one pose, so skipping it for a light that does not cast would leave the\n * light shading from wherever it was last posed.\n *\n * @param light - The Lite light.\n */\n #followEntity(light: AdapterLight): void {\n const node = entityInternals(this.entity).node;\n const version = worldMatrixVersion(node);\n if (version === this.#entityVersion) {\n return;\n }\n this.#entityVersion = version;\n const matrix = readWorldMatrix(node, this.#worldMatrix);\n syncLightWorldPose(\n light,\n matrix[FORWARD_COLUMN] ?? 0,\n matrix[FORWARD_COLUMN + 1] ?? 0,\n matrix[FORWARD_COLUMN + 2] ?? 1,\n matrix[UP_COLUMN] ?? 0,\n matrix[UP_COLUMN + 1] ?? 1,\n matrix[UP_COLUMN + 2] ?? 0,\n matrix[TRANSLATION_COLUMN] ?? 0,\n matrix[TRANSLATION_COLUMN + 1] ?? 0,\n matrix[TRANSLATION_COLUMN + 2] ?? 0,\n );\n }\n\n /**\n * Releases the shadow generator, when there is one.\n *\n * @param renderer - The rendering service, for the scene.\n */\n #releaseGenerator(renderer: RendererImpl): void {\n const generator = this.#generator;\n const light = this.#light;\n this.#generator = null;\n if (generator !== null) {\n detachShadows(renderer.scene, light, generator);\n }\n }\n\n /**\n * Removes the light and its generator from the scene.\n *\n * @param renderer - The rendering service, for the scene.\n */\n #teardown(renderer: RendererImpl): void {\n this.#releaseGenerator(renderer);\n const light = this.#light;\n this.#light = null;\n this.#appliedType = null;\n this.#appliedShadows = false;\n if (light !== null) {\n removeLightFromScene(renderer.scene, light);\n }\n }\n}\n\n/**\n * Builds the Lite light of one kind, unparented and at the world origin.\n *\n * @param type - The declared kind.\n * @param intensity - The initial intensity.\n * @returns The light. `Light.sync` poses it from the entity on the same frame.\n */\nfunction createLightOfType(type: LightType, intensity: number): AdapterLight {\n switch (type) {\n case \"directional\":\n return createDirectionalLightInWorld(intensity);\n case \"point\":\n return createPointLightInWorld(intensity);\n case \"spot\":\n return createSpotLightInWorld(45, 2, intensity);\n case \"hemispheric\":\n return createHemisphericLightInWorld(intensity);\n default:\n return assertNever(type, \"light type\");\n }\n}\n\n/**\n * Whether a light has a distance falloff.\n *\n * @param light - The Lite light.\n * @returns `true` for point and spot lights.\n */\nfunction isRanged(light: AdapterLight): light is RangedLight {\n return light.lightType === \"point\" || light.lightType === \"spot\";\n}\n\n/**\n * The set of mesh ids a list of entity references restricts a light to.\n *\n * @remarks\n * A `MeshRenderer` names its clone with the owning entity's uid, so the id set is the uid set.\n *\n * @param entities - The referenced entities; `null` entries are references the file could not\n * resolve and are skipped.\n * @returns The ids.\n */\nfunction toMeshIds(entities: readonly (Entity | null)[]): ReadonlySet<string> {\n const ids = new Set<string>();\n for (let index = 0; index < entities.length; index += 1) {\n const entity = entities[index];\n if (entity !== null && entity !== undefined) {\n ids.add(entity.uid);\n }\n }\n return ids;\n}\n\n/**\n * A colour's change key: four channels joined, which is cheaper to compare than four fields and\n * allocates one small string only when a colour actually changed.\n *\n * @param value - The colour.\n * @param value.r - The red channel.\n * @param value.g - The green channel.\n * @param value.b - The blue channel.\n * @param value.a - The alpha channel.\n * @returns The key.\n */\nfunction colorKey(value: { readonly r: number; readonly g: number; readonly b: number; readonly a: number }): string {\n return `${String(value.r)},${String(value.g)},${String(value.b)},${String(value.a)}`;\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function, not at module scope: a schema field is a function\n * call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4).\n */\nfunction lightSchema(): Schema {\n return defineSchema({\n type: enumOf(LIGHT_TYPES, \"directional\", { tooltip: \"Which kind of light this is.\" }),\n color: color(\"#ffffff\", { tooltip: \"The light's sRGB colour.\" }),\n intensity: f32(1, { min: 0, tooltip: \"How bright the light is.\" }),\n range: f32(10, { min: 0, tooltip: \"Distance at which a point or spot light reaches zero.\" }),\n spotAngle: f32(45, { min: 0, max: 180, tooltip: \"A spot light's full cone angle, in degrees.\" }),\n spotExponent: f32(2, { min: 0, tooltip: \"A spot light's falloff exponent; higher is sharper.\" }),\n groundColor: color(\"#000000\", { tooltip: \"A hemispheric light's sRGB colour from below.\" }),\n shadows: record(\n {\n enabled: bool(false, { tooltip: \"Whether this light casts shadows.\" }),\n technique: enumOf(SHADOW_TECHNIQUES, \"pcf\", { tooltip: \"Directional lights only; spot lights use PCF.\" }),\n mapSize: u32(1024, { min: 16, tooltip: \"Shadow map resolution, in texels per side.\" }),\n bias: f32(0.00005, { tooltip: \"Depth bias applied while sampling.\" }),\n normalBias: f32(0, { tooltip: \"Offset along the surface normal, PCF only.\" }),\n darkness: f32(0, { min: 0, max: 1, tooltip: \"How dark a fully shadowed texel is.\" }),\n cascades: u32(4, { min: 1, max: 4, tooltip: \"Cascade count, CSM only.\" }),\n maxDistance: f32(0, { min: 0, tooltip: \"Shadow distance in metres; 0 takes Lite's default.\" }),\n },\n { tooltip: \"Shadow casting; point and hemispheric lights cannot cast (IGX-0703).\" },\n ),\n includeOnly: array(entityRef<Entity>(), [], { tooltip: \"Light only these entities' renderers.\" }),\n exclude: array(entityRef<Entity>(), [], { tooltip: \"Never light these entities' renderers.\" }),\n });\n}\n","import { CoreErrorCode } from \"../../errors/error-codes.js\";\nimport { IgnifxError } from \"../../errors/ignifx-error.js\";\nimport { loadSceneEnvironment } from \"../../lite/gpu/environment.js\";\nimport {\n ENVIRONMENT_ASSET_TYPE,\n ENVIRONMENT_FILE_EXTENSION,\n ENVIRONMENT_FILE_EXTENSIONS,\n ENVIRONMENT_FILE_FORMAT,\n ENVIRONMENT_FORMAT_VERSION,\n EnvironmentAsset,\n environmentDefinition,\n} from \"../environment-asset.js\";\nimport { DEFAULT_BRDF_LUT_ADDRESS, RENDERING_SETTINGS_SECTION } from \"../rendering-settings.js\";\nimport type { AssetLoader, LoaderContext } from \"../../assets/types.js\";\nimport type { EnvironmentDefinition } from \"../environment-asset.js\";\nimport type { RenderingSettings } from \"../rendering-settings.js\";\n\n/**\n * The `environment` asset loader: `.env`, `.hdr`, `.dds`, and the `.environment.json` description\n * file (`docs/architecture/05-assets-and-loading.md` §5,\n * `06-serialization-and-scene-format.md` §6).\n *\n * ## Two addresses, one asset type\n *\n * A bare `.env` address is the common case: load this IBL, take the BRDF table and the skybox from\n * the project settings. An `.environment.json` is the same thing with the skybox, the blur, and the\n * rotation pinned next to the IBL so several scenes can share one description. Both produce an\n * {@link EnvironmentAsset}, and the loader tells them apart by the address suffix — the longest\n * registered extension wins the match, so `.environment.json` never falls through to the generic\n * `json` loader.\n *\n * ## The BRDF lookup table\n *\n * `loadEnvironment` takes a **required** `brdfUrl` (`index.d.ts` 6779). The address comes from the\n * file, then from `rendering.brdfLut`, then from the built-in default; it is resolved to a URL\n * through `app.assets.resolveUrl`, so a content-hashed production build works with no special\n * casing. Lite fetches it itself — it decodes the table with `createImageBitmap`, the same reason\n * the texture loader hands over a URL rather than bytes.\n *\n * ## Headless\n *\n * The load uploads cube maps, so a headless app skips it and produces an asset with no textures.\n * The declaration is still parsed, so a headless test still covers the file format.\n */\n\n/**\n * Builds the loader for `.env`, `.hdr`, `.dds`, and `.environment.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createEnvironmentLoader());\n * ```\n *\n * @public\n */\nexport function createEnvironmentLoader(): AssetLoader<EnvironmentAsset> {\n return {\n type: ENVIRONMENT_ASSET_TYPE,\n extensions: [...ENVIRONMENT_FILE_EXTENSIONS, ENVIRONMENT_FILE_EXTENSION],\n async load(ctx: LoaderContext): Promise<EnvironmentAsset> {\n const definition = ctx.address.endsWith(ENVIRONMENT_FILE_EXTENSION)\n ? readDescription(await ctx.fetchJson(), ctx.address)\n : environmentDefinition({ environment: ctx.address });\n const brdfUrl = ctx.app.assets.resolveUrl(resolveBrdfAddress(ctx, definition));\n // The option mapping is plain address arithmetic, so it runs either way; only the load is\n // device-only. Under the null engine the asset reports `gpu: null` (§5).\n const options = toLoadOptions(ctx, definition, brdfUrl);\n if (ctx.app.isHeadless) {\n return new EnvironmentAsset(ctx.address, definition, \"\", null);\n }\n const textures = await loadSceneEnvironment(ctx.app.lite.scene, options);\n return new EnvironmentAsset(ctx.address, definition, brdfUrl, textures);\n },\n };\n}\n\n/**\n * Reads an `.environment.json` over the defaults.\n *\n * @param parsed - The parsed JSON.\n * @param address - The address, for diagnostics.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0709` when the header is missing, or `IGX-0603` when the\n * format version is not readable.\n */\nfunction readDescription(parsed: unknown, address: string): EnvironmentDefinition {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw notAnEnvironment(address);\n }\n // Boundary assertion (coding standards §5.2): the array and `null` cases are gone.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const file = parsed as Record<string, unknown>;\n if (file[\"format\"] !== ENVIRONMENT_FILE_FORMAT) {\n throw notAnEnvironment(address);\n }\n const version = file[\"formatVersion\"];\n if (version !== ENVIRONMENT_FORMAT_VERSION) {\n throw new IgnifxError(\n CoreErrorCode.unsupportedFormatVersion,\n `${address} declares format version ${String(version)}, which this build cannot read.`,\n {\n context: { file: address, version: String(version) },\n hint: `This build reads ${ENVIRONMENT_FILE_FORMAT} version ${String(ENVIRONMENT_FORMAT_VERSION)}.`,\n },\n );\n }\n return environmentDefinition({\n environment: readString(file, \"environment\", \"\"),\n brdfLut: readString(file, \"brdfLut\", \"\"),\n skybox: readString(file, \"skybox\", \"\"),\n skyboxSize: readNumber(file, \"skyboxSize\", 20),\n skyboxEnabled: readBoolean(file, \"skyboxEnabled\", true),\n blur: readNumber(file, \"blur\", 0),\n rotation: readNumber(file, \"rotation\", 0),\n });\n}\n\n/**\n * Builds the \"not an environment file\" failure.\n *\n * @param address - The address that failed.\n * @returns The error to throw.\n */\nfunction notAnEnvironment(address: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${ENVIRONMENT_FILE_FORMAT} file.`, {\n context: { file: address, format: ENVIRONMENT_FILE_FORMAT },\n hint: `An environment description carries { \"format\": \"${ENVIRONMENT_FILE_FORMAT}\", \"formatVersion\": ${String(ENVIRONMENT_FORMAT_VERSION)} }.`,\n });\n}\n\n/**\n * Works out which BRDF lookup table this environment uses: the file's, then the project's, then\n * the built-in default.\n *\n * @param ctx - The loader context, for the settings.\n * @param definition - The declaration.\n * @returns The address.\n */\nfunction resolveBrdfAddress(ctx: LoaderContext, definition: EnvironmentDefinition): string {\n if (definition.brdfLut !== \"\") {\n return definition.brdfLut;\n }\n const settings = ctx.app.settings.section<RenderingSettings>(RENDERING_SETTINGS_SECTION);\n return settings.brdfLut === \"\" ? DEFAULT_BRDF_LUT_ADDRESS : settings.brdfLut;\n}\n\n/**\n * Turns a declaration into the shape `loadEnvironment` takes, resolving every address to a URL.\n *\n * @param ctx - The loader context, for `resolveUrl`.\n * @param definition - The declaration.\n * @param brdfUrl - The already-resolved BRDF table URL.\n * @returns The adapter's options.\n */\nfunction toLoadOptions(\n ctx: LoaderContext,\n definition: EnvironmentDefinition,\n brdfUrl: string,\n): {\n url: string;\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround: boolean;\n} {\n const options: {\n url: string;\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround: boolean;\n } = {\n url: ctx.app.assets.resolveUrl(definition.environment === \"\" ? ctx.address : definition.environment),\n brdfUrl,\n // ignifx never wants Lite's reflective ground plane: a world's ground is an entity with a\n // `MeshRenderer`, and a second one nothing owns would be invisible to every ignifx query.\n skipGround: true,\n };\n if (!definition.skyboxEnabled) {\n options.skipSkybox = true;\n } else if (definition.skybox === \"\") {\n options.skyboxSize = definition.skyboxSize;\n } else {\n options.skyboxUrl = ctx.app.assets.resolveUrl(definition.skybox);\n options.skyboxSize = definition.skyboxSize;\n }\n return options;\n}\n\n/**\n * Reads a string property.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when it is absent or not a string.\n * @returns The value.\n */\nfunction readString(file: Record<string, unknown>, key: string, fallback: string): string {\n const value = file[key];\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Reads a number property.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when it is absent or not a finite number.\n * @returns The value.\n */\nfunction readNumber(file: Record<string, unknown>, key: string, fallback: number): number {\n const value = file[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Reads a boolean property.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when it is absent or not a boolean.\n * @returns The value.\n */\nfunction readBoolean(file: Record<string, unknown>, key: string, fallback: boolean): boolean {\n const value = file[key];\n return typeof value === \"boolean\" ? value : fallback;\n}\n","import { createFontFromBuffer, type Font } from \"@babylonjs/lite\";\n\n/**\n * Font half of the Babylon Lite adapter (`docs/architecture/05-assets-and-loading.md` §5, the\n * `font` row). It is deliberately **not** under `./gpu/`: `createFontFromBuffer`\n * (`index.d.ts` 2527) parses a TTF/OTF byte range into a branded, opaque `Font` and touches no\n * device, so a `FontAsset` is the one rendering asset that loads completely under the null engine.\n * Glyph rasterisation happens later, in the text layer `@ignifx/ui` owns.\n *\n * Everything here is `@internal`.\n *\n * ## What a `Font` is (verified against `@babylonjs/lite@1.27.0`)\n *\n * `interface Font { readonly [fontBrand]: true }` (`index.d.ts` 5359) — a nominal handle with no\n * readable members and no disposer. Nothing has to be released when a font is unloaded; the value\n * is plain JavaScript and the collector reclaims it.\n */\n\n/**\n * The Babylon Lite font handle a `FontAsset` wraps, re-exported under an ignifx name so feature code\n * can name the type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4, coding\n * standards §4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches, and it\n * is excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteFont = Font;\n\n/**\n * Parses a TTF or OTF file into a Lite font.\n *\n * @param bytes - The whole font file, as the asset layer fetched it.\n * @returns The font handle.\n * @throws Whatever Lite's parser throws for a file it cannot read; the asset layer turns that into\n * an `IGX-0505`.\n *\n * @example\n * ```ts\n * const font = createFontFromBytes(await ctx.fetchBytes());\n * ```\n *\n * @internal\n */\nexport function createFontFromBytes(bytes: ArrayBuffer): LiteFont {\n return createFontFromBuffer(bytes);\n}\n","import type { LiteFont } from \"../lite/font.js\";\n\n/**\n * `FontAsset` (`docs/architecture/05-assets-and-loading.md` §5, the `font` row): a parsed TTF or\n * OTF, for world and HUD text.\n *\n * It is the one rendering asset that loads **completely** under the null engine.\n * `createFontFromBuffer` (`index.d.ts` 2527) parses the byte range into a branded, opaque `Font`\n * and touches no device; glyph rasterisation happens later, in the text layer `@ignifx/ui` owns. A\n * font therefore has no GPU half to leave `null` in headless mode, and nothing to release: Lite's\n * `Font` exposes no disposer and holds no GPU resource, so the collector reclaims the value like\n * any other object.\n */\n\n/**\n * The asset type fonts are registered under.\n *\n * @public\n */\nexport const FONT_ASSET_TYPE = \"font\";\n\n/**\n * The address suffixes that select the font loader.\n *\n * @public\n */\nexport const FONT_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".ttf\", \".otf\"]);\n\n/**\n * The Babylon Lite objects a {@link FontAsset} owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @public\n */\nexport interface FontAssetLiteHandles {\n /** The parsed font. Present in headless mode too: parsing needs no device. */\n readonly font: LiteFont;\n}\n\n/**\n * A parsed font file (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @example\n * ```ts\n * const inter = await app.assets.loadAsync<FontAsset>(\"fonts/inter.ttf\");\n * inter.value.address; // \"fonts/inter.ttf\"\n * ```\n *\n * @public\n */\nexport class FontAsset {\n /** The type name the asset service registers fonts under. */\n static assetType: string = FONT_ASSET_TYPE;\n\n /** The address the font was loaded from. */\n readonly address: string;\n\n /** How many bytes the file held, for diagnostics. */\n readonly byteLength: number;\n\n readonly #font: LiteFont;\n\n /**\n * Wraps a parsed font. The `font` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param font - The parsed font.\n * @param byteLength - The file's size in bytes.\n *\n * @internal\n */\n constructor(address: string, font: LiteFont, byteLength: number) {\n this.address = address;\n this.#font = font;\n this.byteLength = byteLength;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch.\n *\n * @returns The parsed font.\n */\n get lite(): FontAssetLiteHandles {\n return { font: this.#font };\n }\n}\n","import { createFontFromBytes } from \"../../lite/font.js\";\nimport { FONT_ASSET_TYPE, FONT_FILE_EXTENSIONS, FontAsset } from \"../font-asset.js\";\nimport type { AssetLoader, LoaderContext } from \"../../assets/types.js\";\n\n/**\n * The `font` asset loader (`docs/architecture/05-assets-and-loading.md` §5, the `font` row).\n *\n * It is the only core rendering loader with no headless branch. `createFontFromBuffer`\n * (`index.d.ts` 2527) parses the byte range and touches no device, so a font loads identically\n * under the null engine and under a real one — which is what makes the whole path, including the\n * fetch, testable in Node.\n *\n * A file Lite cannot parse throws from inside the parser; the asset service retries it and then\n * settles the handle with `IGX-0505`, carrying the parser's own message as `cause`. There is\n * nothing to release on unload: a Lite `Font` is a branded value with no disposer and no GPU\n * resource.\n */\n\n/**\n * Builds the loader for `.ttf` and `.otf` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createFontLoader());\n * ```\n *\n * @public\n */\nexport function createFontLoader(): AssetLoader<FontAsset> {\n return {\n type: FONT_ASSET_TYPE,\n extensions: FONT_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<FontAsset> {\n const bytes = await ctx.fetchBytes();\n return new FontAsset(ctx.address, createFontFromBytes(bytes), bytes.byteLength);\n },\n };\n}\n","import { CoreErrorCode } from \"../../errors/error-codes.js\";\nimport { IgnifxError } from \"../../errors/ignifx-error.js\";\nimport {\n assertMaterialKindSupported,\n buildMaterialAsset,\n MATERIAL_ASSET_TYPE,\n MATERIAL_FILE_EXTENSION,\n MATERIAL_FILE_FORMAT,\n MATERIAL_FORMAT_VERSION,\n MATERIAL_KINDS,\n PBR_TEXTURE_SLOTS,\n pbrMaterialDefinition,\n STANDARD_TEXTURE_SLOTS,\n standardMaterialDefinition,\n} from \"../material-asset.js\";\nimport type { AssetHandle, AssetLoader, LoaderContext } from \"../../assets/types.js\";\nimport type { ColorLike } from \"../../math/types.js\";\nimport type { JsonValue } from \"../../schema/json.js\";\nimport type { MaterialAlphaModeName, MaterialAsset, MaterialDefinition, MaterialKind } from \"../material-asset.js\";\nimport type { TextureAsset } from \"../texture-asset.js\";\n\n/**\n * The `material` asset loader: `.material.json` to `MaterialAsset`\n * (`docs/architecture/05-assets-and-loading.md` §5, `06-serialization-and-scene-format.md` §6).\n *\n * ## The file\n *\n * ```json\n * {\n * \"format\": \"ignifx.material\",\n * \"formatVersion\": 1,\n * \"type\": \"pbr\",\n * \"name\": \"Gold\",\n * \"baseColor\": [1, 0.77, 0.34, 1],\n * \"metallic\": 1,\n * \"roughness\": 0.25,\n * \"baseColorTexture\": { \"$asset\": \"textures/gold-albedo.png\" }\n * }\n * ```\n *\n * Colours are sRGB arrays of four numbers, the same encoding a `color()` schema field uses\n * (`06-serialization-and-scene-format.md` §3), and textures are `{ \"$asset\": … }` references pulled\n * in with `ctx.loadDependency` so their reference counts and their progress fold into this load.\n *\n * ## Missing and malformed values do not fail the load\n *\n * A material is content, and `CONSTITUTION.md` §3.9 wants content problems to degrade rather than\n * stop a game. A property of the wrong type takes its default; a texture that fails to load leaves\n * its slot unbound and the material draws without it. Only two things throw: a file that is not an\n * `ignifx.material` at all (`IGX-0709`), and one that declares a family this build cannot construct\n * (`IGX-0708`).\n */\n\n/**\n * Builds the loader for `.material.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createMaterialLoader());\n * ```\n *\n * @public\n */\nexport function createMaterialLoader(): AssetLoader<MaterialAsset> {\n return {\n type: MATERIAL_ASSET_TYPE,\n extensions: [MATERIAL_FILE_EXTENSION],\n async load(ctx: LoaderContext): Promise<MaterialAsset> {\n const parsed: unknown = await ctx.fetchJson();\n const file = readMaterialFile(parsed, ctx.address);\n const kind = readKind(file, ctx.address);\n assertMaterialKindSupported(kind, ctx.address);\n const slots = kind === \"pbr\" ? PBR_TEXTURE_SLOTS : STANDARD_TEXTURE_SLOTS;\n const addresses = readTextureAddresses(file, slots);\n const textures = await loadTextures(ctx, addresses);\n const definition = kind === \"pbr\" ? readPbr(file, addresses) : readStandard(file, addresses);\n return buildMaterialAsset(definition, textures);\n },\n };\n}\n\n/**\n * Reads and checks a `.material.json`'s header.\n *\n * @param parsed - The parsed JSON.\n * @param address - The address, for diagnostics.\n * @returns The file body.\n * @throws IgnifxError with code `IGX-0709` when the header is missing or `IGX-0603` when the format\n * version is not readable.\n */\nfunction readMaterialFile(parsed: unknown, address: string): Record<string, unknown> {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw notAMaterial(address);\n }\n // Boundary assertion (coding standards §5.2): the array and `null` cases are gone, so what is\n // left is a JSON object read by name.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const file = parsed as Record<string, unknown>;\n if (file[\"format\"] !== MATERIAL_FILE_FORMAT) {\n throw notAMaterial(address);\n }\n const version = file[\"formatVersion\"];\n if (version !== MATERIAL_FORMAT_VERSION) {\n throw new IgnifxError(\n CoreErrorCode.unsupportedFormatVersion,\n `${address} declares format version ${String(version)}, which this build cannot read.`,\n {\n context: { file: address, version: String(version) },\n hint: `This build reads ${MATERIAL_FILE_FORMAT} version ${String(MATERIAL_FORMAT_VERSION)}.`,\n },\n );\n }\n return file;\n}\n\n/**\n * Builds the \"not a material file\" failure.\n *\n * @param address - The address that failed.\n * @returns The error to throw.\n */\nfunction notAMaterial(address: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${MATERIAL_FILE_FORMAT} file.`, {\n context: { file: address, format: MATERIAL_FILE_FORMAT },\n hint: `A material file carries { \"format\": \"${MATERIAL_FILE_FORMAT}\", \"formatVersion\": ${String(MATERIAL_FORMAT_VERSION)} }.`,\n });\n}\n\n/**\n * Reads the file's `type` discriminator.\n *\n * @param file - The file body.\n * @param address - The address, for diagnostics.\n * @returns The declared family; `\"pbr\"` when the file names none.\n * @throws IgnifxError with code `IGX-0708` when the file names a family that is not a family.\n */\nfunction readKind(file: Record<string, unknown>, address: string): MaterialKind {\n const declared = file[\"type\"];\n if (declared === undefined) {\n return \"pbr\";\n }\n for (const kind of MATERIAL_KINDS) {\n if (declared === kind) {\n return kind;\n }\n }\n throw new IgnifxError(\n CoreErrorCode.unsupportedMaterialKind,\n `${address} declares the material kind ${JSON.stringify(declared)}, which this build cannot construct.`,\n {\n context: { asset: address, kind: JSON.stringify(declared) },\n hint: `Declare one of ${MATERIAL_KINDS.join(\", \")}.`,\n },\n );\n}\n\n/**\n * Collects the `{ \"$asset\": … }` addresses the file bound to texture slots, in slot order.\n *\n * @param file - The file body.\n * @param slots - The slot names this family understands.\n * @returns Slot name to address, for the slots the file bound.\n */\nfunction readTextureAddresses(file: Record<string, unknown>, slots: readonly string[]): Record<string, string> {\n const addresses: Record<string, string> = {};\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index];\n if (slot === undefined) {\n continue;\n }\n const value = file[slot];\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n continue;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a JSON object read by name.\n const address = (value as Record<string, unknown>)[\"$asset\"];\n if (typeof address === \"string\" && address !== \"\") {\n addresses[slot] = address;\n }\n }\n return addresses;\n}\n\n/**\n * Loads every bound texture as a dependency, in slot order.\n *\n * @remarks\n * A texture that fails to load leaves its slot unbound rather than failing the material: a missing\n * normal map is a visual defect, not a reason for a level not to start.\n *\n * @param ctx - The loader context.\n * @param addresses - Slot name to address.\n * @returns The handles, in the same order as `Object.keys(addresses)`.\n */\nasync function loadTextures(\n ctx: LoaderContext,\n addresses: Record<string, string>,\n): Promise<readonly AssetHandle<TextureAsset>[]> {\n const slots = Object.keys(addresses);\n const requests: Promise<AssetHandle<TextureAsset> | null>[] = [];\n for (let index = 0; index < slots.length; index += 1) {\n const address = addresses[slots[index] ?? \"\"] ?? \"\";\n requests.push(ctx.loadDependency<TextureAsset>(address).catch((): null => null));\n }\n const settled = await Promise.all(requests);\n const handles: AssetHandle<TextureAsset>[] = [];\n for (let index = 0; index < settled.length; index += 1) {\n const handle = settled[index];\n if (handle !== null && handle !== undefined) {\n handles.push(handle);\n }\n }\n return handles;\n}\n\n/**\n * Reads the PBR properties over their defaults.\n *\n * @param file - The file body.\n * @param textures - Slot name to address.\n * @returns The declaration.\n */\nfunction readPbr(file: Record<string, unknown>, textures: Record<string, string>): MaterialDefinition {\n return pbrMaterialDefinition({\n name: readString(file, \"name\", \"\"),\n baseColor: readColor(file, \"baseColor\", { r: 1, g: 1, b: 1, a: 1 }),\n metallic: readNumber(file, \"metallic\", 1),\n roughness: readNumber(file, \"roughness\", 1),\n normalScale: readNumber(file, \"normalScale\", 1),\n emissive: readColor(file, \"emissive\", { r: 0, g: 0, b: 0, a: 1 }),\n occlusionStrength: readNumber(file, \"occlusionStrength\", 1),\n alphaMode: readAlphaMode(file),\n alphaCutoff: readNumber(file, \"alphaCutoff\", 0.5),\n alpha: readNumber(file, \"alpha\", 1),\n doubleSided: readBoolean(file, \"doubleSided\", false),\n unlit: readBoolean(file, \"unlit\", false),\n environmentIntensity: readNumber(file, \"environmentIntensity\", 1),\n textures,\n });\n}\n\n/**\n * Reads the Standard properties over their defaults.\n *\n * @param file - The file body.\n * @param textures - Slot name to address.\n * @returns The declaration.\n */\nfunction readStandard(file: Record<string, unknown>, textures: Record<string, string>): MaterialDefinition {\n return standardMaterialDefinition({\n name: readString(file, \"name\", \"\"),\n diffuse: readColor(file, \"diffuse\", { r: 1, g: 1, b: 1, a: 1 }),\n specular: readColor(file, \"specular\", { r: 1, g: 1, b: 1, a: 1 }),\n specularPower: readNumber(file, \"specularPower\", 64),\n emissive: readColor(file, \"emissive\", { r: 0, g: 0, b: 0, a: 1 }),\n alpha: readNumber(file, \"alpha\", 1),\n alphaCutoff: readNumber(file, \"alphaCutoff\", 0),\n doubleSided: readBoolean(file, \"doubleSided\", false),\n unlit: readBoolean(file, \"unlit\", false),\n textures,\n });\n}\n\n/**\n * Reads the `alphaMode` discriminator.\n *\n * @param file - The file body.\n * @returns The declared mode, or `\"opaque\"`.\n */\nfunction readAlphaMode(file: Record<string, unknown>): MaterialAlphaModeName {\n const value = file[\"alphaMode\"];\n return value === \"mask\" || value === \"blend\" ? value : \"opaque\";\n}\n\n/**\n * Reads a number property.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when it is absent or not a finite number.\n * @returns The value.\n */\nfunction readNumber(file: Record<string, unknown>, key: string, fallback: number): number {\n const value = file[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Reads a boolean property.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when it is absent or not a boolean.\n * @returns The value.\n */\nfunction readBoolean(file: Record<string, unknown>, key: string, fallback: boolean): boolean {\n const value = file[key];\n return typeof value === \"boolean\" ? value : fallback;\n}\n\n/**\n * Reads a string property.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when it is absent or not a string.\n * @returns The value.\n */\nfunction readString(file: Record<string, unknown>, key: string, fallback: string): string {\n const value = file[key];\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Reads an sRGB colour written as `[r, g, b]` or `[r, g, b, a]`.\n *\n * @param file - The file body.\n * @param key - The property name.\n * @param fallback - What to use when the property is absent or malformed.\n * @returns The colour.\n */\nfunction readColor(file: Record<string, unknown>, key: string, fallback: ColorLike): ColorLike {\n const value: unknown = file[key];\n if (!Array.isArray(value) || value.length < 3) {\n return fallback;\n }\n const channels: readonly JsonValue[] = value;\n return {\n r: channel(channels[0], fallback.r),\n g: channel(channels[1], fallback.g),\n b: channel(channels[2], fallback.b),\n a: channel(channels[3], 1),\n };\n}\n\n/**\n * Reads one colour channel.\n *\n * @param value - The JSON element.\n * @param fallback - What to use when it is not a finite number.\n * @returns The channel.\n */\nfunction channel(value: JsonValue | undefined, fallback: number): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n","import { addToScene, cloneTransformNode, loadGltf, removeFromScene } from \"@babylonjs/lite\";\nimport type { AnimationGroup, AssetContainer, EngineContext, SceneContext, SceneNode, Skeleton } from \"@babylonjs/lite\";\n\n/**\n * glTF half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.4): loading a\n * `.glb` into an asset container, and instantiating that container under an entity node.\n *\n * Everything here is `@internal`. `loadGltf` uploads vertex buffers and textures, so the module is\n * GPU-only.\n *\n * ## What a container holds (verified against `@babylonjs/lite@1.27.0`)\n *\n * `loadGltf(engine, source)` (`index.d.ts` 6821) takes a URL, an `ArrayBuffer`, or a `Blob` and\n * resolves to an `AssetContainer` (`index.d.ts` 653) whose `entities` is `[rootTransformNode]` for\n * glTF. The ignifx asset layer fetches the bytes itself — that is where progress reporting and\n * `AbortSignal` support live (`docs/architecture/05-assets-and-loading.md`) — and hands Lite an\n * `ArrayBuffer`, so this adapter never fetches.\n *\n * ## Animation groups are stripped, not ticked\n *\n * `addToScene` pushes a container's `animationGroups` onto the scene and installs a before-render\n * hook that calls `tickAnimation` for each one (`lib/scene/scene-core.js`). ADR-0003 says ignifx\n * owns time, so {@link takeAnimationGroups} removes them from the container *before* it is added:\n * Lite then registers no hook, and ignifx's animation system advances the clips itself.\n *\n * ## Instancing\n *\n * `cloneTransformNode` on the container root deep-clones the transform hierarchy while every mesh\n * in it shares the original's `_gpu` wrapper and bumps its reference count\n * (`lib/scene/transform-node.js`) — so N instances of a model upload one copy of the geometry. Lights\n * inside the subtree are shallow-copied as plain objects rather than cloned; glTF cameras are only\n * present at all when `enableGltfCameras()` ran before the load.\n */\n\n/**\n * The Babylon Lite asset container a `ModelAsset` holds, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteAssetContainer = AssetContainer;\n\n/**\n * A Babylon Lite animation clip, re-exported under an ignifx name. `Model.animations` hands these\n * to `@ignifx/3d`'s animator, which owns advancement (ADR-0003).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @beta\n */\nexport type LiteAnimationGroup = AnimationGroup;\n\n/**\n * A Babylon Lite skeleton, re-exported under an ignifx name. Present on a container only when\n * `enableBoneControl()` ran before the load (`index.d.ts` 653).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @beta\n */\nexport type LiteSkeleton = Skeleton;\n\n/** The suffix `cloneTransformNode` appends to every cloned node's name. */\nconst CLONE_SUFFIX = \"_clone\";\n\n/**\n * An instantiated model: the cloned subtree, the nodes worth addressing by name, and the clips.\n *\n * @internal\n */\nexport interface ModelInstance {\n /** The cloned container root, parented under the entity's node. */\n readonly root: SceneNode;\n /** Every named node in the clone, by its glTF node name. Later duplicates of a name are ignored. */\n readonly nodesByName: ReadonlyMap<string, SceneNode>;\n}\n\n/**\n * Loads a glTF or GLB asset from bytes already in memory.\n *\n * @param engine - The engine that will own the GPU resources.\n * @param bytes - The `.glb` or `.gltf` bytes, as fetched by the asset layer.\n * @returns The container. Instantiate it with {@link instantiateContainer}.\n *\n * @example\n * ```ts\n * const bytes = await (await fetch(url, { signal })).arrayBuffer();\n * const container = await loadGltfFromBytes(engine, bytes);\n * ```\n *\n * @internal\n */\nexport function loadGltfFromBytes(engine: EngineContext, bytes: ArrayBuffer): Promise<AssetContainer> {\n return loadGltf(engine, bytes);\n}\n\n/**\n * Loads a glTF or GLB asset from a URL, letting Lite do the fetching.\n *\n * @remarks\n * Used only where the asset layer's progress and cancellation are not wanted — benchmarks and\n * tests. Production loading goes through {@link loadGltfFromBytes}.\n *\n * @param engine - The engine that will own the GPU resources.\n * @param url - Where to fetch the asset from.\n * @returns The container.\n *\n * @internal\n */\nexport function loadGltfFromUrl(engine: EngineContext, url: string): Promise<AssetContainer> {\n return loadGltf(engine, url);\n}\n\n/**\n * Removes a container's animation clips so that adding it to a scene does not make Lite tick them.\n *\n * @remarks\n * Call this **before** {@link addContainerToScene} or {@link instantiateContainer}. ADR-0003: ignifx\n * drives every clock, including animation.\n *\n * @param container - The freshly loaded container.\n * @returns The clips that were removed, in load order. Empty when the file declared none.\n *\n * @internal\n */\nexport function takeAnimationGroups(container: AssetContainer): readonly AnimationGroup[] {\n const groups = container.animationGroups;\n if (groups === undefined || groups.length === 0) {\n return [];\n }\n const taken = groups.slice();\n container.animationGroups = [];\n return taken;\n}\n\n/**\n * Clones a container's subtree under an entity node, ready to be added to a scene.\n *\n * @remarks\n * The container itself stays pristine and acts as the template, so the first instance costs a clone\n * just like the tenth and the asset can outlive any one of them. Every mesh in the clone shares the\n * template's GPU buffers.\n *\n * @param container - The loaded container.\n * @param parent - The entity's transform node, or `null` for world space.\n * @returns The cloned root and its named nodes, or `null` when the container has no scene-node\n * root — a file that declared only lights, for instance.\n *\n * @internal\n */\nexport function instantiateContainer(container: AssetContainer, parent: SceneNode | null): ModelInstance | null {\n const entities = container.entities;\n let template: SceneNode | null = null;\n for (let i = 0; i < entities.length; i++) {\n const entity = entities[i];\n if (entity !== undefined && !(\"lightType\" in entity)) {\n template = entity;\n break;\n }\n }\n if (template === null) {\n return null;\n }\n const root = cloneTransformNode(template);\n root.parent = parent;\n const nodesByName = new Map<string, SceneNode>();\n collectNames(root, nodesByName);\n return { root, nodesByName };\n}\n\n/**\n * Adds a whole container to a scene, the simple path for a model with exactly one instance.\n *\n * @param scene - The render scene.\n * @param container - The container to add.\n *\n * @internal\n */\nexport function addContainerToScene(scene: SceneContext, container: AssetContainer): void {\n addToScene(scene, container);\n}\n\n/**\n * Removes a whole container from a scene, releasing every mesh that has left its last scene.\n *\n * @param scene - The render scene.\n * @param container - The container to remove.\n *\n * @internal\n */\nexport function removeContainerFromScene(scene: SceneContext, container: AssetContainer): void {\n removeFromScene(scene, container);\n}\n\n/**\n * Indexes a cloned subtree by node name.\n *\n * @remarks\n * `cloneTransformNode` appends `\"_clone\"` to every name it copies\n * (`lib/scene/transform-node.js`), so the suffix is stripped here and the map is keyed by the\n * original glTF node names the `Model` component promises.\n *\n * @param node - The subtree root.\n * @param out - The map to fill.\n */\nfunction collectNames(node: SceneNode, out: Map<string, SceneNode>): void {\n const name = node.name.endsWith(CLONE_SUFFIX) ? node.name.slice(0, -CLONE_SUFFIX.length) : node.name;\n if (name.length > 0 && !out.has(name)) {\n out.set(name, node);\n }\n const children = node.children;\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child !== undefined) {\n collectNames(child, out);\n }\n }\n}\n","import { instantiateContainer, removeContainerFromScene, takeAnimationGroups } from \"../lite/gpu/gltf.js\";\nimport type { LiteAnimationGroup, LiteAssetContainer, LiteSkeleton, ModelInstance } from \"../lite/gpu/gltf.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\nimport type { LiteScene } from \"../lite/scene.js\";\n\n/**\n * `ModelAsset` (`docs/architecture/05-assets-and-loading.md` §5 and §6,\n * `07-rendering.md` §2.4): the loaded glTF container a `Model` component instantiates.\n *\n * ## The container is a template, not a scene member\n *\n * `loadGltf` resolves to an `AssetContainer` whose `entities` is `[rootTransformNode]`\n * (`index.d.ts` 653). ignifx never adds that container to a scene. Each `Model` clones it instead\n * (`cloneTransformNode`), which deep-copies the transform hierarchy while every mesh shares the\n * original's GPU buffers under a reference count — so ten instances of a model upload one copy of\n * the geometry (`src/lite/gpu/gltf.ts`). Keeping the container out of the scene is also what makes\n * the first instance cost the same as the tenth, and what lets the asset outlive any one of them.\n *\n * ## Animation groups are taken, not ticked\n *\n * `addToScene` would register a container's `animationGroups` with Lite's own animation manager and\n * install a before-render hook for them. ADR-0003 says ignifx owns every clock, so the loader\n * removes them from the container the moment it is loaded and the asset keeps them\n * ({@link ModelAsset.animations}). Phase 2 exposes them and advances nothing; `@ignifx/3d`'s\n * animator is what plays them.\n *\n * ## Instance counting\n *\n * Instances are counted so the template's GPU resources live until the last instance and the asset\n * handle are gone (`05-assets-and-loading.md` §6). {@link ModelAsset.retainInstance} and\n * {@link ModelAsset.releaseInstance} are that counter; `Model` calls them, and\n * {@link ModelAsset.instanceCount} is what a test asserts on.\n *\n * ## Headless\n *\n * `loadGltf` throws a `TypeError` under the null engine — it reaches for `engine._device` while\n * uploading (ADR-0002 Validation) — so a headless load skips it entirely and produces an asset with\n * `lite.container === null`. A `Model` that holds one keeps its fields, reports an empty `nodes`\n * map, and touches no scene (`07-rendering.md` §6).\n */\n\n/**\n * The asset type models are registered under.\n *\n * @public\n */\nexport const MODEL_ASSET_TYPE = \"model\";\n\n/**\n * The address suffixes that select the model loader.\n *\n * @public\n */\nexport const MODEL_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".glb\", \".gltf\"]);\n\n/**\n * The Babylon Lite objects a {@link ModelAsset} owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @public\n */\nexport interface ModelAssetLiteHandles {\n /** The template container, or `null` under a headless app. */\n readonly container: LiteAssetContainer | null;\n}\n\n/**\n * One instantiated copy of a model, as a `Model` component holds it.\n *\n * @public\n */\nexport interface ModelInstantiation {\n /** The cloned container root, parented under the entity's node. */\n readonly root: LiteSceneNode;\n /** Every named node in the clone, keyed by its glTF node name. */\n readonly nodes: ReadonlyMap<string, LiteSceneNode>;\n}\n\n/**\n * A loaded glTF or GLB file (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @example\n * ```ts\n * const hero = await app.assets.loadAsync<ModelAsset>(\"models/hero.glb\");\n * hero.value.animations.map((clip) => clip.name);\n * ```\n *\n * @public\n */\nexport class ModelAsset {\n /** The type name the asset service registers models under. */\n static assetType: string = MODEL_ASSET_TYPE;\n\n /** The address the model was loaded from. */\n readonly address: string;\n\n /**\n * The clips the file declared, stripped from the container so Lite never ticks them.\n *\n * @remarks\n * Unstable: these are Lite's own animation groups, handed on to `@ignifx/3d`'s animator, and they\n * are excluded from the stability guarantees of `CONSTITUTION.md` Article IV. A `Model` re-binds\n * them per instance when the animation system lands; in Phase 2 they are read-only metadata.\n *\n * @beta\n */\n readonly animations: readonly LiteAnimationGroup[];\n\n /**\n * The skeletons the file declared. Empty unless the `boneControl` rendering feature was on before\n * the load, because Lite builds them only then (`index.d.ts` 653).\n *\n * @beta\n */\n readonly skeletons: readonly LiteSkeleton[];\n\n readonly #scene: LiteScene | null;\n\n #container: LiteAssetContainer | null;\n\n #instances = 0;\n\n /**\n * Wraps a loaded container. The `model` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param container - The template container, or `null` when the app is headless.\n * @param animations - The clips taken off the container.\n * @param skeletons - The skeletons the loader found.\n * @param scene - The scene the container is released through, or `null` when headless.\n *\n * @internal\n */\n constructor(\n address: string,\n container: LiteAssetContainer | null,\n animations: readonly LiteAnimationGroup[],\n skeletons: readonly LiteSkeleton[],\n scene: LiteScene | null,\n ) {\n this.address = address;\n this.#container = container;\n this.animations = animations;\n this.skeletons = skeletons;\n this.#scene = scene;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch.\n *\n * @returns The template container, or `null` under a headless app.\n */\n get lite(): ModelAssetLiteHandles {\n return { container: this.#container };\n }\n\n /**\n * How many `Model` components currently hold a copy of this template.\n *\n * @returns The live instance count.\n */\n get instanceCount(): number {\n return this.#instances;\n }\n\n /**\n * Clones the template under an entity's node.\n *\n * @param parent - The entity's transform node, or `null` for world space.\n * @returns The cloned root and its named nodes, or `null` when there is nothing to clone — a\n * headless app, or a file that declared only lights.\n */\n instantiate(parent: LiteSceneNode | null): ModelInstantiation | null {\n const container = this.#container;\n if (container === null) {\n return null;\n }\n const instance: ModelInstance | null = instantiateContainer(container, parent);\n if (instance === null) {\n return null;\n }\n return { root: instance.root, nodes: instance.nodesByName };\n }\n\n /** Records that one more `Model` holds a copy. */\n retainInstance(): void {\n this.#instances += 1;\n }\n\n /** Records that one fewer `Model` holds a copy. Releasing below zero is a no-op. */\n releaseInstance(): void {\n if (this.#instances > 0) {\n this.#instances -= 1;\n }\n }\n\n /**\n * Releases the template's GPU resources.\n *\n * @remarks\n * The container was never added to a scene, so the round trip `removeFromScene` needs is the same\n * one `MeshAsset.dispose` performs: this hands it to the scene and takes it straight back out,\n * which drops its share of every buffer. Clones still in a scene keep theirs. Calling it twice is\n * a no-op, and it is a no-op under a headless app.\n */\n dispose(): void {\n const container = this.#container;\n const scene = this.#scene;\n this.#container = null;\n if (container !== null && scene !== null) {\n removeContainerFromScene(scene, container);\n }\n }\n\n /** Releases the template when the asset leaves a `using` block. */\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n/**\n * Strips a freshly loaded container's clips and skeletons and wraps it as an asset.\n *\n * @param address - The address it was loaded from.\n * @param container - The container, or `null` when the app is headless.\n * @param scene - The scene the container is released through, or `null` when headless.\n * @returns The asset.\n *\n * @internal\n */\nexport function createModelAsset(\n address: string,\n container: LiteAssetContainer | null,\n scene: LiteScene | null,\n): ModelAsset {\n if (container === null) {\n return new ModelAsset(address, null, [], [], null);\n }\n const animations = takeAnimationGroups(container);\n const skeletons = container.skeletons ?? [];\n return new ModelAsset(address, container, animations, skeletons, scene);\n}\n","import { loadGltfFromBytes } from \"../../lite/gpu/gltf.js\";\nimport { createModelAsset, MODEL_ASSET_TYPE, MODEL_FILE_EXTENSIONS } from \"../model-asset.js\";\nimport type { AssetLoader, LoaderContext } from \"../../assets/types.js\";\nimport type { ModelAsset } from \"../model-asset.js\";\n\n/**\n * The `model` asset loader (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * ## Bytes, not a URL\n *\n * `loadGltf` accepts a URL, an `ArrayBuffer`, or a `Blob`. ignifx hands it an `ArrayBuffer` fetched\n * through `ctx.fetchBytes`, because that is where progress reporting, `AbortSignal` support, the\n * priority queue, and the retry policy live (§5). A `.glb` is one file, so this is lossless.\n *\n * A `.gltf` with **external** buffers and images is the one case where it is not: Lite would have to\n * resolve those relative URLs itself, which it can only do when it did the fetching. Phase 2 loads\n * the container from bytes either way and therefore supports self-contained `.gltf` files and\n * `.glb`; a `.gltf` with siblings fails inside Lite and surfaces as `IGX-0505`. `.glb` is what the\n * asset pipeline produces, and the fix — passing the URL through for that one shape — is a\n * three-line change whenever a project needs it.\n *\n * ## Headless\n *\n * `loadGltf` throws a `TypeError` under the null engine: it uploads while parsing and reaches for\n * `engine._device` (ADR-0002 Validation). So a headless load skips it entirely and produces an\n * asset with no container — the `gpu: null` shape §5 requires — rather than failing. The bytes are\n * still fetched, so a headless test still exercises the address, the manifest, and the byte\n * counters.\n */\n\n/**\n * Builds the loader for `.glb` and `.gltf` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createModelLoader());\n * ```\n *\n * @public\n */\nexport function createModelLoader(): AssetLoader<ModelAsset> {\n return {\n type: MODEL_ASSET_TYPE,\n extensions: MODEL_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<ModelAsset> {\n const bytes = await ctx.fetchBytes();\n if (ctx.app.isHeadless) {\n return createModelAsset(ctx.address, null, null);\n }\n const container = await loadGltfFromBytes(ctx.lite.engine, bytes);\n return createModelAsset(ctx.address, container, ctx.app.lite.scene);\n },\n unload(value: ModelAsset): void {\n value.dispose();\n },\n };\n}\n","import { acquireTexture, loadTexture2D, releaseTexture } from \"@babylonjs/lite\";\nimport type { EngineContext, Texture2D, Texture2DOptions } from \"@babylonjs/lite\";\n\n/**\n * Texture half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §7). Loading\n * uploads to the device, so this module is GPU-only.\n *\n * Everything here is `@internal`.\n *\n * ## Lifetime (verified against `@babylonjs/lite@1.27.0` `lib/resource/gpu-pool.js`)\n *\n * A `Texture2D` has no `dispose`. Lite keeps a process-wide reference count keyed by the underlying\n * `GPUTexture`: `acquireTexture` increments it, `releaseTexture` decrements it and destroys the\n * texture when it reaches zero, returning whether it did. A texture that was never acquired starts\n * at an implicit count of one, so a single `releaseTexture` frees it. This is the mechanism\n * `docs/architecture/07-rendering.md` §7 means by \"release texture handles through Lite's resource\n * pool\", and it is why the asset layer — not the material — owns a texture's lifetime.\n *\n * ## Colour space\n *\n * `srgb: true` picks an `rgba8unorm-srgb` format so the GPU decodes to linear when sampling. Base\n * colour and emissive textures need it; normal, ORM, and data textures must not have it\n * (`index.d.ts` 12911).\n */\n\n/**\n * The Babylon Lite texture a `TextureAsset` wraps, re-exported under an ignifx name so feature code\n * can name the type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4, coding\n * standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteTexture2D = Texture2D;\n\n/**\n * The sampler, mipmap, colour-space, and decode options `loadTexture2D` accepts\n * (`index.d.ts` 12911), re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteTexture2DOptions = Texture2DOptions;\n\n/**\n * Loads a 2D texture from a URL.\n *\n * @param engine - The engine that owns the GPU texture.\n * @param url - Where to fetch it from.\n * @param options - Sampler, mipmap, colour-space, and decode options.\n * @returns The texture. Its reference count starts at an implicit one.\n *\n * @example\n * ```ts\n * const albedo = await loadTexture(engine, \"textures/hero-albedo.png\", { srgb: true });\n * ```\n *\n * @internal\n */\nexport function loadTexture(engine: EngineContext, url: string, options?: Texture2DOptions): Promise<Texture2D> {\n return loadTexture2D(engine, url, options);\n}\n\n/**\n * Claims a share of a texture, so a later {@link releaseTextureHandle} by someone else does not\n * destroy it.\n *\n * @param texture - The texture to retain.\n *\n * @internal\n */\nexport function retainTexture(texture: Texture2D): void {\n acquireTexture(texture);\n}\n\n/**\n * Gives up a share of a texture, destroying it when the last share goes.\n *\n * @param texture - The texture to release.\n * @returns `true` when this call destroyed the underlying `GPUTexture`.\n *\n * @internal\n */\nexport function releaseTextureHandle(texture: Texture2D): boolean {\n return releaseTexture(texture);\n}\n","import { releaseTextureHandle, retainTexture } from \"../lite/gpu/texture.js\";\nimport type { LiteTexture2D, LiteTexture2DOptions } from \"../lite/gpu/texture.js\";\nimport type { JsonObject } from \"../schema/json.js\";\n\n/**\n * `TextureAsset` (`docs/architecture/05-assets-and-loading.md` §5, `07-rendering.md` §7): a GPU\n * texture plus the import options the build recorded for it.\n *\n * ## Lifetime, and why the loader does not `acquireTexture`\n *\n * Lite reference-counts `GPUTexture`s in a process-wide pool keyed by the underlying texture\n * (`lib/resource/gpu-pool.js`): `acquireTexture` increments, `releaseTexture` decrements and\n * destroys at zero, and **a texture that was never acquired starts at an implicit count of one**.\n * A freshly loaded texture is therefore already owned once, by the asset that loaded it. Calling\n * `acquireTexture` in the loader — which `07-rendering.md` §7 could be read as asking for — would\n * put the count at two and make the matching `releaseTexture` on unload free nothing: a leak, not a\n * safety net. So the loader acquires nothing and {@link TextureAsset.releaseGpu} releases the one\n * implicit share when the asset is unloaded.\n *\n * Sharing is expressed one level up instead. A `MaterialAsset` that samples a texture pulls it in\n * with `ctx.loadDependency`, which retains the *asset handle*; the texture's GPU share is released\n * only when the last asset holding that handle is collected. That is the same rule every other\n * dependency follows, and it is observable through `handle.refCount`.\n * {@link TextureAsset.retainGpu} exists for the rare case where a Lite object outlives its asset.\n *\n * ## Headless\n *\n * `loadTexture2D` uploads through `engine._device`, which the null engine has none of, so a\n * headless load produces an asset with `lite.texture === null` — the `gpu: null` shape\n * `05-assets-and-loading.md` §5 requires of every GPU loader.\n */\n\n/**\n * The asset type textures are registered under.\n *\n * @public\n */\nexport const TEXTURE_ASSET_TYPE = \"texture\";\n\n/**\n * The import options a texture's `.meta.json` sidecar can declare, under its `texture` key\n * (`docs/architecture/05-assets-and-loading.md` §7).\n *\n * @remarks\n * They are the sampler and decode options, not scene state: two materials that sample one address\n * get one texture with one set of options, because the cache is keyed by address.\n *\n * @example\n * ```json\n * { \"texture\": { \"srgb\": true, \"addressModeU\": \"clamp-to-edge\" } }\n * ```\n *\n * @public\n */\nexport interface TextureImportOptions {\n /** Decode to linear on sample (`rgba8unorm-srgb`). Base colour and emissive want it; data maps must not. */\n readonly srgb: boolean;\n /** Generate a mip chain. Lite defaults to `true`. */\n readonly mipMaps: boolean;\n /** Address mode along U. */\n readonly addressModeU: string;\n /** Address mode along V. */\n readonly addressModeV: string;\n /** Minification filter. */\n readonly minFilter: string;\n /** Magnification filter. */\n readonly magFilter: string;\n /** Flip the image vertically at upload. Lite defaults to `true`, matching Babylon.js. */\n readonly invertY: boolean;\n /** Premultiply alpha at decode time; for atlases drawn with a premultiplied blend pipeline. */\n readonly premultiplyAlpha: boolean;\n}\n\n/**\n * The Babylon Lite objects a {@link TextureAsset} owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @public\n */\nexport interface TextureAssetLiteHandles {\n /** The GPU texture, or `null` under a headless app. */\n readonly texture: LiteTexture2D | null;\n}\n\n/**\n * A loaded 2D texture (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @example\n * ```ts\n * const albedo = await app.assets.loadAsync<TextureAsset>(\"textures/hero-albedo.png\");\n * albedo.value.options.srgb; // what the .meta.json sidecar asked for\n * ```\n *\n * @public\n */\nexport class TextureAsset {\n /** The type name the asset service registers textures under. */\n static assetType: string = TEXTURE_ASSET_TYPE;\n\n /** The address the texture was loaded from. */\n readonly address: string;\n\n /** The resolved import options, sidecar values merged onto the defaults. */\n readonly options: TextureImportOptions;\n\n #texture: LiteTexture2D | null;\n\n /**\n * Wraps a loaded texture. The `texture` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param texture - The GPU texture, or `null` when the app is headless.\n * @param options - The resolved import options.\n *\n * @internal\n */\n constructor(address: string, texture: LiteTexture2D | null, options: TextureImportOptions) {\n this.address = address;\n this.#texture = texture;\n this.options = options;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch.\n *\n * @returns The GPU texture, or `null` under a headless app.\n */\n get lite(): TextureAssetLiteHandles {\n return { texture: this.#texture };\n }\n\n /**\n * Whether the GPU texture has been given up.\n *\n * @returns `true` once {@link TextureAsset.releaseGpu} has run.\n */\n get isReleased(): boolean {\n return this.#texture === null;\n }\n\n /**\n * Claims an extra share of the GPU texture, so releasing the asset does not destroy it.\n *\n * @remarks\n * Only needed when a Lite object has to outlive the asset that loaded it. Ordinary sharing goes\n * through `ctx.loadDependency`, which counts the asset handle instead.\n */\n retainGpu(): void {\n const texture = this.#texture;\n if (texture !== null) {\n retainTexture(texture);\n }\n }\n\n /**\n * Gives up the asset's share of the GPU texture, destroying it when it was the last one. Calling\n * it twice is a no-op, and it is a no-op under a headless app.\n *\n * @returns `true` when this call destroyed the underlying `GPUTexture`.\n */\n releaseGpu(): boolean {\n const texture = this.#texture;\n this.#texture = null;\n return texture === null ? false : releaseTextureHandle(texture);\n }\n}\n\n/**\n * The import options a texture gets when its sidecar names none: Lite's own defaults, with `srgb`\n * off so that a data map is never silently decoded.\n *\n * @returns A fresh option set.\n *\n * @internal\n */\nexport function defaultTextureImportOptions(): TextureImportOptions {\n return {\n srgb: false,\n mipMaps: true,\n addressModeU: \"repeat\",\n addressModeV: \"repeat\",\n minFilter: \"linear\",\n magFilter: \"linear\",\n invertY: true,\n premultiplyAlpha: false,\n };\n}\n\n/**\n * Reads the `texture` block of a `.meta.json` sidecar over the defaults.\n *\n * @remarks\n * Unknown keys and values of the wrong type are ignored rather than rejected: a sidecar is written\n * by hand and shared with other tools, and a typo in an optional import hint must not stop a game\n * from starting (`CONSTITUTION.md` §3.9 — the asset still loads, with the documented default).\n *\n * @param meta - The whole sidecar, or `null` when the manifest recorded none.\n * @returns The resolved options.\n *\n * @internal\n */\nexport function readTextureImportOptions(meta: JsonObject | null): TextureImportOptions {\n const defaults = defaultTextureImportOptions();\n const raw = meta === null ? undefined : meta[TEXTURE_ASSET_TYPE];\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return defaults;\n }\n // Boundary assertion (coding standards §5.2): the array and `null` cases are already gone, so\n // what is left is a JSON object, which the readers below index by name.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const block = raw as Record<string, unknown>;\n return {\n srgb: readBoolean(block, \"srgb\", defaults.srgb),\n mipMaps: readBoolean(block, \"mipMaps\", defaults.mipMaps),\n addressModeU: readString(block, \"addressModeU\", defaults.addressModeU),\n addressModeV: readString(block, \"addressModeV\", defaults.addressModeV),\n minFilter: readString(block, \"minFilter\", defaults.minFilter),\n magFilter: readString(block, \"magFilter\", defaults.magFilter),\n invertY: readBoolean(block, \"invertY\", defaults.invertY),\n premultiplyAlpha: readBoolean(block, \"premultiplyAlpha\", defaults.premultiplyAlpha),\n };\n}\n\n/**\n * Turns the resolved options into the shape `loadTexture2D` takes.\n *\n * @remarks\n * The sampler strings are handed to Lite as declared; WebGPU rejects a mode or filter it does not\n * know, and that failure is a clearer signal than an ignored option would be.\n *\n * @param options - The resolved import options.\n * @returns Lite's options.\n *\n * @internal\n */\nexport function toLiteTextureOptions(options: TextureImportOptions): LiteTexture2DOptions {\n return {\n srgb: options.srgb,\n mipMaps: options.mipMaps,\n // Boundary assertion (coding standards §5.2): the sidecar is JSON, so the sampler modes arrive\n // as plain strings; WebGPU validates them when the sampler is created.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n addressModeU: options.addressModeU as GPUAddressMode,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n addressModeV: options.addressModeV as GPUAddressMode,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n minFilter: options.minFilter as GPUFilterMode,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n magFilter: options.magFilter as GPUFilterMode,\n invertY: options.invertY,\n premultiplyAlpha: options.premultiplyAlpha,\n };\n}\n\n/**\n * Reads a boolean out of a sidecar block.\n *\n * @param block - The sidecar sub-object.\n * @param key - The property name.\n * @param fallback - What to use when the property is absent or not a boolean.\n * @returns The value.\n */\nfunction readBoolean(block: Record<string, unknown>, key: string, fallback: boolean): boolean {\n const value = block[key];\n return typeof value === \"boolean\" ? value : fallback;\n}\n\n/**\n * Reads a string out of a sidecar block.\n *\n * @param block - The sidecar sub-object.\n * @param key - The property name.\n * @param fallback - What to use when the property is absent or not a string.\n * @returns The value.\n */\nfunction readString(block: Record<string, unknown>, key: string, fallback: string): string {\n const value = block[key];\n return typeof value === \"string\" ? value : fallback;\n}\n","import { loadTexture } from \"../../lite/gpu/texture.js\";\nimport { readTextureImportOptions, TEXTURE_ASSET_TYPE, TextureAsset, toLiteTextureOptions } from \"../texture-asset.js\";\nimport type { AssetLoader, LoaderContext } from \"../../assets/types.js\";\n\n/**\n * The `texture` asset loader (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * ## Lite fetches the bytes, not ignifx\n *\n * Every other GPU loader here reads through `ctx.fetchBytes`, which is what gives it progress,\n * cancellation, and retries. A texture cannot: `loadTexture2D` takes a **URL** and decodes it with\n * `createImageBitmap`, which is the browser's own hardware-accelerated decode path\n * (`src/lite/gpu/texture.ts`). Handing it bytes would mean decoding a PNG in JavaScript. So the\n * loader hands Lite `ctx.url` and reports its own coarse progress instead, and a texture's\n * `AbortSignal` stops the *request* rather than the fetch. The trade is deliberate and it is the\n * one place §5's \"the three `fetch*` methods are the only network paths\" does not hold; the\n * alternative is worse.\n *\n * ## Options come from the sidecar\n *\n * `.meta.json` sidecars carry per-asset import options (§7), the build copies them into the\n * manifest entry, and `ctx.meta` is how a loader reads its own block. sRGB is the one that matters:\n * a base-colour or emissive texture wants it, and a normal, ORM, or data map must not have it.\n */\n\n/**\n * Builds the loader for `.png`, `.jpg`, `.jpeg`, `.webp`, `.ktx2`, and `.basis` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createTextureLoader());\n * ```\n *\n * @public\n */\nexport function createTextureLoader(): AssetLoader<TextureAsset> {\n return {\n type: TEXTURE_ASSET_TYPE,\n extensions: [\".png\", \".jpg\", \".jpeg\", \".webp\", \".ktx2\", \".basis\"],\n async load(ctx: LoaderContext): Promise<TextureAsset> {\n const options = readTextureImportOptions(ctx.meta);\n if (ctx.app.isHeadless) {\n // §5: \"a loader must tolerate the null engine (return CPU-only data with `gpu: null`)\".\n return new TextureAsset(ctx.address, null, options);\n }\n ctx.reportProgress(0);\n const texture = await loadTexture(ctx.lite.engine, ctx.url, toLiteTextureOptions(options));\n ctx.reportProgress(1);\n return new TextureAsset(ctx.address, texture, options);\n },\n unload(value: TextureAsset): void {\n value.releaseGpu();\n },\n };\n}\n","import {\n addToScene,\n cloneTransformNode,\n createBox,\n createCapsule,\n createCylinder,\n createGround,\n createMeshFromData,\n createPlane,\n createSphere,\n createTorus,\n removeFromScene,\n setSubtreeVisible,\n} from \"@babylonjs/lite\";\nimport type {\n BoxOptions,\n CapsuleOptions,\n CylinderOptions,\n EngineContext,\n GroundOptions,\n Material,\n Mesh,\n PlaneOptions,\n SceneContext,\n SceneNode,\n SphereOptions,\n TorusOptions,\n} from \"@babylonjs/lite\";\n\n/**\n * Mesh half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3). Every function\n * here needs a WebGPU device — `createMeshFromData` uploads four vertex buffers through\n * `engine._device` (`lib/mesh/mesh.js`, `uploadMeshToGPU`) and the null engine has no `_device` —\n * so the whole module lives under `src/lite/gpu/` and is covered by the browser test project.\n *\n * Everything here is `@internal`.\n *\n * ## Ownership, cloning, and disposal (verified against `@babylonjs/lite@1.27.0`)\n *\n * - `cloneTransformNode(mesh)` (`index.d.ts` 1776, `lib/scene/transform-node.js`) shallow-clones a\n * mesh: the clone gets a fresh transform and **the same `_gpu` wrapper object**, with\n * `retain(_gpu)` bumping a reference count. So N clones of one template share exactly one set of\n * GPU buffers — that is spike S2.4's \"instancing shares GPU buffers\", and it is provable by\n * object identity rather than by measuring memory.\n * - Disposal is driven entirely by scene membership. `removeFromScene` calls `unregisterMeshScene`,\n * and only when the mesh has left its **last** scene does it queue `disposeMeshGpu`, which calls\n * `release(_gpu)` and destroys the buffers only when the count drops to one\n * (`lib/scene/scene-remove.js`, `lib/mesh/mesh-dispose.js`, `lib/resource/ref-count.js`). A\n * template that is never added to a scene therefore keeps its buffers alive no matter how many\n * clones come and go — which is what `docs/architecture/07-rendering.md` §2.3 means by \"the\n * template's buffers stay alive while the asset is retained\".\n * - The flip side is that Lite exports **no** mesh disposer. The only public way to release a\n * template's buffers is {@link disposeMeshTemplate}: add it to a scene and take it out again.\n * - `removeFromScene` also recursively removes a mesh's `children` and nulls its `parent`, so\n * removing a `Model`'s root removes the whole instantiated subtree in one call.\n * - Hiding is `setSubtreeVisible` (exported as `setMeshVisible` too, `index.d.ts` 11199): it\n * cascades `visible` down the subtree and bumps a global visibility epoch. Never remove a mesh\n * from the scene to hide it — that disposes it.\n */\n\n/**\n * The Babylon Lite mesh a `MeshAsset` template and a `MeshRenderer` clone are, re-exported under an\n * ignifx name so feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches, and it\n * is excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMesh = Mesh;\n\n/**\n * Creates a box template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - A uniform size, or per-axis dimensions.\n * @returns The mesh. It belongs to no scene yet.\n *\n * @example\n * ```ts\n * const template = createBoxMesh(engine, { size: 2 });\n * const instance = cloneMeshUnderNode(template, entityNode);\n * addMeshToScene(scene, instance);\n * ```\n *\n * @internal\n */\nexport function createBoxMesh(engine: EngineContext, options?: number | BoxOptions): Mesh {\n return createBox(engine, options);\n}\n\n/**\n * Creates a sphere template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Segment count and diameters.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createSphereMesh(engine: EngineContext, options?: SphereOptions): Mesh {\n return createSphere(engine, options);\n}\n\n/**\n * Creates a plane template in the XY plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Size, or width and height.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createPlaneMesh(engine: EngineContext, options?: PlaneOptions): Mesh {\n return createPlane(engine, options);\n}\n\n/**\n * Creates a subdivided ground template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Width, height, subdivisions, and UV scale.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createGroundMesh(engine: EngineContext, options?: GroundOptions): Mesh {\n return createGround(engine, options);\n}\n\n/**\n * Creates a cylinder template along the Y axis.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, diameters, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCylinderMesh(engine: EngineContext, options?: CylinderOptions): Mesh {\n return createCylinder(engine, options);\n}\n\n/**\n * Creates a capsule template along the Y axis.\n *\n * @remarks\n * `height` is the **total** height including both caps (`index.d.ts` 1523), which is the same\n * convention `@ignifx/physics`'s capsule collider uses, so a renderer and a collider built from one\n * pair of numbers line up.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, radius, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCapsuleMesh(engine: EngineContext, options?: CapsuleOptions): Mesh {\n return createCapsule(engine, options);\n}\n\n/**\n * Creates a torus template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Diameter, thickness, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createTorusMesh(engine: EngineContext, options?: TorusOptions): Mesh {\n return createTorus(engine, options);\n}\n\n/**\n * Creates a mesh from raw vertex data.\n *\n * @remarks\n * Lite keeps a reference to the arrays that are handed in — it does not copy them — and uses them\n * for CPU ray picking and bounds (`lib/mesh/mesh-factories.js`). Callers must not mutate them\n * afterwards.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param name - A debug name.\n * @param positions - Three floats per vertex.\n * @param normals - Three floats per vertex.\n * @param indices - Three indices per triangle.\n * @param uvs - Two floats per vertex, or omitted.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createMeshFromGeometry(\n engine: EngineContext,\n name: string,\n positions: Float32Array,\n normals: Float32Array,\n indices: Uint32Array,\n uvs?: Float32Array,\n): Mesh {\n return createMeshFromData(engine, name, positions, normals, indices, uvs);\n}\n\n/**\n * Clones a template — mesh or transform-node subtree — and parents the clone under an entity node.\n *\n * @remarks\n * The clone shares the template's GPU buffers (see the module note). Cloning a mesh whose buffers\n * were already released throws, which is Lite's way of telling you the template outlived its asset.\n *\n * Only the `parent` link is written; the clone is deliberately **not** pushed into the parent's\n * `children` array, for the same reason cameras and lights are not (`./camera.ts`): ignifx\n * transform nodes are never added to a Lite scene, so nothing in Lite walks their children, and\n * `removeFromScene` nulls a removed mesh's `parent` without touching the array it was listed in —\n * so maintaining it would only create a stale entry to clean up.\n *\n * @param template - The mesh or subtree to clone.\n * @param parent - The entity's transform node, or `null` for world space.\n * @returns The cloned root. Add it to the scene with {@link addMeshToScene}.\n *\n * @internal\n */\nexport function cloneMeshUnderNode(template: SceneNode, parent: SceneNode | null): SceneNode {\n const clone = cloneTransformNode(template);\n clone.parent = parent;\n return clone;\n}\n\n/**\n * Adds a mesh — or a transform-node subtree containing meshes — to a render scene.\n *\n * @remarks\n * `addToScene` recurses into `children` and re-parents each one, so a whole instantiated model goes\n * in with one call. When the scene is already registered, the mesh joins Lite's runtime\n * material-swap queue and appears once its material family's renderable has been rebuilt\n * (`docs/architecture/07-rendering.md` §1.1 and ADR-0014).\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to add.\n *\n * @internal\n */\nexport function addMeshToScene(scene: SceneContext, node: SceneNode): void {\n addToScene(scene, node);\n}\n\n/**\n * Removes a mesh — and everything under it — from a render scene, releasing its GPU buffers when it\n * has left its last scene.\n *\n * @remarks\n * This is destruction, not hiding: use {@link setMeshSubtreeVisible} to hide.\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to remove.\n *\n * @internal\n */\nexport function removeMeshFromScene(scene: SceneContext, node: SceneNode): void {\n removeFromScene(scene, node);\n}\n\n/**\n * Shows or hides a mesh and everything under it.\n *\n * @param node - The subtree root.\n * @param visible - `true` to show it, `false` to hide it.\n *\n * @internal\n */\nexport function setMeshSubtreeVisible(node: SceneNode, visible: boolean): void {\n setSubtreeVisible(node, visible);\n}\n\n/**\n * Assigns a mesh's material.\n *\n * @remarks\n * `Mesh.material` is an accessor once the mesh has joined a scene: writing it queues a material\n * swap on every scene the mesh belongs to (`lib/scene/mesh-scene-registry.js`,\n * `installMaterialSetter`). Assigning the material the mesh already has is a no-op.\n *\n * @param mesh - The mesh to change.\n * @param material - The material to draw it with.\n *\n * @internal\n */\nexport function setMeshMaterial(mesh: Mesh, material: Material): void {\n mesh.material = material;\n}\n\n/**\n * Sets whether a mesh is darkened by shadow maps.\n *\n * @param mesh - The mesh to change.\n * @param receiveShadows - `true` to sample shadow maps on this mesh.\n *\n * @internal\n */\nexport function setMeshReceiveShadows(mesh: Mesh, receiveShadows: boolean): void {\n mesh.receiveShadows = receiveShadows;\n}\n\n/**\n * Sets a mesh's sort key within its phase. Lower values are drawn first.\n *\n * @param mesh - The mesh to change.\n * @param renderOrder - The sort key; it only orders within the opaque or the transparent phase.\n *\n * @internal\n */\nexport function setMeshRenderOrder(mesh: Mesh, renderOrder: number): void {\n mesh.renderOrder = renderOrder;\n}\n\n/**\n * Sets whether picking considers a mesh at all.\n *\n * @remarks\n * `pickable === false` removes the mesh from both the GPU picker's candidate list and the CPU ray\n * test, so it neither occludes nor returns a hit (`index.d.ts` 7156, `lib/picking/ray-pick.js`).\n *\n * @param mesh - The mesh to change.\n * @param pickable - `true` to allow picking.\n *\n * @internal\n */\nexport function setMeshPickable(mesh: Mesh, pickable: boolean): void {\n mesh.pickable = pickable;\n}\n\n/**\n * Gives a mesh the string id Lite's light include/exclude sets match on.\n *\n * @param mesh - The mesh to name.\n * @param id - The id. It should be unique within the scene.\n *\n * @internal\n */\nexport function setMeshId(mesh: Mesh, id: string): void {\n mesh.id = id;\n}\n\n/**\n * Replaces the materials of every mesh in a subtree whose current material carries one of the given\n * names.\n *\n * @remarks\n * `Material.name` is \"populated by loaders from the source asset (e.g. the glTF material name) so\n * callers can look a material up by name\" (`index.d.ts`), which is the identifier\n * `docs/architecture/07-rendering.md` §2.4 means by \"by material name\". Assigning `Mesh.material`\n * queues a material swap on every scene the mesh belongs to; assigning the material a mesh already\n * has is a no-op, so re-running this is cheap.\n *\n * @param node - The subtree root.\n * @param overrides - Source material name to replacement material.\n * @returns How many meshes were re-materialled.\n *\n * @internal\n */\nexport function overrideSubtreeMaterials(node: SceneNode, overrides: ReadonlyMap<string, Material>): number {\n let changed = 0;\n if (\"material\" in node) {\n // Boundary assertion (coding standards §5.2): a scene node that carries `material` is a mesh —\n // the same structural test Lite's own scene walk uses.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const mesh = node as Mesh;\n const name = mesh.material.name;\n const replacement = name === undefined ? undefined : overrides.get(name);\n if (replacement !== undefined && replacement !== mesh.material) {\n mesh.material = replacement;\n changed += 1;\n }\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n changed += overrideSubtreeMaterials(child, overrides);\n }\n }\n return changed;\n}\n\n/**\n * Releases a template mesh's GPU buffers.\n *\n * @remarks\n * Lite exports no mesh disposer: a mesh's buffers are freed only when it leaves its last scene\n * (`lib/scene/scene-remove.js`). A template that was never added to a scene therefore has to be\n * added and removed to be released, which is exactly what this does. Two consequences the caller\n * must respect:\n *\n * 1. The template must carry no material, or the round trip will build and immediately tear down a\n * renderable for it. Templates created by the factories above start with none.\n * 2. Any clone still alive keeps the shared buffers: the reference count only reaches zero when the\n * last co-owner has gone. Releasing the template while clones are in a scene is safe, but the\n * template can no longer be cloned afterwards.\n *\n * @param scene - Any scene on the template's engine; it is used only as the round trip's vehicle.\n * @param template - The template to release.\n *\n * @internal\n */\nexport function disposeMeshTemplate(scene: SceneContext, template: Mesh): void {\n addToScene(scene, template);\n removeFromScene(scene, template);\n}\n\n/**\n * Collects every mesh in a subtree — the root included — in depth-first order.\n *\n * @remarks\n * A scene node that carries `material` is a mesh: the same structural test\n * {@link overrideSubtreeMaterials} and Lite's own scene walk use (`index.d.ts` 7156 declares\n * `material` on `Mesh` and nowhere on `SceneNode`, 10104).\n *\n * Call it **once**, when the subtree is instantiated. The clone tree `instantiateContainer` built\n * never changes shape afterwards, so walking it again every frame would put a recursion on the\n * render path for an answer that cannot have moved (coding standards §7).\n *\n * @param node - The subtree root.\n * @param out - The list the meshes are appended to; it is not cleared first.\n *\n * @internal\n */\nexport function collectSubtreeMeshes(node: SceneNode, out: Mesh[]): void {\n if (\"material\" in node) {\n // Boundary assertion (coding standards §5.2): see the note above.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push(node as Mesh);\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectSubtreeMeshes(child, out);\n }\n }\n}\n","import {\n createBoxMesh,\n createCapsuleMesh,\n createCylinderMesh,\n createGroundMesh,\n createMeshFromGeometry,\n createPlaneMesh,\n createSphereMesh,\n createTorusMesh,\n disposeMeshTemplate,\n} from \"../lite/gpu/mesh.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { LiteMesh } from \"../lite/gpu/mesh.js\";\nimport type { LiteScene } from \"../lite/scene.js\";\n\n/**\n * `MeshAsset` (`docs/architecture/07-rendering.md` §2.3): the geometry template a `MeshRenderer`\n * clones. One upload, many renderers — `cloneTransformNode` shallow-clones a mesh and shares its\n * `_gpu` wrapper under a reference count, so N renderers of one asset cost one set of vertex\n * buffers (ADR-0002 Validation, `src/lite/gpu/mesh.ts`).\n *\n * ## Why the factories return handles\n *\n * `MeshRenderer.mesh` is an `asset(MeshAsset)` field, and since Phase 2 the runtime value of an\n * `asset()` field is an `AssetHandle` (`05-assets-and-loading.md` §3). A primitive built in code\n * therefore has to be *published* before a renderer can hold it, which is what `Assets.register`\n * does: the factories below register the template under a `memory:mesh/<n>` address and hand back\n * the handle, already loaded, with one holder — the caller.\n *\n * Ownership follows from that. The caller releases the handle (or lets a `using` block do it); the\n * collector then runs the `mesh` type's `unload`, which is {@link MeshAsset.dispose}. Releasing\n * while renderers still hold clones is safe — Lite frees the shared buffers only when the last\n * co-owner has gone — but the template can no longer be cloned afterwards.\n *\n * ## Headless\n *\n * Every Lite mesh factory uploads through `engine._device`, which the null engine does not have\n * (`07-rendering.md` §6). Under a headless app a `MeshAsset` therefore carries no geometry:\n * `lite.mesh` is `null`, `dispose()` is a no-op, and a `MeshRenderer` that holds it keeps its state\n * without touching the scene. Tests assert on component state, not on Lite scene contents.\n */\n\n/**\n * The asset type primitives are registered under.\n *\n * @public\n */\nexport const MESH_ASSET_TYPE = \"mesh\";\n\n/**\n * How {@link MeshAsset.box} sizes its box, in metres. Give `size` for a cube, or the three\n * dimensions.\n *\n * @public\n */\nexport interface BoxMeshOptions {\n /** Edge length on every axis. */\n readonly size?: number;\n /** Size along X, overriding `size`. */\n readonly width?: number;\n /** Size along Y, overriding `size`. */\n readonly height?: number;\n /** Size along Z, overriding `size`. */\n readonly depth?: number;\n}\n\n/**\n * How {@link MeshAsset.sphere} tessellates its sphere.\n *\n * @public\n */\nexport interface SphereMeshOptions {\n /** Diameter on every axis, in metres. Lite defaults to 1. */\n readonly diameter?: number;\n /** Ring count; higher is smoother. Lite defaults to 32. */\n readonly segments?: number;\n}\n\n/**\n * How {@link MeshAsset.plane} sizes its quad, which lies in the XY plane facing `-Z`.\n *\n * @public\n */\nexport interface PlaneMeshOptions {\n /** Edge length on both axes, in metres. */\n readonly size?: number;\n /** Width, overriding `size`. */\n readonly width?: number;\n /** Height, overriding `size`. */\n readonly height?: number;\n}\n\n/**\n * How {@link MeshAsset.ground} sizes and subdivides its grid, which lies in the XZ plane facing\n * `+Y`.\n *\n * @public\n */\nexport interface GroundMeshOptions {\n /** Size along X, in metres. */\n readonly width?: number;\n /** Size along Z, in metres. */\n readonly height?: number;\n /** Quads per side. */\n readonly subdivisions?: number;\n /** UV multiplier, for tiling a texture across the grid. */\n readonly uvScale?: readonly [number, number];\n}\n\n/**\n * How {@link MeshAsset.cylinder} sizes its cylinder, which stands along Y.\n *\n * @public\n */\nexport interface CylinderMeshOptions {\n /** Height along Y, in metres. */\n readonly height?: number;\n /** Diameter of both ends. */\n readonly diameter?: number;\n /** Diameter of the top cap, overriding `diameter` — a cone is `diameterTop: 0`. */\n readonly diameterTop?: number;\n /** Diameter of the bottom cap, overriding `diameter`. */\n readonly diameterBottom?: number;\n /** Radial segment count. */\n readonly tessellation?: number;\n}\n\n/**\n * How {@link MeshAsset.capsule} sizes its capsule, which stands along Y.\n *\n * @remarks\n * `height` is the **total** height including both caps, the same convention `@ignifx/physics` uses\n * for a capsule collider, so one pair of numbers describes both.\n *\n * @public\n */\nexport interface CapsuleMeshOptions {\n /** Total height including both caps, in metres. */\n readonly height?: number;\n /** Radius of the body and the caps. */\n readonly radius?: number;\n /** Radial segment count. */\n readonly tessellation?: number;\n}\n\n/**\n * How {@link MeshAsset.torus} sizes its ring, which lies in the XZ plane.\n *\n * @public\n */\nexport interface TorusMeshOptions {\n /** Outer diameter, in metres. */\n readonly diameter?: number;\n /** Tube thickness, in metres. */\n readonly thickness?: number;\n /** Segment count around the ring. */\n readonly tessellation?: number;\n}\n\n/**\n * Raw vertex data for {@link MeshAsset.fromData}.\n *\n * @remarks\n * Lite keeps references to these arrays rather than copying them — they are what its CPU ray pick\n * and its bounds read (`lib/mesh/mesh-factories.js`) — so a caller must not mutate them afterwards.\n *\n * @public\n */\nexport interface MeshGeometryData {\n /** Three floats per vertex. */\n readonly positions: Float32Array;\n /** Three floats per vertex, one normal each. */\n readonly normals: Float32Array;\n /** Three indices per triangle. */\n readonly indices: Uint32Array;\n /** Two floats per vertex, or omitted for a mesh with no texture coordinates. */\n readonly uvs?: Float32Array;\n}\n\n/**\n * The Babylon Lite objects a {@link MeshAsset} owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @public\n */\nexport interface MeshAssetLiteHandles {\n /** The template mesh, or `null` under a headless app, which uploads no geometry. */\n readonly mesh: LiteMesh | null;\n}\n\n/**\n * A geometry template a `MeshRenderer` draws (`docs/architecture/07-rendering.md` §2.3).\n *\n * @remarks\n * Build one with a primitive factory or {@link MeshAsset.fromData}; each returns the handle the\n * `MeshRenderer.mesh` field takes. A mesh that came from a file arrives as part of a `ModelAsset`\n * instead — a glTF is a tree of meshes, materials, and animations, not one buffer.\n *\n * @example\n * ```ts\n * using box = MeshAsset.box(app, { size: 2 });\n * const cube = app.world.createEntity(\"Cube\");\n * cube.addComponent(MeshRenderer, { mesh: box.retain() });\n * ```\n *\n * @public\n */\nexport class MeshAsset {\n /** The type name the asset service registers meshes under. */\n static assetType: string = MESH_ASSET_TYPE;\n\n /** A human-readable name, used in diagnostics and as the Lite mesh's name. */\n readonly name: string;\n\n readonly #scene: LiteScene | null;\n\n #mesh: LiteMesh | null;\n\n #isDisposed = false;\n\n /**\n * Wraps a template mesh. Use the static factories; the engine constructs assets.\n *\n * @param name - A human-readable name.\n * @param mesh - The template, or `null` when the app is headless.\n * @param scene - The scene the template is released through, or `null` when there is nothing to\n * release.\n *\n * @internal\n */\n constructor(name: string, mesh: LiteMesh | null, scene: LiteScene | null) {\n this.name = name;\n this.#mesh = mesh;\n this.#scene = scene;\n }\n\n /**\n * The Babylon Lite objects the asset owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The template mesh, or `null` under a headless app.\n */\n get lite(): MeshAssetLiteHandles {\n return { mesh: this.#mesh };\n }\n\n /**\n * Whether the template's GPU buffers have been released.\n *\n * @returns `true` once {@link MeshAsset.dispose} has run.\n */\n get isDisposed(): boolean {\n return this.#isDisposed;\n }\n\n /**\n * Releases the template's GPU buffers.\n *\n * @remarks\n * Lite exports no mesh disposer: a mesh's buffers are freed when it leaves its last scene, so the\n * adapter adds the template to a scene and takes it straight out again\n * (`src/lite/gpu/mesh.ts`). Clones still in a scene keep the shared buffers alive; what the\n * template loses is the ability to be cloned again. Calling it twice is a no-op, and it is a\n * no-op under a headless app, which has no buffers.\n */\n dispose(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#isDisposed = true;\n const mesh = this.#mesh;\n const scene = this.#scene;\n this.#mesh = null;\n if (mesh !== null && scene !== null) {\n disposeMeshTemplate(scene, mesh);\n }\n }\n\n /** Releases the template when the asset leaves a `using` block. */\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n /**\n * Creates a box template and publishes it.\n *\n * @param app - The app whose engine uploads the geometry and whose asset service holds the handle.\n * @param options - A uniform `size`, or per-axis dimensions.\n * @returns The handle, with one holder — the caller.\n *\n * @example\n * ```ts\n * const box = MeshAsset.box(app, { width: 2, height: 1, depth: 3 });\n * ```\n */\n static box(app: App, options?: BoxMeshOptions): AssetHandle<MeshAsset> {\n return publish(app, \"box\", () =>\n createBoxMesh(app.lite.engine, options === undefined ? undefined : { ...options }),\n );\n }\n\n /**\n * Creates a sphere template and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param options - Diameter and ring count.\n * @returns The handle, with one holder.\n */\n static sphere(app: App, options?: SphereMeshOptions): AssetHandle<MeshAsset> {\n return publish(app, \"sphere\", () =>\n createSphereMesh(app.lite.engine, options === undefined ? undefined : { ...options }),\n );\n }\n\n /**\n * Creates a quad template in the XY plane and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param options - A uniform `size`, or width and height.\n * @returns The handle, with one holder.\n */\n static plane(app: App, options?: PlaneMeshOptions): AssetHandle<MeshAsset> {\n return publish(app, \"plane\", () =>\n createPlaneMesh(app.lite.engine, options === undefined ? undefined : { ...options }),\n );\n }\n\n /**\n * Creates a subdivided grid in the XZ plane and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param options - Width, depth, subdivisions, and UV scale.\n * @returns The handle, with one holder.\n */\n static ground(app: App, options?: GroundMeshOptions): AssetHandle<MeshAsset> {\n const lite = toGroundOptions(options);\n return publish(app, \"ground\", () => createGroundMesh(app.lite.engine, lite));\n }\n\n /**\n * Creates a cylinder template standing along Y and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param options - Height, diameters, and tessellation.\n * @returns The handle, with one holder.\n */\n static cylinder(app: App, options?: CylinderMeshOptions): AssetHandle<MeshAsset> {\n return publish(app, \"cylinder\", () =>\n createCylinderMesh(app.lite.engine, options === undefined ? undefined : { ...options }),\n );\n }\n\n /**\n * Creates a capsule template standing along Y and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param options - Total height, radius, and tessellation.\n * @returns The handle, with one holder.\n */\n static capsule(app: App, options?: CapsuleMeshOptions): AssetHandle<MeshAsset> {\n return publish(app, \"capsule\", () =>\n createCapsuleMesh(app.lite.engine, options === undefined ? undefined : { ...options }),\n );\n }\n\n /**\n * Creates a torus template in the XZ plane and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param options - Diameter, thickness, and tessellation.\n * @returns The handle, with one holder.\n */\n static torus(app: App, options?: TorusMeshOptions): AssetHandle<MeshAsset> {\n return publish(app, \"torus\", () =>\n createTorusMesh(app.lite.engine, options === undefined ? undefined : { ...options }),\n );\n }\n\n /**\n * Creates a template from raw vertex data and publishes it.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param name - A human-readable name.\n * @param data - Positions, normals, indices, and optional texture coordinates. Lite keeps\n * references to the arrays; do not mutate them afterwards.\n * @returns The handle, with one holder.\n *\n * @example\n * ```ts\n * const triangle = MeshAsset.fromData(app, \"triangle\", {\n * positions: Float32Array.from([0, 0, 0, 1, 0, 0, 0, 1, 0]),\n * normals: Float32Array.from([0, 0, -1, 0, 0, -1, 0, 0, -1]),\n * indices: Uint32Array.from([0, 1, 2]),\n * });\n * ```\n */\n static fromData(app: App, name: string, data: MeshGeometryData): AssetHandle<MeshAsset> {\n return publish(app, name, () =>\n createMeshFromGeometry(app.lite.engine, name, data.positions, data.normals, data.indices, data.uvs),\n );\n }\n}\n\n/**\n * Copies the ignifx ground options onto Lite's, which types `uvScale` as a mutable tuple.\n *\n * @param options - The declared options.\n * @returns Lite's options, or `undefined` when the caller declared none.\n */\nfunction toGroundOptions(\n options: GroundMeshOptions | undefined,\n): { width?: number; height?: number; subdivisions?: number; uvScale?: [number, number] } | undefined {\n if (options === undefined) {\n return undefined;\n }\n const result: { width?: number; height?: number; subdivisions?: number; uvScale?: [number, number] } = {};\n if (options.width !== undefined) {\n result.width = options.width;\n }\n if (options.height !== undefined) {\n result.height = options.height;\n }\n if (options.subdivisions !== undefined) {\n result.subdivisions = options.subdivisions;\n }\n const uvScale = options.uvScale;\n if (uvScale !== undefined) {\n result.uvScale = [uvScale[0], uvScale[1]];\n }\n return result;\n}\n\n/**\n * Builds a template — skipping the upload under a headless app — and registers it as an in-memory\n * asset.\n *\n * @param app - The app that owns the engine and the asset service.\n * @param name - A human-readable name.\n * @param build - Creates the Lite mesh. Never called when the app is headless.\n * @returns The handle, with one holder.\n */\nfunction publish(app: App, name: string, build: () => LiteMesh): AssetHandle<MeshAsset> {\n const scene = app.lite.scene;\n const mesh = app.isHeadless ? null : build();\n return app.assets.register(new MeshAsset(name, mesh, app.isHeadless ? null : scene), { type: MESH_ASSET_TYPE });\n}\n","import {\n addMeshToScene,\n cloneMeshUnderNode,\n removeMeshFromScene,\n setMeshId,\n setMeshMaterial,\n setMeshPickable,\n setMeshReceiveShadows,\n setMeshRenderOrder,\n setMeshSubtreeVisible,\n} from \"../../lite/gpu/mesh.js\";\nimport { tagNode } from \"../../lite/node.js\";\nimport type { LiteMesh } from \"../../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../../lite/material.js\";\nimport type { LiteSceneNode, NodeTag } from \"../../lite/node.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\n\n/**\n * One `MeshRenderer`'s clone of a `MeshAsset` template, and everything writing to it\n * (`docs/architecture/07-rendering.md` §2.3).\n *\n * Every line here needs a WebGPU device: a clone only exists when the template does, and a template\n * only exists when the engine uploaded its buffers. That is why the module lives under\n * `src/render/gpu/`, the render layer's half of the rule R1 established for `src/lite/gpu/`: the\n * root Vitest coverage config excludes both, and the browser project is what measures them.\n *\n * The per-field \"did it change\" cache lives here rather than on the component for the same reason.\n * It is only consulted when there is something to write to, so leaving it on the component would\n * put a dozen branches no unit test can reach in a file unit tests otherwise cover completely.\n */\n\n/**\n * A live clone in a scene.\n *\n * @internal\n */\nexport class MeshInstance {\n /** The cloned subtree root, parented under the entity's node. */\n readonly clone: LiteSceneNode;\n\n #material: LiteMaterial | null = null;\n\n #receiveShadows: boolean | null = null;\n\n #renderOrder = Number.NaN;\n\n #pickable: boolean | null = null;\n\n #visible = false;\n\n /**\n * Clones a template under an entity's node, tags it, and adds it to the scene.\n *\n * @param scene - The render scene.\n * @param template - The `MeshAsset`'s template mesh.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material to draw with. It is assigned **before** the mesh joins the\n * scene: `addToScene` buckets a mesh by its material's build group, and a mesh that arrives\n * without one takes a path that leaves the scene's render pass presenting nothing at all\n * (measured on SwiftShader, 2026-09-05).\n */\n constructor(\n scene: LiteScene,\n template: LiteMesh,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n ) {\n const clone = cloneMeshUnderNode(template, parent);\n tagNode(clone, tag);\n const mesh = asMesh(clone);\n setMeshId(mesh, meshId);\n setMeshMaterial(mesh, material);\n this.#material = material;\n // A fresh clone is visible until the first `applyVisible`; starting it hidden means a renderer\n // on an inactive entity never flashes for one frame.\n setMeshSubtreeVisible(clone, false);\n addMeshToScene(scene, clone);\n this.clone = clone;\n }\n\n /**\n * Whether the clone is currently drawn.\n *\n * @returns `true` when Lite's `visible` is set on the subtree.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * The clone as a mesh, for the shadow caster list.\n *\n * @returns The clone.\n */\n get mesh(): LiteMesh {\n return asMesh(this.clone);\n }\n\n /**\n * Assigns the material, when it changed.\n *\n * @param material - The Lite material to draw with.\n */\n applyMaterial(material: LiteMaterial): void {\n if (material === this.#material) {\n return;\n }\n this.#material = material;\n setMeshMaterial(this.mesh, material);\n }\n\n /**\n * Writes the per-mesh flags that changed.\n *\n * @param receiveShadows - Whether shadow maps darken the mesh.\n * @param renderOrder - The sort key within its phase.\n * @param pickable - Whether picking considers the mesh at all.\n */\n applyFlags(receiveShadows: boolean, renderOrder: number, pickable: boolean): void {\n const mesh = this.mesh;\n if (this.#receiveShadows !== receiveShadows) {\n this.#receiveShadows = receiveShadows;\n setMeshReceiveShadows(mesh, receiveShadows);\n }\n if (this.#renderOrder !== renderOrder) {\n this.#renderOrder = renderOrder;\n setMeshRenderOrder(mesh, renderOrder);\n }\n if (this.#pickable !== pickable) {\n this.#pickable = pickable;\n setMeshPickable(mesh, pickable);\n }\n }\n\n /**\n * Shows or hides the clone, when the state changed.\n *\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n */\n applyVisible(visible: boolean): void {\n if (visible === this.#visible) {\n return;\n }\n this.#visible = visible;\n setMeshSubtreeVisible(this.clone, visible);\n }\n\n /**\n * Removes the clone from the scene, releasing its share of the template's buffers.\n *\n * @param scene - The render scene.\n */\n destroy(scene: LiteScene): void {\n removeMeshFromScene(scene, this.clone);\n }\n}\n\n/**\n * Narrows a cloned subtree root to a mesh.\n *\n * @remarks\n * `cloneTransformNode` is typed as returning the wider `SceneNode` because it also clones plain\n * transform nodes; the clone of a mesh is a mesh (coding standards §5.2).\n *\n * @param node - The clone.\n * @returns The same object, typed as a mesh.\n */\nfunction asMesh(node: LiteSceneNode): LiteMesh {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- see the note above.\n return node as LiteMesh;\n}\n","import { Component } from \"../component/component.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { array, asset, bool, i32 } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport { MeshInstance } from \"./gpu/mesh-instance.js\";\nimport { MaterialAsset } from \"./material-asset.js\";\nimport { MeshAsset } from \"./mesh-asset.js\";\nimport { rendererInternals } from \"./renderer.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { ComponentHooks } from \"../component/component.js\";\nimport type { LiteMesh } from \"../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../lite/material.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `MeshRenderer` component (`docs/architecture/07-rendering.md` §2.3): one clone of a\n * `MeshAsset`, drawn with a `MaterialAsset`.\n *\n * ## Cloning, not sharing\n *\n * The asset holds the template; the renderer holds a clone parented under the entity's node.\n * `cloneTransformNode` shallow-clones the mesh — fresh transform, **same** `_gpu` wrapper with its\n * reference count bumped — so a hundred renderers of one asset upload one set of vertex buffers\n * (ADR-0002 Validation). Removing the component calls `removeFromScene` on the clone, which is what\n * frees its share.\n *\n * ## Hiding is `visible`, never removal\n *\n * Lite disposes a mesh that leaves its last scene, so `enabled = false` must not remove anything.\n * `visible` is derived from `entity.activeInHierarchy && component.enabled` and written on the\n * clone's subtree; the mesh stays in the scene, keeps its buffers, and comes back the moment the\n * flag flips. That is `07-rendering.md` §2.3's rule, and the browser test asserts both halves: the\n * pixel returns to the clear colour, and the mesh is still in the scene.\n *\n * ## Decisions the documents left open\n *\n * - **The clone's Lite `id` is the entity's uid.** Lite's light include/exclude lists match on\n * `Mesh.id` strings (`lib/render/lights-ubo.js`), and §2.2 maps `Light.includeOnly` onto them\n * from *entity* references. The uid is the one identifier both sides can name.\n * - **`materials` beyond the first is accepted and ignored in Phase 2.** §2.3 says \"one per\n * submesh\", but Lite's `Mesh.material` is a single value and Lite has no submesh material list in\n * 1.27.0. The field keeps its array shape so files do not have to change when submeshes land; the\n * renderer uses index 0, or the default material when the array is empty.\n *\n * ## Headless\n *\n * A headless `MeshAsset` carries no geometry, so there is nothing to clone: the component keeps its\n * fields, reports `lite.mesh === null`, and touches no scene (`07-rendering.md` §6).\n */\n\n/**\n * Draws a mesh asset with a material (`docs/architecture/07-rendering.md` §2.3).\n *\n * @example\n * ```ts\n * using box = MeshAsset.box(app, { size: 1 });\n * const cube = world.createEntity(\"Cube\");\n * cube.addComponent(MeshRenderer, { mesh: box.retain(), castShadows: true });\n * ```\n *\n * @public\n */\nexport class MeshRenderer extends Component implements ComponentHooks {\n /** The namespaced registration id. */\n static typeId = \"ignifx/MeshRenderer\";\n\n /** Several renderers on one entity draw several meshes from one transform, which is useful. */\n static allowMultiple = true;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = meshRendererSchema();\n\n declare mesh: AssetHandle<MeshAsset> | null;\n\n declare materials: (AssetHandle<MaterialAsset> | null)[];\n\n declare castShadows: boolean;\n\n declare receiveShadows: boolean;\n\n declare renderOrder: number;\n\n declare pickable: boolean;\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(MeshRenderer.schema));\n }\n\n #instance: MeshInstance | null = null;\n\n #appliedMesh: MeshAsset | null = null;\n\n #appliedCastShadows = true;\n\n /**\n * The Babylon Lite mesh this renderer draws. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The clone, or `null` when there is nothing to draw.\n */\n get lite(): { readonly mesh: LiteSceneNode | null } {\n return { mesh: this.#instance?.clone ?? null };\n }\n\n /**\n * Whether the mesh is currently drawn: its own `enabled` flag and its entity's\n * `activeInHierarchy`, materialised onto Lite's `visible`.\n *\n * @returns `true` when the clone is visible.\n */\n get isVisible(): boolean {\n return this.#instance?.isVisible === true;\n }\n\n /** Nothing to do at attach: the clone is built on the first sync, once `mesh` has been decoded. */\n onAttach(): void {\n this.#appliedMesh = null;\n }\n\n /** Removes the clone from the scene, releasing its share of the template's buffers. */\n onDetach(): void {\n this.#releaseClone(rendererInternals(this.app.renderer));\n }\n\n /**\n * Rebuilds the clone when `mesh` changed, then writes every other field that changed. The\n * `PreRender` system calls it.\n *\n * @param renderer - The rendering service, for the scene and the default material.\n * @returns `true` when the scene's renderable set changed, which the system coalesces into one\n * `rebuildSceneRenderables`.\n *\n * @internal\n */\n sync(renderer: RendererImpl): boolean {\n const changed = this.#ensureClone(renderer);\n const instance = this.#instance;\n if (instance === null) {\n return changed;\n }\n instance.applyMaterial(this.#material(renderer));\n instance.applyFlags(this.receiveShadows, this.renderOrder, this.pickable);\n instance.applyVisible(this.isEnabledInHierarchy);\n return changed;\n }\n\n /**\n * Appends this renderer's mesh to a shadow caster list, when it casts.\n *\n * @param out - The caster list being built.\n *\n * @internal\n */\n collectCasters(out: LiteMesh[]): void {\n const instance = this.#instance;\n if (instance !== null && this.castShadows && instance.isVisible) {\n out.push(instance.mesh);\n }\n }\n\n /**\n * Whether the caster contribution of this renderer changed since the last frame.\n *\n * @returns `true` when `castShadows` or visibility moved.\n *\n * @internal\n */\n consumeCasterChange(): boolean {\n const casting = this.castShadows && this.isVisible;\n if (casting === this.#appliedCastShadows) {\n return false;\n }\n this.#appliedCastShadows = casting;\n return true;\n }\n\n /**\n * Builds or rebuilds the clone when the `mesh` field changed.\n *\n * @param renderer - The rendering service, for the scene.\n * @returns `true` when a mesh was added to or removed from the scene.\n */\n #ensureClone(renderer: RendererImpl): boolean {\n const loaded = this.mesh?.state === \"loaded\" ? this.mesh.value : null;\n if (loaded === this.#appliedMesh) {\n return false;\n }\n this.#releaseClone(renderer);\n this.#appliedMesh = loaded;\n const template = loaded?.lite.mesh ?? null;\n if (template === null) {\n return false;\n }\n this.#instance = new MeshInstance(\n renderer.scene,\n template,\n entityInternals(this.entity).node,\n { entity: this.entity.handle, component: this.handle },\n this.entity.uid,\n this.#material(renderer),\n );\n return true;\n }\n\n /**\n * The material this renderer draws with: the first it declares, or the app's default.\n *\n * @param renderer - The rendering service, for the default material.\n * @returns The Lite material.\n */\n #material(renderer: RendererImpl): LiteMaterial {\n const declared = this.materials[0];\n return declared?.state === \"loaded\" ? declared.value.lite.material : renderer.defaultMaterial().lite.material;\n }\n\n /**\n * Removes the clone from the scene, when there is one.\n *\n * @param renderer - The rendering service, for the scene.\n */\n #releaseClone(renderer: RendererImpl): void {\n const instance = this.#instance;\n this.#instance = null;\n this.#appliedMesh = null;\n instance?.destroy(renderer.scene);\n }\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function, not at module scope: a schema field is a function\n * call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4).\n */\nfunction meshRendererSchema(): Schema {\n return defineSchema({\n mesh: asset(MeshAsset, { tooltip: \"The geometry template to clone.\" }),\n materials: array(asset(MaterialAsset), [], { tooltip: \"One per submesh; empty uses the default material.\" }),\n castShadows: bool(true, { tooltip: \"Whether this mesh is rendered into shadow maps.\" }),\n receiveShadows: bool(true, { tooltip: \"Whether shadow maps darken this mesh.\" }),\n renderOrder: i32(0, { tooltip: \"Sort key within the opaque or transparent phase; lower draws first.\" }),\n pickable: bool(true, { tooltip: \"Whether picking considers this mesh at all.\" }),\n });\n}\n","import {\n addMeshToScene,\n collectSubtreeMeshes,\n overrideSubtreeMaterials,\n removeMeshFromScene,\n setMeshReceiveShadows,\n setMeshSubtreeVisible,\n} from \"../../lite/gpu/mesh.js\";\nimport { tagNode } from \"../../lite/node.js\";\nimport type { LiteMesh } from \"../../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../../lite/material.js\";\nimport type { LiteSceneNode, NodeTag } from \"../../lite/node.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\nimport type { ModelAsset, ModelInstantiation } from \"../model-asset.js\";\n\n/**\n * One `Model`'s instantiated copy of a `ModelAsset`, and everything writing to it\n * (`docs/architecture/07-rendering.md` §2.4).\n *\n * Device-only, for the same reason as `./mesh-instance.ts`: an instance only exists when the\n * container does, and a container only exists when `loadGltf` uploaded it. The root Vitest coverage\n * config excludes `src/render/gpu/**`; the browser project measures it.\n */\n\n/**\n * A live instantiated model subtree in a scene.\n *\n * @internal\n */\nexport class ModelInstance {\n /** The cloned container root, parented under the entity's node. */\n readonly root: LiteSceneNode;\n\n /** Every named node in the clone, keyed by its glTF node name. */\n readonly nodes: ReadonlyMap<string, LiteSceneNode>;\n\n /**\n * Every mesh in the clone, collected once at instantiation.\n *\n * @remarks\n * It is the shadow-caster contribution of the whole model and the list `receiveShadows` is\n * written across. Collected here rather than per frame because the clone tree's shape is fixed\n * the moment `instantiateContainer` built it (coding standards §7).\n */\n readonly meshes: readonly LiteMesh[];\n\n readonly #asset: ModelAsset;\n\n #visible = false;\n\n #receiveShadows: boolean | null = null;\n\n #overrideCount = -1;\n\n /**\n * Wraps a freshly instantiated subtree, tags it, and adds it to the scene.\n *\n * @param scene - The render scene.\n * @param asset - The template the subtree was cloned from; its instance count is bumped.\n * @param instantiation - What the asset's `instantiate` produced.\n * @param tag - The owning entity and component, for picking.\n */\n constructor(scene: LiteScene, asset: ModelAsset, instantiation: ModelInstantiation, tag: NodeTag) {\n this.root = instantiation.root;\n this.nodes = instantiation.nodes;\n const meshes: LiteMesh[] = [];\n collectSubtreeMeshes(instantiation.root, meshes);\n this.meshes = meshes;\n this.#asset = asset;\n asset.retainInstance();\n tagNode(instantiation.root, tag);\n setMeshSubtreeVisible(instantiation.root, false);\n addMeshToScene(scene, instantiation.root);\n }\n\n /**\n * Whether the subtree is currently drawn.\n *\n * @returns `true` when Lite's `visible` is set on it.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * Shows or hides the subtree, when the state changed.\n *\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n */\n applyVisible(visible: boolean): void {\n if (visible === this.#visible) {\n return;\n }\n this.#visible = visible;\n setMeshSubtreeVisible(this.root, visible);\n }\n\n /**\n * Appends every mesh of the subtree to a shadow caster list, when the subtree is drawn.\n *\n * @remarks\n * A hidden model casts nothing, exactly as a hidden `MeshRenderer` does: `visible` is what\n * `entity.activeInHierarchy && component.enabled` is materialised onto, and a shadow from an\n * object that is not there would be a bug the player can see.\n *\n * @param out - The caster list being built.\n */\n collectCasters(out: LiteMesh[]): void {\n if (!this.#visible) {\n return;\n }\n const meshes = this.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const mesh = meshes[index];\n if (mesh !== undefined) {\n out.push(mesh);\n }\n }\n }\n\n /**\n * Writes the receive-shadows flag across every mesh in the subtree, when it changed.\n *\n * @remarks\n * The same flag `MeshRenderer` writes onto its single clone (`src/render/gpu/mesh-instance.ts`),\n * fanned out over the instantiated tree: Lite reads `receiveShadows` per mesh\n * (`index.d.ts` 7160), so a model is a receiver only when each of its meshes is.\n *\n * @param receiveShadows - Whether shadow maps darken the instance.\n */\n applyReceiveShadows(receiveShadows: boolean): void {\n if (receiveShadows === this.#receiveShadows) {\n return;\n }\n this.#receiveShadows = receiveShadows;\n const meshes = this.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const mesh = meshes[index];\n if (mesh !== undefined) {\n setMeshReceiveShadows(mesh, receiveShadows);\n }\n }\n }\n\n /**\n * Re-materials the subtree when the override map changed size.\n *\n * @remarks\n * Size is the change signal because the map is short, inspector-edited data and walking the\n * subtree every frame to catch a same-size swap would cost more than the case is worth\n * (coding standards §7). Assigning a mesh the material it already has is a no-op in Lite, so a\n * rebuild after a real change is idempotent.\n *\n * @param overrides - Source glTF material name to replacement material.\n */\n applyOverrides(overrides: ReadonlyMap<string, LiteMaterial>): void {\n if (overrides.size === this.#overrideCount) {\n return;\n }\n this.#overrideCount = overrides.size;\n if (overrides.size > 0) {\n overrideSubtreeMaterials(this.root, overrides);\n }\n }\n\n /**\n * Removes the subtree from the scene and gives back its share of the template's buffers.\n *\n * @param scene - The render scene.\n */\n destroy(scene: LiteScene): void {\n this.#asset.releaseInstance();\n removeMeshFromScene(scene, this.root);\n }\n}\n","import { Component } from \"../component/component.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { linkParent } from \"../lite/node.js\";\nimport { asset, bool, map } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport { ModelInstance } from \"./gpu/model-instance.js\";\nimport { MaterialAsset } from \"./material-asset.js\";\nimport { ModelAsset } from \"./model-asset.js\";\nimport { rendererInternals } from \"./renderer.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { ComponentHooks } from \"../component/component.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { LiteAnimationGroup, LiteSkeleton } from \"../lite/gpu/gltf.js\";\nimport type { LiteMesh } from \"../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../lite/material.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `Model` component (`docs/architecture/07-rendering.md` §2.4): one instance of a loaded glTF,\n * cloned under the entity's node.\n *\n * ## The instanced subtree is opaque\n *\n * §2.4 is explicit that the Lite subtree \"is not expanded into entities in the MVP\": one entity\n * holds one model, and the glTF nodes inside it are reachable by name through\n * {@link Model.nodes} rather than as entities of their own. {@link Model.attachToNode} covers the\n * case that actually needs an entity inside the model — a weapon in a hand — by parenting an\n * entity's node under a glTF node, which makes it follow that bone with no per-frame copy.\n *\n * ## Decisions the documents left open\n *\n * - **glTF cameras and lights are ignored, and Phase 2 has no way to ask otherwise.** §2.4 says\n * they are imported only when `importLights`/`importCameras` are set in the asset's\n * `.meta.json`. Lite gates cameras behind a process-global `enableGltfCameras()` that must run\n * before the **first** load (`src/lite/render-features.ts`), so a per-asset sidecar flag cannot\n * decide it: whichever asset loads first would fix the answer for every later one. Rather than\n * ship a flag that silently means \"whatever the first model wanted\", Phase 2 imports neither and\n * the adapter keeps `enableGltfCameraImport` ready for the phase that adds a project-level\n * setting. Lights inside a container are shallow-copied by Lite's own clone and are not added to\n * the scene by ignifx, so they never light anything.\n * - **`materialOverrides` matches on the glTF material *name*.** §2.4 says \"by material name\",\n * which is the only stable identifier a glTF gives a material. Phase 2 records the map and\n * applies it to the nodes whose material carries that name; a name nothing matches is ignored.\n * - **`animations` are exposed, not advanced.** ADR-0003 gives every clock to ignifx, so the\n * loader strips the clips off the container and this component republishes them. Playing them is\n * `@ignifx/3d`'s animator; in Phase 2 they are read-only metadata, and the property is `@beta`\n * because its element type is Lite's.\n *\n * ## Shadows are the whole subtree, decided once\n *\n * `castShadows` and `receiveShadows` mean for a model exactly what they mean for a `MeshRenderer`\n * (§2.3, §2.4): the instance contributes to `setShadowTaskCasterMeshes` while it casts, and Lite's\n * per-mesh `receiveShadows` is written across it. Both are answered from the mesh list\n * {@link ModelInstance} collects when the subtree is instantiated, never by walking the clone tree\n * per frame — the tree's shape is fixed once `instantiateContainer` built it (coding standards §7).\n * Instantiating a model, hiding it, or flipping `castShadows` reports a caster change through\n * {@link Model.consumeCasterChange}, which is what makes the `PreRender` system rebuild the caster\n * lists that frame. Destroying one cannot: the component has left the world's list by the time the\n * system runs, so `onDetach` raises `RendererImpl.needsCasterRebuild` instead and the next frame\n * picks it up.\n *\n * ## Headless\n *\n * A headless `ModelAsset` has no container, so there is nothing to clone: the component keeps its\n * fields, reports an empty `nodes` map and no animations, touches no scene, and casts nothing.\n */\n\n/**\n * The empty node map a model without an instance reports, built once on first use and shared from\n * then on. It is a lazy cache rather than a module-scope constant because a `Map` allocates, and\n * coding standards §4 keeps allocation out of import time.\n */\nlet noNodes: ReadonlyMap<string, LiteSceneNode> | null = null;\n\n/**\n * The shared empty node map.\n *\n * @returns A map that is always empty; every caller sees the same instance.\n */\nfunction emptyNodes(): ReadonlyMap<string, LiteSceneNode> {\n noNodes ??= new Map<string, LiteSceneNode>();\n return noNodes;\n}\n\n/** The empty clip list a model without an asset reports. */\nconst NO_ANIMATIONS: readonly LiteAnimationGroup[] = Object.freeze([]);\n\n/** The empty skeleton list a model without an asset reports. */\nconst NO_SKELETONS: readonly LiteSkeleton[] = Object.freeze([]);\n\n/**\n * One instance of a loaded model (`docs/architecture/07-rendering.md` §2.4).\n *\n * @example\n * ```ts\n * const hero = await app.assets.loadAsync<ModelAsset>(\"models/hero.glb\");\n * const entity = world.createEntity(\"Hero\");\n * const model = entity.addComponent(Model, { model: hero.retain() });\n * model.attachToNode(\"hand.R\", sword);\n * ```\n *\n * @public\n */\nexport class Model extends Component implements ComponentHooks {\n /** The namespaced registration id. */\n static typeId = \"ignifx/Model\";\n\n /** One model per entity: a second instance under the same transform wants its own entity. */\n static allowMultiple = false;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = modelSchema();\n\n declare model: AssetHandle<ModelAsset> | null;\n\n declare materialOverrides: Record<string, AssetHandle<MaterialAsset> | null>;\n\n declare castShadows: boolean;\n\n declare receiveShadows: boolean;\n\n declare pickable: boolean;\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(Model.schema));\n }\n\n #asset: ModelAsset | null = null;\n\n #instance: ModelInstance | null = null;\n\n #appliedCastShadows = false;\n\n /**\n * The glTF nodes of this instance, by their names in the file.\n *\n * @remarks\n * The map is the instance's own, so two `Model`s of one asset never hand out each other's nodes.\n * It is empty until the asset is loaded, and under a headless app.\n *\n * @returns The nodes, keyed by glTF node name.\n */\n get nodes(): ReadonlyMap<string, LiteSceneNode> {\n return this.#instance?.nodes ?? emptyNodes();\n }\n\n /**\n * The clips the file declared.\n *\n * @remarks\n * Unstable: these are Lite's own animation groups, and ignifx does not advance them in Phase 2\n * (ADR-0003 — `@ignifx/3d`'s animator owns playback).\n *\n * @returns The clips, in load order.\n *\n * @beta\n */\n get animations(): readonly LiteAnimationGroup[] {\n return this.#asset?.animations ?? NO_ANIMATIONS;\n }\n\n /**\n * The skeletons the file declared. Empty unless the `boneControl` rendering feature was on before\n * the asset loaded.\n *\n * @returns The skeletons.\n *\n * @beta\n */\n get skeletons(): readonly LiteSkeleton[] {\n return this.#asset?.skeletons ?? NO_SKELETONS;\n }\n\n /**\n * The Babylon Lite objects this instance owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The cloned root, or `null` when there is nothing instantiated.\n */\n get lite(): { readonly root: LiteSceneNode | null } {\n return { root: this.#instance?.root ?? null };\n }\n\n /**\n * Parents an entity under one of the model's glTF nodes — the \"weapon in hand\" case\n * (`docs/architecture/07-rendering.md` §2.4).\n *\n * @remarks\n * The entity keeps its **local** transform, so it lands at the node's origin and then follows it\n * for free: Lite composes `parentWorld × local` on every read, so a bone attachment costs no\n * per-frame work at all. Detach by re-parenting the entity in the ordinary way.\n *\n * @param nodeName - The glTF node name, as the file spells it.\n * @param entity - The entity to attach.\n * @returns `true` when the node exists and the entity was attached.\n *\n * @example\n * ```ts\n * model.attachToNode(\"hand.R\", sword);\n * ```\n */\n attachToNode(nodeName: string, entity: Entity): boolean {\n const node = this.nodes.get(nodeName);\n if (node === undefined) {\n return false;\n }\n linkParent(entityInternals(entity).node, node);\n return true;\n }\n\n /** Nothing to do at attach: the instance is built on the first sync, once `model` is decoded. */\n onAttach(): void {\n this.#asset = null;\n }\n\n /** Removes the instance from the scene and gives back its share of the template's buffers. */\n onDetach(): void {\n const renderer = rendererInternals(this.app.renderer);\n // A destroyed model leaves the world's component list, so the `PreRender` system will never ask\n // it for casters again — and would otherwise hand the generators a list still holding meshes\n // that are no longer in the scene. `needsCasterRebuild` is the one signal that survives the\n // component. It is raised unconditionally: a model that was not casting rebuilds to the same\n // list, so the flag says \"the caster set may have moved\", which is exactly what is true here.\n renderer.needsCasterRebuild = true;\n this.#appliedCastShadows = false;\n this.#release(renderer);\n }\n\n /**\n * Instantiates the template when `model` changed, then writes the flags that changed. The\n * `PreRender` system calls it.\n *\n * @param renderer - The rendering service, for the scene.\n * @returns `true` when the scene's renderable set changed.\n *\n * @internal\n */\n sync(renderer: RendererImpl): boolean {\n const changed = this.#ensureInstance(renderer);\n // The map is resolved whether or not there is an instance: it is the component's own state,\n // and resolving it here keeps the instance half free of asset-handle bookkeeping.\n const overrides = this.#resolvedOverrides();\n const instance = this.#instance;\n if (instance === null) {\n return changed;\n }\n instance.applyOverrides(overrides);\n instance.applyReceiveShadows(this.receiveShadows);\n instance.applyVisible(this.isEnabledInHierarchy);\n return changed;\n }\n\n /**\n * Appends every mesh of the instantiated subtree to a shadow caster list, when the model casts.\n *\n * @param out - The caster list being built.\n *\n * @internal\n */\n collectCasters(out: LiteMesh[]): void {\n if (this.castShadows) {\n this.#instance?.collectCasters(out);\n }\n }\n\n /**\n * Whether the caster contribution of this model changed since the last frame.\n *\n * @returns `true` when `castShadows` or visibility moved — which covers the model being\n * instantiated, destroyed, hidden, or shown, because each of those moves visibility.\n *\n * @internal\n */\n consumeCasterChange(): boolean {\n const casting = this.castShadows && this.#instance?.isVisible === true;\n const changed = casting !== this.#appliedCastShadows;\n this.#appliedCastShadows = casting;\n return changed;\n }\n\n /**\n * The override map with every entry resolved to a loaded Lite material.\n *\n * @returns Source glTF material name to replacement material; empty when nothing resolved.\n */\n #resolvedOverrides(): ReadonlyMap<string, LiteMaterial> {\n const byName = new Map<string, LiteMaterial>();\n for (const name of Object.keys(this.materialOverrides)) {\n const handle = this.materialOverrides[name];\n if (handle != null && handle.state === \"loaded\") {\n byName.set(name, handle.value.lite.material);\n }\n }\n return byName;\n }\n\n /**\n * Builds or rebuilds the instance when the `model` field changed.\n *\n * @param renderer - The rendering service, for the scene.\n * @returns `true` when a subtree was added to or removed from the scene.\n */\n #ensureInstance(renderer: RendererImpl): boolean {\n const loaded = this.model?.state === \"loaded\" ? this.model.value : null;\n if (loaded === this.#asset) {\n return false;\n }\n this.#release(renderer);\n this.#asset = loaded;\n if (loaded === null) {\n return false;\n }\n const instantiation = loaded.instantiate(entityInternals(this.entity).node);\n if (instantiation === null) {\n return false;\n }\n this.#instance = new ModelInstance(renderer.scene, loaded, instantiation, {\n entity: this.entity.handle,\n component: this.handle,\n });\n return true;\n }\n\n /**\n * Removes the instantiated subtree from the scene.\n *\n * @param renderer - The rendering service, for the scene.\n */\n #release(renderer: RendererImpl): void {\n const instance = this.#instance;\n this.#instance = null;\n this.#asset = null;\n instance?.destroy(renderer.scene);\n }\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function, not at module scope: a schema field is a function\n * call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4).\n */\nfunction modelSchema(): Schema {\n return defineSchema({\n model: asset(ModelAsset, { tooltip: \"The glTF template to instantiate.\" }),\n materialOverrides: map(asset(MaterialAsset), { tooltip: \"Replaces a glTF material, by its name.\" }),\n castShadows: bool(true, { tooltip: \"Whether the instance is rendered into shadow maps.\" }),\n receiveShadows: bool(true, { tooltip: \"Whether shadow maps darken the instance.\" }),\n pickable: bool(true, { tooltip: \"Whether picking considers the instance at all.\" }),\n });\n}\n","import {\n addTask,\n buildFrameGraphTask,\n createBloomPostProcessTask,\n createImageProcessingTask,\n createRenderTarget,\n createSmaaPostProcessTask,\n getFrameGraph,\n} from \"@babylonjs/lite\";\nimport type {\n BloomPostProcessTask,\n EngineContext,\n RenderTarget,\n SceneContext,\n SmaaPostProcessTask,\n SurfaceContext,\n Task,\n} from \"@babylonjs/lite\";\n\n/**\n * Post-processing (`docs/architecture/07-rendering.md` §2.7): the three effects the MVP ships —\n * bloom, SMAA, and image processing — and how they are wired into a scene's frame graph.\n *\n * Everything here is `@internal`, and every entry point needs a device.\n *\n * ## How a task joins the frame graph (verified against `@babylonjs/lite@1.27.0`)\n *\n * A scene's frame graph is an ordered array of tasks. `createSceneContext` appends the default\n * render task, named `\"scene\"`, at creation; `registerSceneWithShadowSupport` unshifts a task named\n * `\"shadow\"` in front of it (`lib/scene/scene-core.js`). `getFrameGraph(scene)` returns a\n * `FrameGraph` whose public surface is only `build`/`execute`/`dispose` (`index.d.ts` 5367) — **the\n * default render task itself is not reachable through any public API**, so `addTaskAfter(scene,\n * task, sceneRenderTask)` cannot be written. What can be written is `addTask(scene, task)`, which\n * appends to the end of the array (`lib/frame-graph/frame-graph-actions.js`) and therefore already\n * runs after the render task. {@link appendPostProcessTask} is that call, and a chain of effects is\n * built by appending them in order.\n *\n * There is also no public *remove*: `FrameGraph.dispose` frees everything, and individual tasks can\n * only be neutralised. {@link setPostProcessTaskEnabled} flips `Task.executionEnabled`, which makes\n * the frame graph skip every pass of the task while keeping it recorded\n * (`lib/frame-graph/frame-graph.js`), and {@link disposePostProcessTask} frees its GPU resources.\n * A disabled task costs one array entry and one branch per frame. Both gaps are recorded in\n * ADR-0002's validation table.\n *\n * ## Sources and targets\n *\n * Every post-process task takes a `sourceTexture` and writes to a `targetTexture`, defaulting to\n * the surface's swapchain target.\n *\n * **A chain can never read the swapchain.** `createSurface` configures the canvas context with no\n * `usage` (`lib/engine/surface.js` 30), so its texture is `RENDER_ATTACHMENT` only and binding it\n * as a `sourceTexture` fails WebGPU validation, taking the whole frame's command buffer with it.\n * Writing *into* the swapchain is fine, and both a post-process task and a copy task have a special\n * path for it. So a chain reads the offscreen colour the scene was rendered into\n * (`./render-path.ts`) and ping-pongs through {@link createChainColorTarget} links until its last\n * effect writes {@link surfaceRenderTarget}.\n *\n * `createImageProcessingTask` is the exception that shapes the chain's order: it writes\n * `engine.scRT` unconditionally, with no `targetTexture` at all\n * (`lib/frame-graph/image-processing-task.js`), so it can only ever be the **last** effect.\n */\n\n/**\n * A frame-graph task a `PostProcessStack` records, re-exported under an ignifx name so feature code\n * can name the type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4, coding\n * standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @internal\n */\nexport type LitePostProcessTask = Task;\n\n/**\n * A colour attachment a post-process task reads or writes, re-exported under an ignifx name.\n *\n * @internal\n */\nexport type LiteRenderTarget = RenderTarget;\n\n/**\n * The bloom settings an ignifx `PostProcessStack` entry declares.\n *\n * @internal\n */\nexport interface BloomSettings {\n /** How strongly the glow is mixed back in. */\n readonly weight?: number;\n /** The blur kernel width, in pixels. */\n readonly kernel?: number;\n /** The luminance above which a pixel glows. */\n readonly threshold?: number;\n /** An exposure applied while extracting highlights. */\n readonly exposure?: number;\n /** The fraction of full resolution the blur runs at. */\n readonly scale?: number;\n}\n\n/**\n * The SMAA settings an ignifx `PostProcessStack` entry declares.\n *\n * @internal\n */\nexport interface SmaaSettings {\n /** The luma difference that counts as an edge. Lite defaults to 0.05. */\n readonly threshold?: number;\n /** How far the pattern search runs along an edge, in pixels. */\n readonly maxSearchSteps?: number;\n /** Whether 45-degree patterns are detected. Off by default, and Lite measured it as no better. */\n readonly diagonalDetection?: boolean;\n /** Whether corner patterns are attenuated. */\n readonly cornerDetection?: boolean;\n /** Set when the source is an sRGB view, so edge detection re-encodes before taking luma. */\n readonly sourceIsSrgb?: boolean;\n}\n\n/**\n * The surface's swapchain render target — where the last effect in a chain writes.\n *\n * @param surface - The surface. The engine is its own primary surface.\n * @returns The colour-only target wrapping the swapchain texture.\n *\n * @internal\n */\nexport function surfaceRenderTarget(surface: SurfaceContext): RenderTarget {\n return surface.scRT;\n}\n\n/**\n * Creates one ping-pong colour target for an effect chain, sized to the surface.\n *\n * @remarks\n * An ordinary `createRenderTarget`, not `createRenderTargetTexture`: the lazy kind is allocated by\n * whichever task first *owns* it as a target (`buildRenderTarget` inside `PostProcessTask.record`),\n * with `RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC | COPY_DST`\n * (`lib/engine/render-target.js`), and its size is re-resolved from the surface on every frame-graph\n * build. That is what lets the chain follow a canvas resize; the eager kind cannot, and Lite refuses\n * a `SurfaceContext` as its size for that reason (error 571).\n *\n * The consequence is an ordering rule the chain already keeps: a link must be **written** by an\n * earlier task than the one that reads it, or the reader finds no colour texture and Lite raises\n * error 107.\n *\n * @param surface - The surface whose colour format and size the target matches.\n * @param label - A debug label for the allocated GPU texture.\n * @returns The target.\n *\n * @internal\n */\nexport function createChainColorTarget(surface: SurfaceContext, label: string): RenderTarget {\n return createRenderTarget({ lbl: label, format: surface.format, samples: 1, size: surface });\n}\n\n/**\n * Creates a bloom task.\n *\n * @param engine - The engine that owns its GPU resources.\n * @param scene - The scene it belongs to.\n * @param source - The colour target it reads.\n * @param target - The colour target it writes, or `null` for the surface swapchain.\n * @param settings - The declared tuning.\n * @returns The task. Insert it with {@link appendPostProcessTask}.\n *\n * @example\n * ```ts\n * const bloom = createBloomTask(engine, scene, sceneColor, surfaceRenderTarget(engine), { threshold: 0.9 });\n * appendPostProcessTask(scene, bloom);\n * ```\n *\n * @internal\n */\nexport function createBloomTask(\n engine: EngineContext,\n scene: SceneContext,\n source: RenderTarget,\n target: RenderTarget | null,\n settings: BloomSettings,\n): BloomPostProcessTask {\n const config: {\n name: string;\n sourceTexture: RenderTarget;\n targetTexture: RenderTarget | null;\n weight?: number;\n kernel?: number;\n threshold?: number;\n exposure?: number;\n bloomScale?: number;\n } = { name: \"ignifx:bloom\", sourceTexture: source, targetTexture: target };\n if (settings.weight !== undefined) {\n config.weight = settings.weight;\n }\n if (settings.kernel !== undefined) {\n config.kernel = settings.kernel;\n }\n if (settings.threshold !== undefined) {\n config.threshold = settings.threshold;\n }\n if (settings.exposure !== undefined) {\n config.exposure = settings.exposure;\n }\n if (settings.scale !== undefined) {\n config.bloomScale = settings.scale;\n }\n return createBloomPostProcessTask(config, engine, scene);\n}\n\n/**\n * Creates a subpixel morphological anti-aliasing task.\n *\n * @remarks\n * SMAA needs a single-sample source (Lite error 108), so an MSAA scene must resolve first. The\n * offscreen render path always hands the chain the resolved single-sample colour\n * (`./render-path.ts`, the render task's `rst`).\n *\n * @param engine - The engine that owns its GPU resources.\n * @param scene - The scene it belongs to.\n * @param source - The colour target it reads.\n * @param target - The colour target it writes, or `null` for the surface swapchain.\n * @param settings - The declared tuning.\n * @returns The task.\n *\n * @internal\n */\nexport function createSmaaTask(\n engine: EngineContext,\n scene: SceneContext,\n source: RenderTarget,\n target: RenderTarget | null,\n settings: SmaaSettings,\n): SmaaPostProcessTask {\n const config: {\n name: string;\n sourceTexture: RenderTarget;\n targetTexture: RenderTarget | null;\n threshold?: number;\n maxSearchSteps?: number;\n diagonalDetection?: boolean;\n cornerDetection?: boolean;\n sourceIsSrgb?: boolean;\n } = { name: \"ignifx:smaa\", sourceTexture: source, targetTexture: target };\n if (settings.threshold !== undefined) {\n config.threshold = settings.threshold;\n }\n if (settings.maxSearchSteps !== undefined) {\n config.maxSearchSteps = settings.maxSearchSteps;\n }\n if (settings.diagonalDetection !== undefined) {\n config.diagonalDetection = settings.diagonalDetection;\n }\n if (settings.cornerDetection !== undefined) {\n config.cornerDetection = settings.cornerDetection;\n }\n if (settings.sourceIsSrgb !== undefined) {\n config.sourceIsSrgb = settings.sourceIsSrgb;\n }\n return createSmaaPostProcessTask(config, engine, scene);\n}\n\n/**\n * Creates a task that applies the scene's exposure, contrast, and tone mapping as a full-screen\n * pass, straight onto the swapchain.\n *\n * @remarks\n * It has no target of its own: `execute` begins a render pass on `engine.scRT._colorView` every\n * frame (`lib/frame-graph/image-processing-task.js`), so it is always the last task of a chain. It\n * samples with `textureLoad` at the fragment's own pixel coordinate, so `source` must be the same\n * size as the swapchain — which every target sized to the surface is.\n *\n * Only needed when the scene has no `Environment` component driving `setSceneImageProcessing`; the\n * two are alternatives, not a chain (`docs/architecture/07-rendering.md` §2.7).\n *\n * @param engine - The engine that owns its GPU resources.\n * @param scene - The scene it belongs to.\n * @param source - The colour target it grades. `resolveImageProcessingTexture` accepts a\n * `RenderTarget` and reads its colour texture.\n * @returns The task.\n *\n * @internal\n */\nexport function createImageProcessingPass(engine: EngineContext, scene: SceneContext, source: RenderTarget): Task {\n return createImageProcessingTask({ name: \"ignifx:image-processing\", source }, engine, scene);\n}\n\n/**\n * Appends a post-process task to a scene's frame graph, after the render pass and after every task\n * appended before it, and records it so it runs from the next frame.\n *\n * @remarks\n * `addTask` only puts the task in the array; its passes are recorded when the frame graph is built.\n * `buildFrameGraphTask` (`index.d.ts` 1403) records and initialises **just this task**, which is\n * what makes a task added to a live scene take effect without rebuilding — and reallocating — every\n * other task's resources.\n *\n * @param scene - The scene whose frame graph to extend.\n * @param task - The task to append.\n *\n * @internal\n */\nexport function appendPostProcessTask(scene: SceneContext, task: Task): void {\n addTask(scene, task);\n buildFrameGraphTask(getFrameGraph(scene), task);\n}\n\n/**\n * Switches a post-process task on or off without removing it from the frame graph.\n *\n * @remarks\n * The only way to stop a task: Lite exposes no removal. A disabled task keeps its GPU resources and\n * its recorded passes, and costs one branch per frame.\n *\n * @param task - The task to gate.\n * @param enabled - `false` to skip every pass of the task.\n *\n * @internal\n */\nexport function setPostProcessTaskEnabled(task: Task, enabled: boolean): void {\n task.executionEnabled = enabled;\n}\n\n/**\n * Frees a post-process task's GPU resources.\n *\n * @remarks\n * Disable it first: the task stays in the frame graph, and a disposed task that still executes is a\n * use-after-free.\n *\n * @param task - The task to release.\n *\n * @internal\n */\nexport function disposePostProcessTask(task: Task): void {\n task.dispose();\n}\n","import {\n appendPostProcessTask,\n createBloomTask,\n createChainColorTarget,\n createImageProcessingPass,\n createSmaaTask,\n disposePostProcessTask,\n setPostProcessTaskEnabled,\n surfaceRenderTarget,\n} from \"../../lite/gpu/post-process.js\";\nimport type { LitePostProcessTask, LiteRenderTarget } from \"../../lite/gpu/post-process.js\";\nimport type { ScenePresenter } from \"../../lite/gpu/render-path.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { BloomEffectSettings, SmaaEffectSettings } from \"../post-process-stack.js\";\n\n/**\n * The frame-graph half of `PostProcessStack` (`docs/architecture/07-rendering.md` §2.7).\n *\n * Device-only: a task cannot be created, recorded, enabled, or disposed without an engine and a\n * frame graph. `src/render/gpu/**` is excluded from the Node coverage floor for exactly that reason;\n * the browser project measures it.\n *\n * ## What the chain is plugged into\n *\n * With `rendering.features.postProcessing` on, the scene is not drawn into the swapchain at all. It\n * is drawn into an offscreen, single-sample colour target and a copy task composites that onto the\n * swapchain (`src/lite/gpu/render-path.ts`). The chain reads that target — the swapchain itself\n * carries no `TEXTURE_BINDING` and sampling it rejects the frame — ping-pongs through two links of\n * its own, and lands its last effect on the swapchain, at which point the compositing copy is\n * switched off:\n *\n * ```text\n * scene → sceneColor ─ bloom ─→ link A ─ smaa ─→ swapchain\n * ```\n *\n * Every target is sized by the surface and rebuilt by `frameGraph.build()`, so a canvas resize needs\n * nothing from this class.\n *\n * ## Image processing is always last\n *\n * `createImageProcessingTask` writes `engine.scRT` and takes no target\n * (`lib/frame-graph/image-processing-task.js`), so it cannot hand its output to another effect. The\n * chain moves it to the end whatever `order` the component declares, rather than silently producing\n * a frame in which the effects after it read a target nobody wrote.\n */\n\n/** What an effect entry contributes to the chain. */\nexport interface PostProcessEffectRequest {\n /** Which effect to build. */\n readonly name: \"bloom\" | \"smaa\" | \"imageProcessing\";\n /** The bloom tuning, read only for the bloom entry. */\n readonly bloom: BloomEffectSettings;\n /** The SMAA tuning, read only for the SMAA entry. */\n readonly smaa: SmaaEffectSettings;\n /** Whether the chain's source is an sRGB view, which SMAA's edge detection needs to know. */\n readonly sourceIsSrgb: boolean;\n}\n\n/** A recorded chain, and the handle that takes it down again. */\nexport class PostProcessChain {\n readonly #tasks: LitePostProcessTask[] = [];\n\n readonly #presenter: ScenePresenter;\n\n /**\n * Records the requested effects into a scene's frame graph.\n *\n * @param engine - The engine that owns the tasks' GPU resources; it is also the surface.\n * @param scene - The scene whose frame graph to extend.\n * @param presenter - The offscreen render path: the colour the chain reads, and the compositing\n * blit it takes over from.\n * @param effects - The enabled effects, first to last.\n */\n constructor(\n engine: LiteEngine,\n scene: LiteScene,\n presenter: ScenePresenter,\n effects: readonly PostProcessEffectRequest[],\n ) {\n this.#presenter = presenter;\n const ordered = imageProcessingLast(effects);\n if (ordered.length === 0) {\n return;\n }\n const swapchain = surfaceRenderTarget(engine);\n const links: LiteRenderTarget[] = [];\n let source: LiteRenderTarget = presenter.sceneColor;\n for (let index = 0; index < ordered.length; index += 1) {\n const effect = ordered[index];\n if (effect === undefined) {\n continue;\n }\n const isLast = index === ordered.length - 1;\n if (effect.name === \"imageProcessing\") {\n // It writes the swapchain itself, so it needs no target and can only be last.\n this.#record(scene, createImageProcessingPass(engine, scene, source));\n continue;\n }\n const target = isLast ? swapchain : nextLink(engine, links, source);\n this.#record(scene, this.#createEffect(engine, scene, effect, source, target));\n source = target;\n }\n // The chain's last task now writes the swapchain, so the compositing blit would only be\n // overwritten. Turning it off is what keeps the extra full-screen pass off the frame budget.\n presenter.setPresentEnabled(false);\n }\n\n /**\n * How many frame-graph tasks the chain recorded.\n *\n * @returns The task count.\n */\n get taskCount(): number {\n return this.#tasks.length;\n }\n\n /**\n * Switches every recorded task on or off. Lite offers no removal, so this is what \"disable the\n * stack\" means.\n *\n * @remarks\n * Switching the chain off switches the compositing blit back on, so the swapchain still receives\n * the frame — a disabled stack presents the plain scene rather than a stale one.\n *\n * @param enabled - `false` to skip every pass.\n */\n setEnabled(enabled: boolean): void {\n for (let index = 0; index < this.#tasks.length; index += 1) {\n const task = this.#tasks[index];\n if (task !== undefined) {\n setPostProcessTaskEnabled(task, enabled);\n }\n }\n if (this.#tasks.length > 0) {\n this.#presenter.setPresentEnabled(!enabled);\n }\n }\n\n /** Disables and disposes every recorded task, in the order Lite requires. */\n dispose(): void {\n for (let index = 0; index < this.#tasks.length; index += 1) {\n const task = this.#tasks[index];\n if (task !== undefined) {\n // Disable first: a disposed task that still executes is a use-after-free.\n setPostProcessTaskEnabled(task, false);\n disposePostProcessTask(task);\n }\n }\n if (this.#tasks.length > 0) {\n this.#presenter.setPresentEnabled(true);\n }\n this.#tasks.length = 0;\n }\n\n /**\n * Appends one task to the scene's frame graph and remembers it.\n *\n * @param scene - The scene whose frame graph to extend.\n * @param task - The task.\n */\n #record(scene: LiteScene, task: LitePostProcessTask): void {\n appendPostProcessTask(scene, task);\n this.#tasks.push(task);\n }\n\n /**\n * Builds one bloom or SMAA task.\n *\n * @param engine - The engine that owns its GPU resources.\n * @param scene - The scene it belongs to.\n * @param effect - The requested effect and its tuning.\n * @param source - The colour target it reads.\n * @param target - The colour target it writes.\n * @returns The task.\n */\n #createEffect(\n engine: LiteEngine,\n scene: LiteScene,\n effect: PostProcessEffectRequest,\n source: LiteRenderTarget,\n target: LiteRenderTarget,\n ): LitePostProcessTask {\n if (effect.name === \"bloom\") {\n const settings = effect.bloom;\n return createBloomTask(engine, scene, source, target, {\n weight: settings.weight,\n kernel: settings.kernel,\n threshold: settings.threshold,\n exposure: settings.exposure,\n scale: settings.scale,\n });\n }\n const settings = effect.smaa;\n return createSmaaTask(engine, scene, source, target, {\n threshold: settings.threshold,\n maxSearchSteps: settings.maxSearchSteps,\n diagonalDetection: settings.diagonalDetection,\n cornerDetection: settings.cornerDetection,\n sourceIsSrgb: effect.sourceIsSrgb,\n });\n }\n}\n\n/**\n * The requested effects with the image-processing pass moved to the end, where Lite's task can only\n * work.\n *\n * @param effects - The enabled effects, in the order the component declared.\n * @returns The order the chain records. The array is fresh, so the component's own list is untouched.\n *\n * @internal\n */\nexport function imageProcessingLast(effects: readonly PostProcessEffectRequest[]): readonly PostProcessEffectRequest[] {\n const ordered: PostProcessEffectRequest[] = [];\n let grading: PostProcessEffectRequest | null = null;\n for (let index = 0; index < effects.length; index += 1) {\n const effect = effects[index];\n if (effect === undefined) {\n continue;\n }\n if (effect.name === \"imageProcessing\") {\n grading = effect;\n } else {\n ordered.push(effect);\n }\n }\n if (grading !== null) {\n ordered.push(grading);\n }\n return ordered;\n}\n\n/**\n * The ping-pong target the next effect writes: never the one it is reading.\n *\n * @remarks\n * Two links are enough for any chain length, and they are created on demand so a chain of one\n * allocates none at all.\n *\n * @param engine - The engine, which is also the surface the links are sized to.\n * @param links - The links created so far; this appends to it.\n * @param source - What the next effect reads.\n * @returns A target that is not `source`.\n */\nfunction nextLink(engine: LiteEngine, links: LiteRenderTarget[], source: LiteRenderTarget): LiteRenderTarget {\n for (let index = 0; index < links.length; index += 1) {\n const link = links[index];\n if (link !== undefined && link !== source) {\n return link;\n }\n }\n const created = createChainColorTarget(engine, `ignifx:post-process-${String(links.length)}`);\n links.push(created);\n return created;\n}\n","import { Component } from \"../component/component.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { bool, f32, i32, record, u32 } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport { PostProcessChain } from \"./gpu/post-process-chain.js\";\nimport { rendererInternals } from \"./renderer.js\";\nimport type { PostProcessEffectRequest } from \"./gpu/post-process-chain.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { ComponentHooks } from \"../component/component.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `PostProcessStack` component (`docs/architecture/07-rendering.md` §2.7): the three effects the\n * MVP ships — bloom, SMAA, and image processing — inserted into the scene's frame graph.\n *\n * ## The schema is three records, not a discriminated list\n *\n * §2.7 describes an \"ordered list of effects\". A list of heterogeneous effect records needs either a\n * `custom()` field with a hand-written codec or a tagged union the schema kinds cannot express, and\n * neither is inspectable without extra tooling. Three optional records with an `order` each is the\n * simplest shape that round-trips through `encodeProps`/`decodeProps` unchanged, shows up in the\n * inspector with real field names and tooltips, and still lets a project reorder the chain. The\n * cost is that adding a fourth effect in Phase 7 adds a fourth record rather than a new list entry;\n * that is a schema addition, which the format already tolerates.\n *\n * ## It needs `rendering.features.postProcessing`, declared at app start\n *\n * A chain cannot read the swapchain: `createSurface` configures the canvas context with no `usage`\n * (`lib/engine/surface.js` 30), so its texture is `RENDER_ATTACHMENT` only, binding it as a sampled\n * texture fails WebGPU validation, and the whole frame's command buffer is rejected — a black page.\n * The scene therefore has to be rendered into an offscreen target instead, and *that* is a frame\n * graph decision made inside `createSceneContext`, before a component exists to ask for it\n * (`src/lite/gpu/render-path.ts`). So it is a rendering **feature**, declared with the others\n * (§1.1), and a stack attached without it logs `IGX-0710` once and does nothing.\n *\n * ## How the chain is wired\n *\n * ```text\n * scene ─→ sceneColor ─ bloom ─→ link ─ smaa ─→ swapchain\n * └─ present ─→ swapchain (switched off while the chain runs)\n * ```\n *\n * `sceneColor` is the offscreen target the render path drew into — single-sample, resolved from MSAA\n * when MSAA is on, and carrying the `TEXTURE_BINDING` the swapchain lacks. The chain ping-pongs\n * through targets of its own and its last effect writes the swapchain, which is when the render\n * path's compositing blit is disabled. Disable the stack and the blit comes back, so the swapchain\n * always receives the frame.\n *\n * `imageProcessing` is always recorded last, whatever `order` says: Lite's task writes `engine.scRT`\n * unconditionally and takes no target, so nothing can read what it produced.\n *\n * ## The one Lite limit this component still inherits\n *\n * **Nothing can be removed from a frame graph.** `executionEnabled = false` is the substitute, so\n * disabling an effect leaves its GPU resources allocated and costs one branch per frame. The\n * component disposes them at detach. Resizing, by contrast, is free: every target is sized by the\n * surface and reallocated by the frame-graph rebuild a resize triggers.\n */\n\n/**\n * The `bloom` record a `PostProcessStack` declares (`docs/architecture/07-rendering.md` §2.7).\n *\n * @public\n */\nexport interface BloomEffectSettings {\n /** Whether the glow pass runs. */\n enabled: boolean;\n /** Position in the chain; lower runs first. */\n order: number;\n /** How strongly the glow is mixed back in. */\n weight: number;\n /** The blur kernel width, in pixels. */\n kernel: number;\n /** The luminance above which a pixel glows. */\n threshold: number;\n /** An exposure applied while extracting highlights. */\n exposure: number;\n /** The fraction of full resolution the blur runs at. */\n scale: number;\n}\n\n/**\n * The `smaa` record a `PostProcessStack` declares (`docs/architecture/07-rendering.md` §2.7).\n *\n * @public\n */\nexport interface SmaaEffectSettings {\n /** Whether subpixel morphological anti-aliasing runs. */\n enabled: boolean;\n /** Position in the chain; lower runs first. */\n order: number;\n /** The luma difference that counts as an edge. */\n threshold: number;\n /** How far the pattern search runs along an edge, in pixels. */\n maxSearchSteps: number;\n /** Whether 45-degree patterns are detected. */\n diagonalDetection: boolean;\n /** Whether corner patterns are attenuated. */\n cornerDetection: boolean;\n}\n\n/**\n * The `imageProcessing` record a `PostProcessStack` declares\n * (`docs/architecture/07-rendering.md` §2.7).\n *\n * @public\n */\nexport interface ImageProcessingEffectSettings {\n /** Whether a full-screen grading pass runs. */\n enabled: boolean;\n /** Position in the chain; lower runs first. */\n order: number;\n}\n\n/**\n * One instance of a post-process chain, attached to the main camera's entity\n * (`docs/architecture/07-rendering.md` §2.7).\n *\n * @example\n * ```ts\n * cameraEntity.addComponent(PostProcessStack, {\n * bloom: { enabled: true, threshold: 0.85, weight: 0.4 },\n * smaa: { enabled: true },\n * });\n * ```\n *\n * @public\n */\nexport class PostProcessStack extends Component implements ComponentHooks {\n /** The namespaced registration id. */\n static typeId = \"ignifx/PostProcessStack\";\n\n /** One chain per camera entity; a second would fight the first for the swapchain. */\n static allowMultiple = false;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = postProcessSchema();\n\n declare bloom: BloomEffectSettings;\n\n declare smaa: SmaaEffectSettings;\n\n declare imageProcessing: ImageProcessingEffectSettings;\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(PostProcessStack.schema));\n }\n\n #chain: PostProcessChain | null = null;\n\n #built = \"\";\n\n #hasWarnedAboutFeature = false;\n\n /**\n * How many frame-graph tasks the stack has recorded.\n *\n * @returns The task count; `0` before the chain is built, under a headless app, and when the\n * `postProcessing` rendering feature is off.\n */\n get taskCount(): number {\n return this.#chain?.taskCount ?? 0;\n }\n\n /** Nothing to do at attach: the chain is built on the first sync that wants an effect. */\n onAttach(): void {\n this.#built = \"\";\n this.#hasWarnedAboutFeature = false;\n }\n\n /** Disables and disposes every task the stack recorded. */\n onDetach(): void {\n const chain = this.#chain;\n this.#chain = null;\n this.#built = \"\";\n chain?.dispose();\n }\n\n /**\n * Builds the chain the first time any effect is enabled, and switches individual effects on and\n * off after that. The `PreRender` system calls it.\n *\n * @param renderer - The rendering service, for the engine and the scene.\n *\n * @internal\n */\n sync(renderer: RendererImpl): void {\n const wanted = this.#chainKey();\n if (wanted !== this.#built && this.#chain === null) {\n this.#built = wanted;\n // The request list is the component's own state, so it is built whether or not there is a\n // device to record it into; only the recording is device-only.\n const requests = this.#requests(renderer.settings.srgb);\n const presenter = renderer.presenter;\n if (!renderer.isHeadless && presenter !== null) {\n this.#chain = new PostProcessChain(renderer.engine, renderer.scene, presenter, requests);\n }\n this.#warnAboutFeature(renderer, requests.length);\n return;\n }\n this.#warnAboutFeature(renderer, this.plannedChain().length);\n this.#chain?.setEnabled(this.isEnabledInHierarchy);\n }\n\n /**\n * Says once, at warning level, that the stack asks for effects the project did not opt into.\n *\n * @remarks\n * Headless does **not** suppress it, for the same reason the shadows warning is not suppressed: a\n * missing opt-in is a configuration problem, and a headless test is exactly where a project should\n * find out about it. A headless app has no presenter either way, so the check is on the feature\n * flag rather than on the presenter.\n *\n * @param renderer - The rendering service, for the feature flags and the log.\n * @param requestedEffects - How many effects the fields currently ask for.\n */\n #warnAboutFeature(renderer: RendererImpl, requestedEffects: number): void {\n if (this.#hasWarnedAboutFeature || requestedEffects === 0 || renderer.features.postProcessing) {\n return;\n }\n this.#hasWarnedAboutFeature = true;\n renderer.app.log.warn(\n `${CoreErrorCode.postProcessingFeatureOff}: {entity} asks for post-processing, but the ` +\n \"rendering.features.postProcessing opt-in is off, so the stack is inert. Declare it in the \" +\n \"rendering.features block of createApp() or ignifx.config.ts.\",\n this.entity.name,\n );\n }\n\n /**\n * The enabled effects, first to last, with the tuning each one needs.\n *\n * @param sourceIsSrgb - Whether the chain's input is an sRGB target, which decides where the\n * image-processing effect converts.\n * @returns The requests the frame-graph half records.\n */\n #requests(sourceIsSrgb: boolean): readonly PostProcessEffectRequest[] {\n const requests: PostProcessEffectRequest[] = [];\n for (const entry of this.#entries()) {\n if (entry.enabled) {\n requests.push({ name: entry.name, bloom: this.bloom, smaa: this.smaa, sourceIsSrgb });\n }\n }\n return requests;\n }\n\n /**\n * The chain the fields currently ask for, as an ordered list of effect names. It is what\n * {@link PostProcessStack.taskCount} would grow to on a device.\n *\n * @returns The effect names, first to last.\n *\n * @internal\n */\n plannedChain(): readonly string[] {\n const names: string[] = [];\n for (const entry of this.#entries()) {\n if (entry.enabled) {\n names.push(entry.name);\n }\n }\n return names;\n }\n\n /**\n * The identity of the chain the fields currently ask for: which effects are on, in which order.\n * A change to it while the chain already exists only flips `executionEnabled`, because Lite\n * cannot re-order a recorded frame graph.\n *\n * @returns The key.\n */\n #chainKey(): string {\n return this.plannedChain().join(\",\");\n }\n\n /**\n * The three effect records, as a uniform list ordered by their `order` fields.\n *\n * @returns The entries, first to last.\n */\n #entries(): readonly {\n readonly name: \"bloom\" | \"smaa\" | \"imageProcessing\";\n readonly enabled: boolean;\n readonly order: number;\n }[] {\n const entries = [\n { name: \"bloom\", enabled: this.bloom.enabled, order: this.bloom.order },\n { name: \"smaa\", enabled: this.smaa.enabled, order: this.smaa.order },\n { name: \"imageProcessing\", enabled: this.imageProcessing.enabled, order: this.imageProcessing.order },\n ] as const;\n return entries.toSorted((left, right) => left.order - right.order);\n }\n}\n\n/**\n * Reaches the rendering service from a stack, for the tests that drive `sync` by hand.\n *\n * @param stack - The component.\n * @returns The service.\n *\n * @internal\n */\nexport function rendererOfStack(stack: PostProcessStack): RendererImpl {\n return rendererInternals(stack.app.renderer);\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function, not at module scope: a schema field is a function\n * call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4).\n */\nfunction postProcessSchema(): Schema {\n return defineSchema({\n bloom: record(\n {\n enabled: bool(false, { tooltip: \"Whether the glow pass runs.\" }),\n order: i32(0, { tooltip: \"Position in the chain; lower runs first.\" }),\n weight: f32(0.15, { min: 0, tooltip: \"How strongly the glow is mixed back in.\" }),\n kernel: u32(64, { min: 1, tooltip: \"Blur kernel width, in pixels.\" }),\n threshold: f32(0.9, { min: 0, tooltip: \"The luminance above which a pixel glows.\" }),\n exposure: f32(1, { min: 0, tooltip: \"Exposure applied while extracting highlights.\" }),\n scale: f32(0.5, { min: 0.05, max: 1, tooltip: \"Fraction of full resolution the blur runs at.\" }),\n },\n { tooltip: \"Bloom.\" },\n ),\n smaa: record(\n {\n enabled: bool(false, { tooltip: \"Whether subpixel morphological anti-aliasing runs.\" }),\n order: i32(1, { tooltip: \"Position in the chain; lower runs first.\" }),\n threshold: f32(0.05, { min: 0, max: 1, tooltip: \"The luma difference that counts as an edge.\" }),\n maxSearchSteps: u32(16, { min: 1, tooltip: \"How far the pattern search runs along an edge.\" }),\n diagonalDetection: bool(false, { tooltip: \"Detect 45-degree patterns.\" }),\n cornerDetection: bool(false, { tooltip: \"Attenuate corner patterns.\" }),\n },\n { tooltip: \"SMAA anti-aliasing. Needs a single-sample source.\" },\n ),\n imageProcessing: record(\n {\n enabled: bool(false, { tooltip: \"Whether a full-screen grading pass runs.\" }),\n order: i32(2, { tooltip: \"Position in the chain; lower runs first.\" }),\n },\n { tooltip: \"Exposure, contrast, and tone mapping as a pass — the alternative to Environment.\" },\n ),\n });\n}\n","import { setSceneCamera } from \"../lite/camera.js\";\nimport { rebuildRenderables } from \"../lite/shadow.js\";\nimport { Camera } from \"./camera.js\";\nimport { Environment } from \"./environment.js\";\nimport { Light } from \"./light.js\";\nimport { MeshRenderer } from \"./mesh-renderer.js\";\nimport { Model } from \"./model.js\";\nimport { PostProcessStack } from \"./post-process-stack.js\";\nimport type { RendererImpl } from \"./renderer.js\";\nimport type { System, SystemContext } from \"../app/types.js\";\nimport type { LiteMesh } from \"../lite/gpu/mesh.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * The `PreRender` system that reconciles the render components with the Lite scene\n * (`docs/architecture/01-lifecycle-and-time.md` §3 step 6, `07-rendering.md` §2).\n *\n * ## What it does not do\n *\n * It does **not** copy transforms. A `Camera` is parented under its entity's node, a `Light` is\n * parented under its entity's node, and a `MeshRenderer`'s clone is parented under its entity's\n * node, so Lite composes `parentWorld × local` on every read and an entity that moved is already\n * where it should be (`src/lite/node.ts`). Copying would be work with no result.\n *\n * ## What it does\n *\n * 1. **Field reconciliation.** Every component compares each field with the value it last applied\n * and writes only what changed. That is what makes a scene file's props — decoded *after*\n * `addComponent` ran (`06-serialization-and-scene-format.md` §4 step 5) — reach Lite without the\n * components needing a dirty API of their own, and it is what makes a script's edit take effect\n * on the next frame with no bookkeeping at the call site.\n * 2. **Visibility.** `entity.activeInHierarchy && component.enabled` is materialised onto each\n * clone's `visible`. Never removal: Lite disposes a mesh that leaves its last scene.\n * 3. **One `rebuildSceneRenderables` per frame.** Adding a mesh, adding a light, or giving a light\n * a shadow generator all invalidate the per-mesh light index list and the compiled shader\n * permutation that renderables bake in (`index.d.ts` 9465). The call is expensive, so every\n * topology change in a frame is coalesced into one, fired at the end of the phase and not\n * awaited — it resolves on its own, and the frame must not block on it.\n * 4. **Main-camera selection.** The enabled camera with the highest `priority` becomes\n * `scene.camera` and `world.mainCamera`; ties break on creation order, so two cameras at the\n * same priority resolve deterministically. A world with no enabled camera logs `IGX-0706` once.\n * 5. **Shadow caster lists.** Lite keys a generator's caster list by array identity and re-preloads\n * the shadow pipeline whenever a **new** array arrives, so the list is rebuilt only in a frame\n * where the caster set actually changed, and the same array is handed to every casting light.\n * Both renderable components contribute: a `MeshRenderer` adds its one clone, a `Model` adds\n * every mesh of its instantiated subtree, and each reports its own change through\n * `consumeCasterChange`. A component destroyed between frames cannot report anything — it has\n * left the world's list — so it raises `renderer.needsCasterRebuild` from `onDetach` instead.\n * 6. **One environment.** The enabled `Environment` with the highest creation order wins; a second\n * one logs `IGX-0705` once per world.\n */\n\n/**\n * Where render synchronisation sits inside `PreRender`.\n *\n * @remarks\n * Late in the phase, so that interpolation, animation, and any extension that moves a transform in\n * `PreRender` have already run: this system reads the world the frame ends with\n * (`docs/architecture/03-scripting-and-components.md` §6 — core systems use `[-1000, 1000]`).\n *\n * @internal\n */\nexport const RENDER_SYNC_ORDER = 900;\n\n/**\n * Reconciles the render components with the Lite scene once per frame.\n *\n * @internal\n */\nexport class RenderSyncSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name: string = \"ignifx/render-sync\";\n\n readonly #renderer: RendererImpl;\n\n readonly #casters: LiteMesh[] = [];\n\n #hasLoggedMultipleEnvironments = false;\n\n #isRebuildDue = false;\n\n #isRebuildInFlight = false;\n\n #areCastersDirty = false;\n\n /**\n * Creates the system.\n *\n * @param renderer - The rendering service, which holds the render layer's per-app state.\n */\n constructor(renderer: RendererImpl) {\n this.#renderer = renderer;\n }\n\n /**\n * Runs one frame of render synchronisation.\n *\n * @param ctx - The world, the clock, the phase, and the frame delta.\n */\n update(ctx: SystemContext): void {\n this.sync(ctx.world);\n }\n\n /**\n * Reconciles one world with its Lite scene.\n *\n * @remarks\n * Separated from {@link RenderSyncSystem.update} because `app.start()` runs it **once before**\n * `registerScene`, so a world whose scene was built before the app started registers with its\n * cameras, lights, and meshes already in the Lite scene — the fast path\n * (`docs/architecture/07-rendering.md` §1.1: entities added afterwards go through the runtime\n * material-swap path instead).\n *\n * @param world - The world to reconcile.\n *\n * @internal\n */\n sync(world: World): void {\n const renderer = this.#renderer;\n const meshes = world.components(MeshRenderer);\n const models = world.components(Model);\n const lights = world.components(Light);\n const cameras = world.components(Camera);\n\n let topologyChanged = false;\n // A component that was destroyed since the last frame is no longer in any of these lists, so\n // the flag it raised in `onDetach` is the only way its meshes leave the caster lists.\n let castersChanged = renderer.needsCasterRebuild;\n renderer.needsCasterRebuild = false;\n for (let index = 0; index < meshes.length; index += 1) {\n const renderable = meshes[index];\n if (renderable === undefined) {\n continue;\n }\n topologyChanged = renderable.sync(renderer) || topologyChanged;\n castersChanged = renderable.consumeCasterChange() || castersChanged;\n }\n for (let index = 0; index < models.length; index += 1) {\n const model = models[index];\n if (model !== undefined) {\n topologyChanged = model.sync(renderer) || topologyChanged;\n castersChanged = model.consumeCasterChange() || castersChanged;\n }\n }\n for (let index = 0; index < lights.length; index += 1) {\n const light = lights[index];\n if (light === undefined) {\n continue;\n }\n const changed = light.sync(renderer);\n topologyChanged = changed || topologyChanged;\n castersChanged = changed || castersChanged;\n }\n\n this.#selectCamera(world, cameras);\n this.#applyEnvironment(world);\n this.#applyStacks(world);\n this.#areCastersDirty = this.#areCastersDirty || castersChanged;\n // The rebuild is deferred by one frame on purpose; see `#rebuildRenderables`.\n if (this.#isRebuildDue && !topologyChanged) {\n this.#isRebuildDue = false;\n this.#rebuildRenderables();\n }\n this.#isRebuildDue = this.#isRebuildDue || topologyChanged;\n // Caster lists come **after** the renderable rebuild has settled; see `#rebuildCasters`.\n if (this.#areCastersDirty && !this.#isRebuildDue && !this.#isRebuildInFlight) {\n this.#areCastersDirty = false;\n this.#rebuildCasters(meshes, models, lights);\n }\n renderer.publishCounters(cameras.length, lights.length, meshes.length);\n }\n\n /**\n * Picks the enabled camera with the highest priority and installs it.\n *\n * @param world - The world being reconciled.\n * @param cameras - Every camera in the world, in creation order.\n */\n #selectCamera(world: World, cameras: readonly Camera[]): void {\n const renderer = this.#renderer;\n let best: Camera | 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 camera.sync(renderer);\n if (best === null || camera.priority > best.priority) {\n best = camera;\n }\n }\n world.setMainCamera(best);\n setSceneCamera(renderer.scene, best?.lite.camera ?? null);\n if (best === null) {\n this.#warnAboutMissingCamera(world);\n return;\n }\n renderer.hasLoggedNoCamera = false;\n const override = best.clearColor;\n if (override !== null) {\n renderer.applyClearColor(override);\n }\n }\n\n /**\n * Says once, at warning level, that the world renders nothing because no camera is enabled.\n *\n * @param world - The world being reconciled.\n */\n #warnAboutMissingCamera(world: World): void {\n const renderer = this.#renderer;\n if (renderer.hasLoggedNoCamera) {\n return;\n }\n renderer.hasLoggedNoCamera = true;\n world.app.log.warn(\"IGX-0706: this world has no enabled camera, so nothing is drawn.\");\n }\n\n /**\n * Applies the winning `Environment`, warning once when a world has more than one enabled.\n *\n * @param world - The world being reconciled.\n */\n #applyEnvironment(world: World): void {\n const environments = world.components(Environment);\n let winner: Environment | null = null;\n let enabledCount = 0;\n for (let index = 0; index < environments.length; index += 1) {\n const environment = environments[index];\n if (environment === undefined || !environment.isEnabledInHierarchy) {\n continue;\n }\n enabledCount += 1;\n // Later in the live component list means created later, which is what \"most recently\n // enabled wins\" resolves to for a list the store appends to.\n winner = environment;\n }\n if (enabledCount > 1 && !this.#hasLoggedMultipleEnvironments) {\n this.#hasLoggedMultipleEnvironments = true;\n world.app.log.warn(\n \"IGX-0705: {count} Environment components are enabled in this world; the most recent one wins.\",\n enabledCount,\n );\n }\n if (enabledCount <= 1) {\n this.#hasLoggedMultipleEnvironments = false;\n }\n winner?.sync(this.#renderer);\n }\n\n /**\n * Reconciles every post-process stack.\n *\n * @param world - The world being reconciled.\n */\n #applyStacks(world: World): void {\n const stacks = world.components(PostProcessStack);\n for (let index = 0; index < stacks.length; index += 1) {\n stacks[index]?.sync(this.#renderer);\n }\n }\n\n /**\n * Rebuilds the shadow caster list once and hands the same array to every casting light.\n *\n * @remarks\n * **Never in a frame that still owes a renderable rebuild.** Lite's shadow task builds a render\n * task out of the caster meshes and flushes its pending list by looking each caster material's\n * `_buildGroup` up in `scene._groups`; a group that is not there yet is `throw Error()` with no\n * message, inside the frame (`lib/frame-graph/render-task.js`). A caster added at runtime — the\n * ordinary case for a `Model`, whose component only exists once its glTF handle settled — has no\n * group until `rebuildSceneRenderables` has drained the material swap it queued. So the dirty\n * flag is held until the pending rebuild has been fired *and* resolved, which cost 3 uncaught\n * errors in 12 loads of the glTF viewer on SwiftShader before it was measured (2026-09-06).\n *\n * @param meshes - Every mesh renderer in the world.\n * @param models - Every model in the world; each contributes its whole instantiated subtree.\n * @param lights - Every light in the world.\n */\n #rebuildCasters(meshes: readonly MeshRenderer[], models: readonly Model[], lights: readonly Light[]): void {\n const casters = this.#casters;\n casters.length = 0;\n for (let index = 0; index < meshes.length; index += 1) {\n meshes[index]?.collectCasters(casters);\n }\n for (let index = 0; index < models.length; index += 1) {\n models[index]?.collectCasters(casters);\n }\n // Lite keys the list by array identity, so a fresh array is what tells it the set changed.\n const snapshot = casters.slice();\n for (let index = 0; index < lights.length; index += 1) {\n const light = lights[index];\n if (light?.isCastingShadows === true) {\n light.setShadowCasters(snapshot);\n }\n }\n }\n\n /**\n * Fires the one renderable rebuild the previous frame's topology changes earned.\n *\n * @remarks\n * **It is deliberately one frame late.** A mesh added inside the before-render callback is not in\n * a renderable group yet: `addToScene` queues a material swap that `processMaterialSwaps` drains\n * at the *start* of the next frame (`lib/scene/scene-material-swap.js`). Rebuilding in the same\n * frame therefore rebuilds the groups the mesh has not joined, the mesh joins afterwards with the\n * light list the group was built with, and nothing schedules a second rebuild — which on\n * SwiftShader leaves the scene's render pass presenting nothing at all when the warm-up probes\n * registered a group into a scene that had no lights yet (measured 2026-09-05; the same\n * combination is pinned in `test/render/warm-up.browser.test.ts`). Waiting one frame is the whole\n * fix, and it costs a frame of a stale light list on the frame a light was added.\n *\n * The counter is incremented before the headless gate: \"one rebuild however many things changed\"\n * is a property of the *coalescing*, not of the GPU, and counting it here is what lets a Node test\n * assert it without a device.\n */\n #rebuildRenderables(): void {\n const renderer = this.#renderer;\n renderer.renderableRebuilds += 1;\n // A rebuild bumps the scene's renderable version, and Lite's shadow task re-records itself\n // whenever that version moves (`lib/frame-graph/shadow-task.js`, `execute`). Recording a shadow\n // pass for a renderable whose shadow-variant pipeline has not been compiled throws inside the\n // frame — intermittently, because it depends on how far the rebuild got. Re-supplying the\n // caster list is what prevents it: `setShadowTaskCasterMeshes` parks the generator behind\n // `_preloadPending` until the pipelines for that array are built\n // (`lib/frame-graph/shadow-inputs.js`), so the task skips instead of throwing. Measured on\n // SwiftShader against the glTF viewer, 2026-09-06: 3 uncaught errors in 12 loads without this.\n renderer.needsCasterRebuild = true;\n if (renderer.isHeadless || !renderer.isSceneRegistered) {\n return;\n }\n this.#isRebuildInFlight = true;\n // Out of the frame callback as well as out of the frame: the whole ignifx frame runs inside\n // Lite's `onBeforeRender`, and rebuilding a scene's material groups from in there rebuilds them\n // against a frame that has not been recorded yet. A microtask runs once the rendered frame's\n // task has finished, which is the earliest point that is genuinely \"between frames\".\n queueMicrotask((): void => {\n void rebuildRenderables(renderer.scene)\n .catch((error: unknown): void => {\n renderer.app.onError.emit({ error, source: \"system\", phase: null, entity: null, component: null });\n })\n .finally((): void => {\n this.#isRebuildInFlight = false;\n });\n });\n }\n}\n","import type { JsonArray, JsonObject, JsonValue } from \"../schema/json.js\";\n\n/**\n * Narrows a JSON value to an object. `Array.isArray` alone does not remove `JsonArray` from the\n * `JsonValue` union in a way that lets the object half be indexed by an arbitrary string, so the\n * whole discrimination lives here rather than being repeated with an assertion at every call site.\n *\n * @param value - The JSON to narrow.\n * @returns The object, or `null` when the value is an array, `null`, or a primitive.\n *\n * @internal\n */\nexport function asJsonObject(value: JsonValue | undefined): JsonObject | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // Boundary assertion (coding standards §5.2): the guard above is exactly `JsonObject` — an\n // object that is neither `null` nor an array — which is what `JsonValue` leaves in the union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as JsonObject;\n}\n\n/**\n * Narrows a JSON value to an array.\n *\n * @param value - The JSON to narrow.\n * @returns The array, or `null` when the value is not one.\n *\n * @internal\n */\nexport function asJsonArray(value: JsonValue | undefined): JsonArray | null {\n return Array.isArray(value) ? value : null;\n}\n","/**\n * Guards and path helpers shared by validation, encoding, and decoding. Nothing here is exported\n * from the package barrel.\n */\n\n/**\n * The component names of a vector value, in encoded order.\n *\n * @internal\n */\nexport const VECTOR_COMPONENTS = [\"x\", \"y\", \"z\", \"w\"] as const;\n\n/**\n * The channel names of a color value, in encoded order.\n *\n * @internal\n */\nexport const COLOR_CHANNELS = [\"r\", \"g\", \"b\", \"a\"] as const;\n\n/**\n * Extends a property path with a named child.\n *\n * @param path - The parent path, possibly empty.\n * @param name - The child property name.\n * @returns The child path.\n *\n * @internal\n */\nexport function childPath(path: string, name: string): string {\n return path === \"\" ? name : `${path}.${name}`;\n}\n\n/**\n * Extends a property path with an array index or map key.\n *\n * @param path - The parent path.\n * @param key - The index or key.\n * @returns The child path.\n *\n * @internal\n */\nexport function indexPath(path: string, key: number | string): string {\n return typeof key === \"number\" ? `${path}[${key}]` : `${path}[${JSON.stringify(key)}]`;\n}\n\n/**\n * Narrows a value to a read-only array without widening its elements to `any`, which is what the\n * built-in `Array.isArray` predicate does for an `unknown` input.\n *\n * @param value - The value to test.\n * @returns Whether the value is an array.\n *\n * @internal\n */\nexport function isArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Narrows a value to a plain object, excluding arrays and `null`.\n *\n * @param value - The value to test.\n * @returns Whether the value is a plain object.\n *\n * @internal\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !isArray(value);\n}\n\n/**\n * Reinterprets a decoded JavaScript value as the field's declared type. Decoders are the JSON\n * boundary coding standards §5.2 allows assertions at: the value was just built from the field's\n * own definition, so it matches by construction, but that fact is not expressible in the type\n * system without threading the value type through every recursive step.\n *\n * @param value - The decoded value.\n * @returns The same value, typed as the field's value type.\n *\n * @internal\n */\n// The type parameter exists so that the caller names the target type; there is no argument to infer\n// it from, which is exactly what makes this an assertion helper rather than a conversion.\n// oxlint-disable-next-line typescript/no-unnecessary-type-parameters\nexport function asFieldValue<T>(value: unknown): T {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- invariant stated above.\n return value as T;\n}\n","import { isMemoryAddress } from \"../assets/address.js\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport {\n COLOR_CHANNELS,\n VECTOR_COMPONENTS,\n asFieldValue,\n childPath,\n indexPath,\n isArray,\n isPlainObject,\n} from \"./internal.js\";\nimport { SchemaIssueCode, issue } from \"./issues.js\";\nimport type { SchemaIssue } from \"./issues.js\";\nimport type { JsonObject, JsonValue } from \"./json.js\";\nimport type { FieldDefinition, FieldsOf, PartialFieldsOf, Schema } from \"./types.js\";\n\n/**\n * How the serializer turns a live entity or component reference into the uid written to a file.\n * Reference kinds cannot be encoded without a world, so the kernel implements this and tests pass\n * a fake.\n *\n * @public\n */\nexport interface ReferenceEncoder {\n /**\n * Resolves an entity reference to its file-local uid.\n *\n * @param value - The entity the field points at.\n * @returns The uid, or `null` when the target is not part of the file being written.\n */\n entityUid(value: unknown): string | null;\n /**\n * Resolves a component reference to its file-local uid.\n *\n * @param value - The component the field points at.\n * @returns The uid, or `null` when the target is not part of the file being written.\n */\n componentUid(value: unknown): string | null;\n}\n\n/**\n * How the loader turns a uid read from a file back into a live entity or component.\n *\n * @public\n */\nexport interface ReferenceDecoder {\n /**\n * Looks up an entity by its file-local uid.\n *\n * @param uid - The uid read from the file.\n * @returns The entity, or `null` when the uid is unknown.\n */\n entity(uid: string): unknown;\n /**\n * Looks up a component by its file-local uid.\n *\n * @param uid - The uid read from the file.\n * @returns The component, or `null` when the uid is unknown.\n */\n component(uid: string): unknown;\n /**\n * Resolves an asset address to the loaded handle an `asset()` field should hold\n * (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * @remarks\n * The scene loader answers from the dependency handles the `SceneAsset` already retains, so the\n * field never starts a load of its own and never owns a reference count. A resolver that returns\n * `null` — an address nothing loaded — makes the field `null` and adds an `IGX-0602` issue.\n *\n * @param address - The address the file carries, fragment included.\n * @param type - The asset type the field or the file declared, or `null` when the address's\n * extension identifies it on its own.\n * @returns The handle, or `null` when nothing loaded stands at that address.\n */\n asset(address: string, type: string | null): unknown;\n}\n\n/**\n * What decoding produced: a value that is always usable — the field's default when the JSON could\n * not be read — plus every problem found on the way.\n *\n * @typeParam T - The decoded value type.\n *\n * @public\n */\nexport interface DecodeResult<T> {\n /** The decoded value, or the field's freshly built default when decoding failed. */\n readonly value: T;\n /** Every problem found, in discovery order; empty on a clean decode. */\n readonly issues: readonly SchemaIssue[];\n}\n\n/**\n * Rounds a number to the file format's precision: six decimal places, with `-0` normalized to `0`\n * (`docs/architecture/06-serialization-and-scene-format.md` §3). The rule is idempotent, so\n * save → load → save is byte-identical.\n *\n * @param value - The number to canonicalize.\n * @returns The canonical form of the number.\n *\n * @example\n * ```ts\n * canonicalizeNumber(0.1 + 0.2); // 0.3\n * canonicalizeNumber(-0); // 0\n * ```\n *\n * @public\n */\nexport function canonicalizeNumber(value: number): number {\n const rounded = Math.round(value * 1e6) / 1e6;\n return rounded === 0 ? 0 : rounded;\n}\n\n/**\n * Reports a value that does not match its field and yields the JSON stand-in for it.\n *\n * @param issues - The collector to append to.\n * @param path - The property path the problem was found at.\n * @param message - An actionable description.\n * @returns `null`, the placeholder written for an unrepresentable value.\n *\n * @internal\n */\nfunction unrepresentable(issues: SchemaIssue[], path: string, message: string): null {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, message));\n return null;\n}\n\n/**\n * Encodes one number, reporting `NaN` and the infinities.\n *\n * @param value - The candidate number.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n * @returns The canonical number, or `null` when it cannot be written.\n *\n * @internal\n */\nfunction encodeNumber(value: unknown, path: string, issues: SchemaIssue[]): JsonValue {\n if (typeof value !== \"number\") {\n return unrepresentable(issues, path, `expected a number, received ${typeof value}.`);\n }\n if (!Number.isFinite(value)) {\n issues.push(issue(SchemaIssueCode.nonFiniteNumber, path, `${String(value)} cannot be written to JSON.`));\n return null;\n }\n return canonicalizeNumber(value);\n}\n\n/**\n * Encodes the named channels of an object value as a JSON number array.\n *\n * @param names - The channel names to read, in encoded order.\n * @param label - How the value is named in messages.\n * @param value - The candidate value.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n * @returns The number array, or `null` when a channel is missing or unrepresentable.\n *\n * @internal\n */\nfunction encodeChannels(\n names: readonly string[],\n label: string,\n value: unknown,\n path: string,\n issues: SchemaIssue[],\n): JsonValue {\n if (!isPlainObject(value)) {\n return unrepresentable(issues, path, `expected a ${label} object, received ${typeof value}.`);\n }\n const encoded: JsonValue[] = [];\n for (const name of names) {\n const channel = encodeNumber(value[name], childPath(path, name), issues);\n if (channel === null) {\n return null;\n }\n encoded.push(channel);\n }\n return encoded;\n}\n\n/**\n * Encodes one value against one field definition.\n *\n * @param field - The field to encode against.\n * @param value - The value to encode.\n * @param references - How to resolve entity and component references to uids.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n * @returns The JSON representation.\n *\n * @internal\n */\nfunction encodeInto(\n field: FieldDefinition<unknown>,\n value: unknown,\n references: ReferenceEncoder,\n path: string,\n issues: SchemaIssue[],\n): JsonValue {\n const { spec } = field;\n switch (spec.kind) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\": {\n return encodeNumber(value, path, issues);\n }\n case \"bool\": {\n return typeof value === \"boolean\"\n ? value\n : unrepresentable(issues, path, `expected a boolean, received ${typeof value}.`);\n }\n case \"str\": {\n return typeof value === \"string\"\n ? value\n : unrepresentable(issues, path, `expected a string, received ${typeof value}.`);\n }\n case \"vec2\":\n case \"vec3\":\n case \"vec4\":\n case \"quat\": {\n return encodeChannels(VECTOR_COMPONENTS.slice(0, spec.components), spec.kind, value, path, issues);\n }\n case \"color\": {\n return encodeChannels(COLOR_CHANNELS, \"color\", value, path, issues);\n }\n case \"enum\": {\n return typeof value === \"string\"\n ? value\n : unrepresentable(issues, path, `expected a string, received ${typeof value}.`);\n }\n case \"entityRef\": {\n if (value === null) {\n return null;\n }\n const uid = references.entityUid(value);\n if (uid === null) {\n issues.push(issue(SchemaIssueCode.unresolvedReference, path, `the referenced entity is not in this file.`));\n return null;\n }\n return { $entity: uid };\n }\n case \"componentRef\": {\n if (value === null) {\n return null;\n }\n const uid = references.componentUid(value);\n if (uid === null) {\n issues.push(issue(SchemaIssueCode.unresolvedReference, path, `the referenced component is not in this file.`));\n return null;\n }\n return { $component: uid };\n }\n case \"asset\": {\n if (value === null) {\n return null;\n }\n if (!isPlainObject(value) || typeof value[\"address\"] !== \"string\") {\n return unrepresentable(issues, path, `expected a loaded asset handle, or null.`);\n }\n const address = value[\"address\"];\n if (isMemoryAddress(address)) {\n // An in-code asset (`Assets.register`, `MeshAsset.box`, `MaterialAsset.pbr`) names no file,\n // so there is nothing a reader could resolve the address against. Writing it would produce\n // a file that loads with a dangling reference; writing `null` and saying so does not.\n issues.push(\n issue(\n SchemaIssueCode.unresolvedReference,\n path,\n `the asset was created in code (${address}) and has no file to reference.`,\n ),\n );\n return null;\n }\n const declared = value[\"type\"];\n const typeName = typeof declared === \"string\" ? declared : spec.typeName;\n return typeName === null ? { $asset: address } : { $asset: address, type: typeName };\n }\n case \"array\": {\n if (!isArray(value)) {\n return unrepresentable(issues, path, `expected an array, received ${typeof value}.`);\n }\n const encoded: JsonValue[] = [];\n for (let index = 0; index < value.length; index += 1) {\n encoded.push(encodeInto(spec.item, value[index], references, indexPath(path, index), issues));\n }\n return encoded;\n }\n case \"record\": {\n if (!isPlainObject(value)) {\n return unrepresentable(issues, path, `expected an object, received ${typeof value}.`);\n }\n return encodeFields(spec.fields, value, references, path, issues);\n }\n case \"map\": {\n if (!isPlainObject(value)) {\n return unrepresentable(issues, path, `expected an object, received ${typeof value}.`);\n }\n const encoded: Record<string, JsonValue> = {};\n for (const key of Object.keys(value).toSorted()) {\n encoded[key] = encodeInto(spec.value, value[key], references, indexPath(path, key), issues);\n }\n return encoded;\n }\n case \"optional\": {\n return value === null ? null : encodeInto(spec.inner, value, references, path, issues);\n }\n case \"layerMask\": {\n if (!isArray(value)) {\n return unrepresentable(issues, path, `expected an array of layer names.`);\n }\n const encoded: JsonValue[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const name = value[index];\n if (typeof name !== \"string\") {\n return unrepresentable(issues, indexPath(path, index), `expected a layer name string.`);\n }\n encoded.push(name);\n }\n return encoded;\n }\n case \"curve\": {\n if (!isPlainObject(value)) {\n return unrepresentable(issues, path, `expected a curve object.`);\n }\n const keys = value[\"keys\"];\n const keysAt = childPath(path, \"keys\");\n if (!isArray(keys)) {\n return unrepresentable(issues, keysAt, `expected an array of curve keys.`);\n }\n const encoded: JsonValue[] = [];\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n const keyAt = indexPath(keysAt, index);\n if (!isArray(key) || key.length !== 4) {\n return unrepresentable(issues, keyAt, `expected [time, value, inTangent, outTangent].`);\n }\n encoded.push([\n encodeNumber(key[0], indexPath(keyAt, 0), issues),\n encodeNumber(key[1], indexPath(keyAt, 1), issues),\n encodeNumber(key[2], indexPath(keyAt, 2), issues),\n encodeNumber(key[3], indexPath(keyAt, 3), issues),\n ]);\n }\n return { keys: encoded };\n }\n case \"custom\": {\n return spec.codec.serialize(value);\n }\n default: {\n return assertNever(spec, \"schema field kind\");\n }\n }\n}\n\n/**\n * Encodes a bag of values against a schema in canonical (declaration) key order, skipping fields\n * marked `transient` (`docs/architecture/06-serialization-and-scene-format.md` §5).\n *\n * @param schema - The schema that fixes the key order.\n * @param values - The values to encode, keyed by field name; missing names take the field default.\n * @param references - How to resolve entity and component references to uids.\n * @param path - The property path prefix for reported issues.\n * @param issues - The collector to append to.\n * @returns The JSON object.\n *\n * @internal\n */\nfunction encodeFields(\n schema: Schema,\n values: Readonly<Record<string, unknown>>,\n references: ReferenceEncoder,\n path: string,\n issues: SchemaIssue[],\n): JsonObject {\n const encoded: Record<string, JsonValue> = {};\n for (const [name, field] of Object.entries(schema)) {\n if (field.options.transient === true) {\n continue;\n }\n const supplied = values[name];\n const value = supplied === undefined ? field.createDefault() : supplied;\n encoded[name] = encodeInto(field, value, references, childPath(path, name), issues);\n }\n return encoded;\n}\n\n/**\n * Encodes one value into the JSON form the scene format defines\n * (`docs/architecture/06-serialization-and-scene-format.md` §3). Numbers are canonicalized,\n * vectors and colors become arrays, and references become tagged objects.\n *\n * Encoding is total: it always returns valid JSON. A value that cannot be represented — a `NaN`, a\n * reference to something outside the file, a value of the wrong type — is written as `null` and\n * reported through `issues`. Call {@link validateValue} when you want the check without the output.\n *\n * @typeParam T - The field's value type.\n * @param field - The field to encode against.\n * @param value - The value to encode.\n * @param references - How to resolve entity and component references to uids.\n * @param issues - An optional collector; problems are appended to it in discovery order.\n * @returns The JSON representation.\n *\n * @example\n * ```ts\n * encodeValue(vec3(), { x: 1, y: 2.0000004, z: -0 }, references); // [1, 2, 0]\n * ```\n *\n * @public\n */\nexport function encodeValue<T>(\n field: FieldDefinition<T>,\n value: T,\n references: ReferenceEncoder,\n issues: SchemaIssue[] = [],\n): JsonValue {\n return encodeInto(field, value, references, \"\", issues);\n}\n\n/**\n * Encodes a component's props in canonical key order. Fields the schema declares but `props` omits\n * take their default; fields marked `transient` are skipped.\n *\n * @typeParam S - The schema being encoded.\n * @param schema - The schema that fixes the key order.\n * @param props - The values to encode, keyed by field name.\n * @param references - How to resolve entity and component references to uids.\n * @param issues - An optional collector; problems are appended to it in discovery order.\n * @returns The JSON object written under `props` in a scene file.\n *\n * @public\n */\nexport function encodeProps<S extends Schema>(\n schema: S,\n props: PartialFieldsOf<S>,\n references: ReferenceEncoder,\n issues: SchemaIssue[] = [],\n): JsonObject {\n return encodeFields(schema, asFieldValue<Record<string, unknown>>(props), references, \"\", issues);\n}\n\n/**\n * Decodes one JSON value against one field definition.\n *\n * @param field - The field to decode against.\n * @param json - The JSON to read.\n * @param references - How to resolve uids back to entities and components.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n * @returns The decoded value, or the field's fresh default when the JSON could not be read.\n *\n * @internal\n */\nfunction decodeInto(\n field: FieldDefinition<unknown>,\n json: JsonValue,\n references: ReferenceDecoder,\n path: string,\n issues: SchemaIssue[],\n): unknown {\n const { spec } = field;\n switch (spec.kind) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\": {\n if (typeof json !== \"number\" || !Number.isFinite(json)) {\n return rejected(field, issues, path, `expected a finite number.`);\n }\n return canonicalizeNumber(json);\n }\n case \"bool\": {\n return typeof json === \"boolean\" ? json : rejected(field, issues, path, `expected a boolean.`);\n }\n case \"str\": {\n return typeof json === \"string\" ? json : rejected(field, issues, path, `expected a string.`);\n }\n case \"vec2\":\n case \"vec3\":\n case \"vec4\":\n case \"quat\": {\n return decodeChannels(VECTOR_COMPONENTS.slice(0, spec.components), field, json, path, issues);\n }\n case \"color\": {\n return decodeChannels(COLOR_CHANNELS, field, json, path, issues);\n }\n case \"enum\": {\n if (typeof json !== \"string\" || !spec.values.includes(json)) {\n return rejected(field, issues, path, `expected one of [${spec.values.join(\", \")}].`);\n }\n return json;\n }\n case \"entityRef\": {\n return decodeReference(field, json, \"$entity\", (uid) => references.entity(uid), path, issues);\n }\n case \"componentRef\": {\n return decodeReference(field, json, \"$component\", (uid) => references.component(uid), path, issues);\n }\n case \"asset\": {\n if (json === null) {\n return null;\n }\n if (!isPlainObject(json) || typeof json[\"$asset\"] !== \"string\") {\n return rejected(field, issues, path, `expected { \"$asset\": \"<address>\" } or null.`);\n }\n const address = json[\"$asset\"];\n const declared = json[\"type\"];\n const typeName = typeof declared === \"string\" ? declared : spec.typeName;\n const handle = references.asset(address, typeName);\n if (handle === null || handle === undefined) {\n issues.push(\n issue(SchemaIssueCode.unresolvedReference, path, `no loaded asset stands at the address \"${address}\".`),\n );\n return null;\n }\n return handle;\n }\n case \"array\": {\n if (!isArray(json)) {\n return rejected(field, issues, path, `expected an array.`);\n }\n const decoded: unknown[] = [];\n for (let index = 0; index < json.length; index += 1) {\n decoded.push(decodeInto(spec.item, json[index] ?? null, references, indexPath(path, index), issues));\n }\n return decoded;\n }\n case \"record\": {\n if (!isPlainObject(json)) {\n return rejected(field, issues, path, `expected an object.`);\n }\n return decodeFields(spec.fields, json, references, path, issues);\n }\n case \"map\": {\n if (!isPlainObject(json)) {\n return rejected(field, issues, path, `expected an object.`);\n }\n const decoded: Record<string, unknown> = {};\n for (const key of Object.keys(json).toSorted()) {\n decoded[key] = decodeInto(spec.value, json[key] ?? null, references, indexPath(path, key), issues);\n }\n return decoded;\n }\n case \"optional\": {\n return json === null ? null : decodeInto(spec.inner, json, references, path, issues);\n }\n case \"layerMask\": {\n if (!isArray(json)) {\n return rejected(field, issues, path, `expected an array of layer names.`);\n }\n const names: string[] = [];\n for (let index = 0; index < json.length; index += 1) {\n const name = json[index];\n if (typeof name !== \"string\") {\n return rejected(field, issues, indexPath(path, index), `expected a layer name string.`);\n }\n names.push(name);\n }\n return names;\n }\n case \"curve\": {\n if (!isPlainObject(json)) {\n return rejected(field, issues, path, `expected a curve object.`);\n }\n const keysAt = childPath(path, \"keys\");\n const rawKeys = json[\"keys\"];\n if (!isArray(rawKeys)) {\n return rejected(field, issues, keysAt, `expected an array of curve keys.`);\n }\n const keys: (readonly [number, number, number, number])[] = [];\n for (let index = 0; index < rawKeys.length; index += 1) {\n const key = rawKeys[index];\n if (!isArray(key) || key.length !== 4) {\n return rejected(field, issues, indexPath(keysAt, index), `expected [time, value, inTangent, outTangent].`);\n }\n const at = (slot: number): number => {\n const component = key[slot];\n return typeof component === \"number\" && Number.isFinite(component) ? canonicalizeNumber(component) : 0;\n };\n keys.push([at(0), at(1), at(2), at(3)]);\n }\n return { keys };\n }\n case \"custom\": {\n return spec.codec.deserialize(json);\n }\n default: {\n return assertNever(spec, \"schema field kind\");\n }\n }\n}\n\n/**\n * Reports unreadable JSON and yields the field's fresh default in its place.\n *\n * @param field - The field being decoded.\n * @param issues - The collector to append to.\n * @param path - The property path the problem was found at.\n * @param message - An actionable description.\n * @returns A newly built default value.\n *\n * @internal\n */\nfunction rejected(field: FieldDefinition<unknown>, issues: SchemaIssue[], path: string, message: string): unknown {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, message));\n return field.createDefault();\n}\n\n/**\n * Decodes a JSON number array back into a channel object.\n *\n * @param names - The channel names to write, in encoded order.\n * @param field - The field being decoded, used for its default on failure.\n * @param json - The JSON to read.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n * @returns The channel object, or the field's default.\n *\n * @internal\n */\nfunction decodeChannels(\n names: readonly string[],\n field: FieldDefinition<unknown>,\n json: JsonValue,\n path: string,\n issues: SchemaIssue[],\n): unknown {\n if (!isArray(json) || json.length !== names.length) {\n return rejected(field, issues, path, `expected an array of ${names.length} numbers.`);\n }\n const decoded: Record<string, number> = {};\n for (let index = 0; index < names.length; index += 1) {\n const component = json[index];\n const name = names[index];\n if (typeof component !== \"number\" || !Number.isFinite(component) || name === undefined) {\n return rejected(field, issues, indexPath(path, index), `expected a finite number.`);\n }\n decoded[name] = canonicalizeNumber(component);\n }\n return decoded;\n}\n\n/**\n * Decodes a tagged reference object back into a live target.\n *\n * @param field - The field being decoded, used for its default on failure.\n * @param json - The JSON to read.\n * @param tag - The tag property, `$entity` or `$component`.\n * @param resolve - How to turn a uid into a target.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n * @returns The resolved target, or `null`.\n *\n * @internal\n */\nfunction decodeReference(\n field: FieldDefinition<unknown>,\n json: JsonValue,\n tag: \"$entity\" | \"$component\",\n resolve: (uid: string) => unknown,\n path: string,\n issues: SchemaIssue[],\n): unknown {\n if (json === null) {\n return null;\n }\n if (!isPlainObject(json) || typeof json[tag] !== \"string\") {\n return rejected(field, issues, path, `expected { \"${tag}\": \"<uid>\" } or null.`);\n }\n const uid = json[tag];\n const target = resolve(uid);\n if (target === null || target === undefined) {\n issues.push(issue(SchemaIssueCode.unresolvedReference, path, `no target in this file has uid \"${uid}\".`));\n return null;\n }\n return target;\n}\n\n/**\n * Decodes a JSON object against a schema, filling omitted fields with their defaults.\n *\n * @param schema - The schema to decode against.\n * @param json - The JSON object to read.\n * @param references - How to resolve uids back to entities and components.\n * @param path - The property path prefix for reported issues.\n * @param issues - The collector to append to.\n * @returns A record holding one value per declared field.\n *\n * @internal\n */\nfunction decodeFields(\n schema: Schema,\n json: JsonObject,\n references: ReferenceDecoder,\n path: string,\n issues: SchemaIssue[],\n): Record<string, unknown> {\n for (const name of Object.keys(json)) {\n if (!Object.hasOwn(schema, name)) {\n issues.push(\n issue(SchemaIssueCode.unknownField, childPath(path, name), `the schema declares no field \"${name}\".`),\n );\n }\n }\n const decoded: Record<string, unknown> = {};\n for (const [name, field] of Object.entries(schema)) {\n const raw = json[name];\n decoded[name] =\n raw === undefined ? field.createDefault() : decodeInto(field, raw, references, childPath(path, name), issues);\n }\n return decoded;\n}\n\n/**\n * Decodes one JSON value back into a field value. Decoding never throws and never returns a broken\n * value: unreadable JSON yields the field's freshly built default plus an issue, so a corrupt file\n * degrades one field rather than failing a whole scene\n * (`docs/architecture/06-serialization-and-scene-format.md` §4).\n *\n * @typeParam T - The field's value type.\n * @param field - The field to decode against.\n * @param json - The JSON to read.\n * @param references - How to resolve uids back to entities and components.\n * @returns The decoded value and every problem found.\n *\n * @example\n * ```ts\n * decodeValue(vec3(), [1, 2, 3], references); // { value: { x: 1, y: 2, z: 3 }, issues: [] }\n * ```\n *\n * @public\n */\nexport function decodeValue<T>(\n field: FieldDefinition<T>,\n json: JsonValue,\n references: ReferenceDecoder,\n): DecodeResult<T> {\n const issues: SchemaIssue[] = [];\n const value = decodeInto(field, json, references, \"\", issues);\n return { value: asFieldValue<T>(value), issues };\n}\n\n/**\n * Decodes a component's `props` object. Fields the file omits take their schema default; names the\n * schema does not declare are reported as `IGX-0607` and ignored.\n *\n * @typeParam S - The schema being decoded.\n * @param schema - The schema to decode against.\n * @param json - The `props` object read from the file.\n * @param references - How to resolve uids back to entities and components.\n * @returns The decoded field object and every problem found.\n *\n * @public\n */\nexport function decodeProps<S extends Schema>(\n schema: S,\n json: JsonObject,\n references: ReferenceDecoder,\n): DecodeResult<FieldsOf<S>> {\n const issues: SchemaIssue[] = [];\n const decoded = decodeFields(schema, json, references, \"\", issues);\n return { value: asFieldValue<FieldsOf<S>>(decoded), issues };\n}\n","import { assertNever } from \"../errors/ignifx-error.js\";\nimport { encodeValue } from \"./encode.js\";\nimport type { ReferenceEncoder } from \"./encode.js\";\nimport type { JsonObject, JsonValue } from \"./json.js\";\nimport type { FieldDefinition, FieldKind, Schema } from \"./types.js\";\n\n/**\n * One field as the documentation harness sees it (`scripts/README.md`, \"Schema discovery\n * convention\").\n *\n * @public\n */\nexport interface SchemaFieldDescription {\n /** The field kind, for example `f32` or `asset`. */\n readonly kind: FieldKind;\n /** The field's default value, already encoded as JSON. */\n readonly default?: JsonValue;\n /** The field's tooltip, when it declares one. */\n readonly description?: string;\n}\n\n/**\n * One component schema as the documentation harness sees it. `pnpm docs:schemas` reads a record of\n * these, keyed by component `typeId`, from each built package's `schemas` export and turns it into\n * `references/formats/<format>.md` and `ignifx.schemas.json`.\n *\n * @public\n */\nexport interface SchemaDescription {\n /** The human-readable name, by default the last segment of the type id. */\n readonly title: string;\n /** The format page the entry is grouped onto; `components` unless overridden. */\n readonly format: string;\n /** A one-line summary of what the component does. */\n readonly description?: string;\n /** Every declared field, in declaration order. */\n readonly fields: Readonly<Record<string, SchemaFieldDescription>>;\n}\n\n/**\n * Optional overrides for {@link describeSchema}.\n *\n * @public\n */\nexport interface SchemaDescriptionMeta {\n /** Overrides the title derived from the type id. */\n readonly title?: string;\n /** Overrides the default `components` grouping. */\n readonly format?: string;\n /** A one-line summary of what the component does. */\n readonly description?: string;\n}\n\n/**\n * A JSON Schema fragment. Kept as a plain JSON object because the generated document is assembled\n * — and validated — by the documentation harness, not by this module\n * (`docs/architecture/06-serialization-and-scene-format.md` §8).\n *\n * @public\n */\nexport type JsonSchemaObject = JsonObject;\n\n/**\n * Resolves references to nothing. Describing a schema means describing its *defaults*, and a\n * reference field's default is always `null`, so no world is needed.\n *\n * @returns An encoder that resolves every reference to `null`.\n *\n * @internal\n */\nfunction noReferences(): ReferenceEncoder {\n return { entityUid: () => null, componentUid: () => null };\n}\n\n/**\n * Builds the JSON Schema fragment for one field.\n *\n * @param field - The field to describe.\n * @returns The fragment describing the field's encoded form.\n *\n * @internal\n */\nfunction fieldJsonSchema(field: FieldDefinition<unknown>): JsonSchemaObject {\n const { spec } = field;\n switch (spec.kind) {\n case \"f32\":\n case \"f64\": {\n return { type: \"number\" };\n }\n case \"i32\": {\n return { type: \"integer\", minimum: -2147483648, maximum: 2147483647 };\n }\n case \"u32\": {\n return { type: \"integer\", minimum: 0, maximum: 4294967295 };\n }\n case \"bool\": {\n return { type: \"boolean\" };\n }\n case \"str\": {\n return { type: \"string\" };\n }\n case \"vec2\":\n case \"vec3\":\n case \"vec4\":\n case \"quat\": {\n return { type: \"array\", items: { type: \"number\" }, minItems: spec.components, maxItems: spec.components };\n }\n case \"color\": {\n return {\n type: \"array\",\n items: { type: \"number\", minimum: 0, maximum: 1 },\n minItems: 4,\n maxItems: 4,\n };\n }\n case \"enum\": {\n return { type: \"string\", enum: [...spec.values] };\n }\n case \"entityRef\": {\n return taggedReferenceSchema(\"$entity\");\n }\n case \"componentRef\": {\n return taggedReferenceSchema(\"$component\");\n }\n case \"asset\": {\n return {\n oneOf: [\n {\n type: \"object\",\n properties: { $asset: { type: \"string\" }, type: { type: \"string\" } },\n required: [\"$asset\"],\n additionalProperties: false,\n },\n { type: \"null\" },\n ],\n };\n }\n case \"array\": {\n return { type: \"array\", items: fieldJsonSchema(spec.item) };\n }\n case \"record\": {\n return schemaJsonSchema(spec.fields);\n }\n case \"map\": {\n return { type: \"object\", additionalProperties: fieldJsonSchema(spec.value) };\n }\n case \"optional\": {\n return { oneOf: [fieldJsonSchema(spec.inner), { type: \"null\" }] };\n }\n case \"layerMask\": {\n return { type: \"array\", items: { type: \"string\" } };\n }\n case \"curve\": {\n return {\n type: \"object\",\n properties: {\n keys: {\n type: \"array\",\n items: { type: \"array\", items: { type: \"number\" }, minItems: 4, maxItems: 4 },\n },\n },\n required: [\"keys\"],\n additionalProperties: false,\n };\n }\n case \"custom\": {\n return spec.codec.jsonSchema ?? {};\n }\n default: {\n return assertNever(spec, \"schema field kind\");\n }\n }\n}\n\n/**\n * Builds the fragment for a tagged reference: an object carrying one uid property, or `null`.\n *\n * @param tag - The tag property, `$entity` or `$component`.\n * @returns The fragment.\n *\n * @internal\n */\nfunction taggedReferenceSchema(tag: \"$entity\" | \"$component\"): JsonSchemaObject {\n return {\n oneOf: [\n {\n type: \"object\",\n properties: { [tag]: { type: \"string\" } },\n required: [tag],\n additionalProperties: false,\n },\n { type: \"null\" },\n ],\n };\n}\n\n/**\n * Decorates a field's fragment with the metadata the inspector and the docs already carry.\n *\n * @param field - The field to describe.\n * @returns The fragment plus `default`, `description`, and numeric bounds where they apply.\n *\n * @internal\n */\nfunction annotatedFieldJsonSchema(field: FieldDefinition<unknown>): JsonSchemaObject {\n const base: Record<string, JsonValue> = { ...fieldJsonSchema(field) };\n const { tooltip, min, max } = field.options;\n if (tooltip !== undefined) {\n base[\"description\"] = tooltip;\n }\n if (min !== undefined) {\n base[\"minimum\"] = min;\n }\n if (max !== undefined) {\n base[\"maximum\"] = max;\n }\n base[\"default\"] = encodeValue(field, field.createDefault(), noReferences());\n return base;\n}\n\n/**\n * Builds the object fragment for a whole schema.\n *\n * @param schema - The schema to describe.\n * @returns The fragment.\n *\n * @internal\n */\nfunction schemaJsonSchema(schema: Schema): JsonSchemaObject {\n const properties: Record<string, JsonValue> = {};\n for (const [name, field] of Object.entries(schema)) {\n properties[name] = annotatedFieldJsonSchema(field);\n }\n // Every prop is optional: a file omits a prop that equals its default\n // (docs/architecture/06-serialization-and-scene-format.md §2), so there is no `required` list.\n return { type: \"object\", properties, additionalProperties: false };\n}\n\n/**\n * Describes a component schema in the shape the documentation harness consumes. A package exports\n * a record of these keyed by `typeId`; `pnpm docs:schemas` reads it from the built entry point and\n * regenerates the format pages and `ignifx.schemas.json` from it\n * (`scripts/README.md`, `docs/architecture/16-docs-harness-and-skill.md` §3).\n *\n * @param typeId - The component's namespaced registration id, for example `mygame/Mover`.\n * @param schema - The component's declared fields.\n * @param meta - Overrides for the title, format grouping, and summary.\n * @returns The description entry.\n *\n * @example\n * ```ts\n * export const schemas = {\n * \"mygame/Mover\": describeSchema(\"mygame/Mover\", moverSchema, { description: \"Moves an entity.\" }),\n * };\n * ```\n *\n * @public\n */\nexport function describeSchema(typeId: string, schema: Schema, meta?: SchemaDescriptionMeta): SchemaDescription {\n const references = noReferences();\n const fields: Record<string, SchemaFieldDescription> = {};\n for (const [name, field] of Object.entries(schema)) {\n const { tooltip } = field.options;\n fields[name] = {\n kind: field.kind,\n default: encodeValue(field, field.createDefault(), references),\n ...(tooltip === undefined ? {} : { description: tooltip }),\n };\n }\n const derivedTitle = typeId.slice(typeId.lastIndexOf(\"/\") + 1);\n return {\n title: meta?.title ?? derivedTitle,\n format: meta?.format ?? \"components\",\n ...(meta?.description === undefined ? {} : { description: meta.description }),\n fields,\n };\n}\n\n/**\n * Generates the JSON Schema (draft 2020-12) for a component's `props` object. The harness and the\n * Vite plugin assemble these into `ignifx.schemas.json`, which drives build-time validation and\n * editor autocompletion (`docs/architecture/06-serialization-and-scene-format.md` §8).\n *\n * @param schema - The schema to convert.\n * @returns The object fragment describing every declared prop.\n *\n * @public\n */\nexport function toJsonSchema(schema: Schema): JsonSchemaObject {\n return schemaJsonSchema(schema);\n}\n","import { toJsonSchema } from \"../schema/describe.js\";\nimport type { ComponentRegistry } from \"../component/component-registry.js\";\nimport type { SchemaDescription } from \"../schema/describe.js\";\nimport type { JsonObject, JsonValue } from \"../schema/json.js\";\n\n/**\n * The `format` discriminator every scene and prefab file carries\n * (`docs/architecture/06-serialization-and-scene-format.md` §2). Levels (`*.scene.json`) and\n * prefabs (`*.prefab.json`) share it: a prefab is a scene instanced inside another scene\n * (ADR-0005), not a second file type.\n *\n * @public\n */\nexport const SCENE_FILE_FORMAT = \"ignifx.scene\";\n\n/**\n * The `formatVersion` this build writes and is the only one it can read. Before 1.0 the number\n * stays `1` and an incompatible change invalidates files rather than migrating them\n * (`CONSTITUTION.md` §4.2); a file declaring anything else is rejected with `IGX-0603`.\n *\n * @public\n */\nexport const SCENE_FORMAT_VERSION = 1;\n\n/**\n * The file extensions the scene loader claims.\n *\n * @public\n */\nexport const SCENE_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".scene.json\", \".prefab.json\"]);\n\n/**\n * The asset type name the scene loader registers under.\n *\n * @public\n */\nexport const SCENE_ASSET_TYPE = \"scene\";\n\n/**\n * A serialized asset reference: `{ \"$asset\": \"<address>\", \"type\"?: \"<type>\" }`\n * (`docs/architecture/06-serialization-and-scene-format.md` §3).\n *\n * @public\n */\nexport interface SceneFileAssetRef {\n /** The address the asset is registered under. */\n readonly $asset: string;\n /** The asset type name, written only when the address extension does not identify it. */\n readonly type?: string;\n}\n\n/**\n * An entity's local transform, always present in the file and always three plain number arrays\n * (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @remarks\n * The values are **local** — relative to `parent` — because the file already stores the tree and\n * local values are the ones that survive a parent being moved. The document says only \"arrays\n * `[x, y, z]`, `[x, y, z, w]`, `[x, y, z]`\"; this is the reading that round trips.\n *\n * @public\n */\nexport interface SceneFileTransform {\n /** Local position, `[x, y, z]`, in metres. */\n readonly position: readonly [number, number, number];\n /** Local rotation quaternion, `[x, y, z, w]`. */\n readonly rotation: readonly [number, number, number, number];\n /** Local scale, `[x, y, z]`. */\n readonly scale: readonly [number, number, number];\n}\n\n/**\n * One component of one entity.\n *\n * @public\n */\nexport interface SceneFileComponent {\n /** ULID, unique within the file. */\n readonly uid: string;\n /** The component class's registered `typeId`. */\n readonly type: string;\n /** Omitted when `true`, the default. */\n readonly enabled?: boolean;\n /** Written only when the class's `schemaVersion` differs from `1` (§7). */\n readonly schemaVersion?: number;\n /** Values in the component schema's declaration order (§3). */\n readonly props?: JsonObject;\n}\n\n/**\n * One override patch applied to an instanced scene, addressed by the *instanced* file's uids\n * (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @remarks\n * `op` defaults to `\"replace\"`, which is why the common case is the two-key\n * `{ path, value }` object shown in the format document.\n *\n * @public\n */\nexport interface SceneFileOverride {\n /** `\"replace\"` (the default) patches a value, `\"remove\"` deletes a component, `\"add\"` appends one. */\n readonly op?: \"replace\" | \"remove\" | \"add\";\n /** The path into the instanced file; see {@link parseOverridePath}. */\n readonly path: string;\n /** The new value, for `\"replace\"` and `\"add\"`. */\n readonly value?: JsonValue;\n}\n\n/**\n * The `instance` entry that turns an entity into the root of an instanced scene — what other\n * engines call a prefab instance (ADR-0005).\n *\n * @public\n */\nexport interface SceneFileInstance {\n /** The scene asset to instance. */\n readonly scene: SceneFileAssetRef;\n /** The content hash of that asset at save time; a mismatch reports `IGX-0604`. */\n readonly hash?: string;\n /** The patches applied to the instanced entities, in order. */\n readonly overrides?: readonly SceneFileOverride[];\n}\n\n/**\n * One entity of a scene file. Entities appear in tree order — parents before children, siblings in\n * `children` order — and `parent` names the uid of the parent, or `null` for a root.\n *\n * @public\n */\nexport interface SceneFileEntity {\n /** ULID, unique within the file. */\n readonly uid: string;\n /** The display name. */\n readonly name: string;\n /** The parent's uid, or `null` for a root. */\n readonly parent: string | null;\n /** Omitted when `true`, the default. */\n readonly active?: boolean;\n /** Omitted when `false`, the default. */\n readonly static?: boolean;\n /** The layer **name**, omitted when `\"Default\"`. Names, never indices, so reordering is safe. */\n readonly layer?: string;\n /** The tags, omitted when empty. */\n readonly tags?: readonly string[];\n /** Always present. */\n readonly transform: SceneFileTransform;\n /** Present only on instance roots. */\n readonly instance?: SceneFileInstance;\n /** The entity's own components; on an instance root, the ones added on top of the instance. */\n readonly components?: readonly SceneFileComponent[];\n}\n\n/**\n * A whole scene or prefab file (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @example\n * ```ts\n * const file = serializeScene(world.activeScene);\n * await app.storage.write(\"save.scene.json\", stringifySceneFile(file));\n * ```\n *\n * @public\n */\nexport interface SceneFile {\n /** Always {@link SCENE_FILE_FORMAT}. */\n readonly format: string;\n /** Always {@link SCENE_FORMAT_VERSION} for files this build writes. */\n readonly formatVersion: number;\n /** The `@ignifx/core` version that wrote the file; informational. */\n readonly engineVersion?: string;\n /** The scene's name. */\n readonly name: string;\n /** Scene-level values interpreted by systems (environment, clear colour, physics overrides). */\n readonly settings?: JsonObject;\n /** Every entity, in tree order. */\n readonly entities: readonly SceneFileEntity[];\n}\n\n/**\n * Writes a scene file as the canonical UTF-8 JSON text: two-space indentation, keys in the order\n * the serializer built them, numbers already canonicalized by\n * {@link canonicalizeNumber}. Two saves of the same state produce byte-identical text\n * (`docs/architecture/06-serialization-and-scene-format.md` §1).\n *\n * @param file - The file object, normally from `serializeScene`.\n * @returns The JSON text, without a trailing newline.\n *\n * @example\n * ```ts\n * stringifySceneFile(serializeScene(instance)) === stringifySceneFile(serializeScene(instance));\n * ```\n *\n * @public\n */\nexport function stringifySceneFile(file: SceneFile): string {\n return JSON.stringify(file, null, 2);\n}\n\n/**\n * Reports whether a parsed JSON value carries the `ignifx.scene` header. It is the cheap check the\n * loader runs before anything else, so a `.json` asset handed to the wrong loader fails with\n * `IGX-0308` rather than a confusing field error.\n *\n * @param value - The parsed JSON.\n * @returns `true` when the value is an object whose `format` is {@link SCENE_FILE_FORMAT}.\n *\n * @public\n */\nexport function isSceneFileHeader(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n // Boundary assertion (coding standards §5.2): the three lines above have established that the\n // value is a non-null, non-array object, which is exactly a string-keyed bag.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const object = value as Record<string, unknown>;\n return object[\"format\"] === SCENE_FILE_FORMAT;\n}\n\n/**\n * The draft 2020-12 JSON Schema for a scene file, with `components[].props` narrowed per registered\n * component `typeId` (`docs/architecture/06-serialization-and-scene-format.md` §8). The Vite plugin\n * and the `ignifx schemas` CLI command emit this into `ignifx.schemas.json`, which drives\n * build-time validation and editor autocompletion.\n *\n * @param registry - The component table whose registered classes narrow `props`. Classes without a\n * schema contribute a `type` match with a free-form `props` object.\n * @returns The schema document.\n *\n * @example\n * ```ts\n * const schema = sceneFileJsonSchema(app.world.registry);\n * await writeFile(\"ignifx.schemas.json\", JSON.stringify(schema, null, 2));\n * ```\n *\n * @public\n */\nexport function sceneFileJsonSchema(registry: ComponentRegistry): JsonObject {\n return {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n $id: \"https://ignifx.com/schemas/ignifx.scene.v1.json\",\n title: \"ignifx scene file\",\n type: \"object\",\n required: [\"format\", \"formatVersion\", \"name\", \"entities\"],\n additionalProperties: false,\n properties: {\n format: { const: SCENE_FILE_FORMAT },\n formatVersion: { const: SCENE_FORMAT_VERSION },\n engineVersion: { type: \"string\" },\n name: { type: \"string\" },\n settings: { type: \"object\" },\n entities: { type: \"array\", items: { $ref: \"#/$defs/entity\" } },\n },\n $defs: {\n uid: { type: \"string\", minLength: 1 },\n assetRef: {\n type: \"object\",\n required: [\"$asset\"],\n additionalProperties: false,\n properties: { $asset: { type: \"string\" }, type: { type: \"string\" } },\n },\n transform: {\n type: \"object\",\n required: [\"position\", \"rotation\", \"scale\"],\n additionalProperties: false,\n properties: {\n position: numberTuple(3),\n rotation: numberTuple(4),\n scale: numberTuple(3),\n },\n },\n override: {\n type: \"object\",\n required: [\"path\"],\n additionalProperties: false,\n properties: {\n op: { type: \"string\", enum: [\"replace\", \"remove\", \"add\"] },\n path: { type: \"string\", minLength: 1 },\n value: true,\n },\n },\n instance: {\n type: \"object\",\n required: [\"scene\"],\n additionalProperties: false,\n properties: {\n scene: { $ref: \"#/$defs/assetRef\" },\n hash: { type: \"string\" },\n overrides: { type: \"array\", items: { $ref: \"#/$defs/override\" } },\n },\n },\n component: {\n type: \"object\",\n required: [\"uid\", \"type\"],\n additionalProperties: false,\n properties: {\n uid: { $ref: \"#/$defs/uid\" },\n type: { type: \"string\", minLength: 1 },\n enabled: { type: \"boolean\" },\n schemaVersion: { type: \"integer\", minimum: 1 },\n props: { type: \"object\" },\n },\n allOf: componentPropsBranches(registry),\n },\n entity: {\n type: \"object\",\n required: [\"uid\", \"name\", \"parent\", \"transform\"],\n additionalProperties: false,\n properties: {\n uid: { $ref: \"#/$defs/uid\" },\n name: { type: \"string\" },\n parent: { anyOf: [{ $ref: \"#/$defs/uid\" }, { type: \"null\" }] },\n active: { type: \"boolean\" },\n static: { type: \"boolean\" },\n layer: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n transform: { $ref: \"#/$defs/transform\" },\n instance: { $ref: \"#/$defs/instance\" },\n components: { type: \"array\", items: { $ref: \"#/$defs/component\" } },\n },\n },\n },\n };\n}\n\n/**\n * The docs-harness description of the scene file format\n * (`scripts/README.md`, \"Schema discovery convention\"), so `pnpm docs:schemas` can render\n * `references/formats/scene.md` beside the component pages.\n *\n * @returns The description of the top-level file fields.\n *\n * @public\n */\nexport function describeSceneFileFormat(): SchemaDescription {\n return {\n title: \"Scene file\",\n format: SCENE_FILE_FORMAT,\n description:\n \"A level or a prefab: a tree of entities with components, instanced scenes, and overrides. One format for both (ADR-0005).\",\n fields: {\n format: { kind: \"str\", default: SCENE_FILE_FORMAT, description: 'Always \"ignifx.scene\".' },\n formatVersion: {\n kind: \"u32\",\n default: SCENE_FORMAT_VERSION,\n description: \"The file format version; 1 before ignifx 1.0.\",\n },\n engineVersion: { kind: \"str\", default: \"\", description: \"The @ignifx/core version that wrote the file.\" },\n name: { kind: \"str\", default: \"\", description: \"The scene's name.\" },\n settings: { kind: \"map\", default: {}, description: \"Scene-level values interpreted by systems.\" },\n entities: { kind: \"array\", default: [], description: \"Every entity, in tree order.\" },\n },\n };\n}\n\n/**\n * A fixed-length JSON Schema array of numbers.\n *\n * @param length - How many entries.\n * @returns The fragment.\n */\nfunction numberTuple(length: number): JsonObject {\n return { type: \"array\", items: { type: \"number\" }, minItems: length, maxItems: length };\n}\n\n/**\n * One `if`/`then` branch per registered component `typeId`, narrowing `props` to that class's\n * generated schema.\n *\n * @param registry - The component table.\n * @returns The branches, in `typeId` order so the document is stable.\n */\nfunction componentPropsBranches(registry: ComponentRegistry): readonly JsonValue[] {\n const branches: JsonValue[] = [];\n const entries: { readonly typeId: string; readonly props: JsonObject }[] = [];\n const registrations = registry.registrations();\n for (let index = 0; index < registrations.length; index += 1) {\n const registration = registrations[index];\n if (registration === undefined) {\n continue;\n }\n const [typeId, type] = registration;\n const schema = registry.describe(type).schema;\n if (schema === null) {\n continue;\n }\n entries.push({ typeId, props: toJsonSchema(schema) });\n }\n entries.sort((left, right) => (left.typeId < right.typeId ? -1 : left.typeId > right.typeId ? 1 : 0));\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry === undefined) {\n continue;\n }\n branches.push({\n if: { properties: { type: { const: entry.typeId } }, required: [\"type\"] },\n // `then` is JSON Schema's conditional keyword here, not a promise method; the object never\n // reaches an `await`, it is serialized into the schema document.\n // oxlint-disable-next-line unicorn/no-thenable\n then: { properties: { props: entry.props } },\n });\n }\n return branches;\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { stringifySceneFile } from \"./scene-file.js\";\nimport type { SceneFile } from \"./scene-file.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\n\n/**\n * What the scene loader produces for a `*.scene.json` or `*.prefab.json` address: the parsed file,\n * every asset it pulled in, and the content hash instance overrides are recorded against\n * (`docs/architecture/05-assets-and-loading.md` §2, `06-serialization-and-scene-format.md` §2).\n *\n * @remarks\n * The handles are already loaded and retained by the asset. That is what lets\n * `world.instantiate(sceneAsset)` be synchronous: everything the file references — textures,\n * materials, and the scene assets its `instance` entries name — is in memory by the time the\n * `SceneAsset` exists (`02-scene-graph.md` §2).\n *\n * @public\n */\nexport interface SceneAsset {\n /** The address the asset was loaded from. */\n readonly address: string;\n /** The parsed, validated file. */\n readonly file: SceneFile;\n /** Every asset the file references, already loaded, in resolution order. */\n readonly dependencies: readonly AssetHandle[];\n /** The content hash of {@link SceneAsset.file}, as `sha256:<hex>`. */\n readonly hash: string;\n}\n\n/** The hash algorithm and the prefix it is written under. */\nconst HASH_ALGORITHM = \"SHA-256\";\n\n/** The prefix `instance.hash` values carry. */\nconst HASH_PREFIX = \"sha256:\";\n\n/**\n * The content hash of a scene file: SHA-256 over the canonical JSON text, so two saves of the same\n * state hash the same and an edited prefab does not\n * (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @param file - The file to hash.\n * @returns The hash as `sha256:<64 lowercase hex digits>`.\n * @throws IgnifxError with code `IGX-1420` when the host exposes no Web Crypto `subtle`.\n *\n * @example\n * ```ts\n * const hash = await computeSceneHash(serializeScene(instance)); // \"sha256:9f2c…\"\n * ```\n *\n * @public\n */\nexport async function computeSceneHash(file: SceneFile): Promise<string> {\n // The DOM lib declares `globalThis.crypto` as always present. Node before 19, workers without a\n // secure context, and locked-down embedders do not have `subtle`, so the assertion models the\n // absence the types deny (coding standards §5.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const webCrypto = globalThis.crypto as Crypto | undefined;\n const subtle: SubtleCrypto | undefined = webCrypto?.subtle;\n if (subtle === undefined || typeof subtle.digest !== \"function\") {\n throw new IgnifxError(CoreErrorCode.cryptoUnavailable, \"This host does not expose Web Crypto subtle.\", {\n context: { file: file.name },\n hint: \"Scene content hashes need crypto.subtle; run on a secure context or Node 19+.\",\n });\n }\n const bytes = new TextEncoder().encode(stringifySceneFile(file));\n const digest = await subtle.digest(HASH_ALGORITHM, bytes);\n return HASH_PREFIX + toHex(new Uint8Array(digest));\n}\n\n/**\n * Builds a `SceneAsset` from a file that is already in memory — the shape the loader returns, and\n * the one tests and tools use when there is no asset service in play.\n *\n * @param address - The address the asset stands at.\n * @param file - The parsed file.\n * @param dependencies - Every asset the file references, already loaded.\n * @returns The asset, with its content hash computed.\n *\n * @example\n * ```ts\n * const prefab = await createSceneAsset(\"prefabs/enemy.prefab.json\", enemyFile, []);\n * ```\n *\n * @public\n */\nexport async function createSceneAsset(\n address: string,\n file: SceneFile,\n dependencies: readonly AssetHandle[] = [],\n): Promise<SceneAsset> {\n return { address, file, dependencies, hash: await computeSceneHash(file) };\n}\n\n/**\n * Finds the loaded scene asset an `instance.scene` reference names, among a scene's dependencies.\n *\n * @param asset - The scene whose `instance` entry is being expanded.\n * @param address - The address the reference carries.\n * @returns The dependency handle and its value, or `null` when nothing loaded stands at that\n * address.\n *\n * @internal\n */\nexport function findSceneDependency(\n asset: SceneAsset,\n address: string,\n): { readonly handle: AssetHandle<SceneAsset>; readonly value: SceneAsset } | null {\n const dependencies = asset.dependencies;\n for (let index = 0; index < dependencies.length; index += 1) {\n const handle = dependencies[index];\n if (handle === undefined || handle.address !== address || handle.state !== \"loaded\") {\n continue;\n }\n const value: unknown = handle.value;\n if (!isSceneAsset(value)) {\n continue;\n }\n // Boundary assertion (coding standards §5.2): `isSceneAsset` has just established the shape,\n // and `AssetHandle<T>` differs from `AssetHandle` only in the type of `value`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return { handle: handle as AssetHandle<SceneAsset>, value };\n }\n return null;\n}\n\n/**\n * Reports whether a loaded asset value is a scene.\n *\n * @param value - The handle's value.\n * @returns `true` when the value carries a scene file and a hash.\n *\n * @internal\n */\nexport function isSceneAsset(value: unknown): value is SceneAsset {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const file: unknown = Reflect.get(value, \"file\");\n return typeof Reflect.get(value, \"hash\") === \"string\" && typeof file === \"object\" && file !== null;\n}\n\n/** Lowercase hexadecimal digits, indexed by nibble. */\nconst HEX_DIGITS = \"0123456789abcdef\";\n\n/**\n * Formats bytes as lowercase hexadecimal.\n *\n * @param bytes - The digest.\n * @returns The hex string.\n */\nfunction toHex(bytes: Uint8Array): string {\n let text = \"\";\n for (let index = 0; index < bytes.length; index += 1) {\n const byte = bytes[index] ?? 0;\n text += (HEX_DIGITS[byte >> 4] ?? \"0\") + (HEX_DIGITS[byte & 0xf] ?? \"0\");\n }\n return text;\n}\n","import { SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION } from \"./scene-file.js\";\nimport type { SceneFile } from \"./scene-file.js\";\n\n/**\n * One structural problem in a scene file.\n *\n * @public\n */\nexport interface SceneFileIssue {\n /** Where the problem is, in JSON-pointer-like notation, for example `entities/3/transform`. */\n readonly path: string;\n /** An actionable description. */\n readonly message: string;\n}\n\n/**\n * Validates a parsed JSON value against the scene file format\n * (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @remarks\n * The checks mirror {@link sceneFileJsonSchema} clause for clause — required keys, value types,\n * tuple lengths, uid uniqueness, and the `parent` and override shapes — and are hand-written\n * because the engine ships no JSON Schema runtime and takes no dependency to gain one\n * (`CONSTITUTION.md` §2.3). The generated document remains the artefact the Vite plugin and editors\n * validate against; this is the same rule set, executable at load time.\n *\n * Component `props` are *not* checked here: `decodeProps` already reports every field problem with\n * a schema issue code, per field, which is more precise than a document-level match.\n *\n * @param value - The parsed JSON.\n * @returns Every problem found, in discovery order; empty when the value is a valid scene file.\n *\n * @example\n * ```ts\n * const issues = validateSceneFile(JSON.parse(text));\n * if (issues.length > 0) {\n * throw new IgnifxError(CoreErrorCode.sceneFileInvalid, issues[0].message);\n * }\n * ```\n *\n * @public\n */\nexport function validateSceneFile(value: unknown): readonly SceneFileIssue[] {\n const issues: SceneFileIssue[] = [];\n const file = asRecord(value);\n if (file === null) {\n issues.push({ path: \"\", message: \"a scene file is a JSON object.\" });\n return issues;\n }\n if (file[\"format\"] !== SCENE_FILE_FORMAT) {\n issues.push({ path: \"format\", message: `expected \"${SCENE_FILE_FORMAT}\".` });\n }\n if (file[\"formatVersion\"] !== SCENE_FORMAT_VERSION) {\n issues.push({ path: \"formatVersion\", message: `expected ${String(SCENE_FORMAT_VERSION)}.` });\n }\n if (typeof file[\"name\"] !== \"string\") {\n issues.push({ path: \"name\", message: \"expected a string.\" });\n }\n const settings = file[\"settings\"];\n if (settings !== undefined && asRecord(settings) === null) {\n issues.push({ path: \"settings\", message: \"expected an object.\" });\n }\n const entities = file[\"entities\"];\n if (!Array.isArray(entities)) {\n issues.push({ path: \"entities\", message: \"expected an array.\" });\n return issues;\n }\n const uids = new Set<string>();\n for (let index = 0; index < entities.length; index += 1) {\n validateEntity(entities[index], `entities/${String(index)}`, uids, issues);\n }\n return issues;\n}\n\n/**\n * Narrows a value to a scene file after {@link validateSceneFile} has passed.\n *\n * @param value - The validated JSON.\n * @returns The same value, typed as a scene file.\n *\n * @internal\n */\nexport function asSceneFile(value: unknown): SceneFile {\n // Boundary assertion (coding standards §5.2): the invariant is that `validateSceneFile` returned\n // no issues for this exact value, which is every constraint the interface expresses.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as SceneFile;\n}\n\n/**\n * Validates one entity entry.\n *\n * @param value - The entry.\n * @param path - Its path, for issue messages.\n * @param uids - Uids already seen in the file, for the uniqueness check.\n * @param issues - Where problems are appended.\n */\nfunction validateEntity(value: unknown, path: string, uids: Set<string>, issues: SceneFileIssue[]): void {\n const entity = asRecord(value);\n if (entity === null) {\n issues.push({ path, message: \"expected an object.\" });\n return;\n }\n requireUid(entity[\"uid\"], `${path}/uid`, uids, issues);\n if (typeof entity[\"name\"] !== \"string\") {\n issues.push({ path: `${path}/name`, message: \"expected a string.\" });\n }\n const parent = entity[\"parent\"];\n if (parent !== null && typeof parent !== \"string\") {\n issues.push({ path: `${path}/parent`, message: \"expected a uid string or null.\" });\n }\n requireBoolean(entity[\"active\"], `${path}/active`, issues);\n requireBoolean(entity[\"static\"], `${path}/static`, issues);\n if (entity[\"layer\"] !== undefined && typeof entity[\"layer\"] !== \"string\") {\n issues.push({ path: `${path}/layer`, message: \"expected a layer name string.\" });\n }\n validateTags(entity[\"tags\"], `${path}/tags`, issues);\n validateTransform(entity[\"transform\"], `${path}/transform`, issues);\n validateInstance(entity[\"instance\"], `${path}/instance`, issues);\n const components = entity[\"components\"];\n if (components === undefined) {\n return;\n }\n if (!Array.isArray(components)) {\n issues.push({ path: `${path}/components`, message: \"expected an array.\" });\n return;\n }\n for (let index = 0; index < components.length; index += 1) {\n validateComponent(components[index], `${path}/components/${String(index)}`, uids, issues);\n }\n}\n\n/**\n * Validates one component entry.\n *\n * @param value - The entry.\n * @param path - Its path.\n * @param uids - Uids already seen.\n * @param issues - Where problems are appended.\n */\nfunction validateComponent(value: unknown, path: string, uids: Set<string>, issues: SceneFileIssue[]): void {\n const component = asRecord(value);\n if (component === null) {\n issues.push({ path, message: \"expected an object.\" });\n return;\n }\n requireUid(component[\"uid\"], `${path}/uid`, uids, issues);\n const type = component[\"type\"];\n if (typeof type !== \"string\" || type === \"\") {\n issues.push({ path: `${path}/type`, message: \"expected a registered component type id.\" });\n }\n requireBoolean(component[\"enabled\"], `${path}/enabled`, issues);\n const version = component[\"schemaVersion\"];\n if (version !== undefined && (typeof version !== \"number\" || !Number.isInteger(version) || version < 1)) {\n issues.push({ path: `${path}/schemaVersion`, message: \"expected a positive integer.\" });\n }\n const props = component[\"props\"];\n if (props !== undefined && asRecord(props) === null) {\n issues.push({ path: `${path}/props`, message: \"expected an object.\" });\n }\n}\n\n/**\n * Validates an `instance` entry.\n *\n * @param value - The entry, or `undefined`.\n * @param path - Its path.\n * @param issues - Where problems are appended.\n */\nfunction validateInstance(value: unknown, path: string, issues: SceneFileIssue[]): void {\n if (value === undefined) {\n return;\n }\n const instance = asRecord(value);\n if (instance === null) {\n issues.push({ path, message: \"expected an object.\" });\n return;\n }\n const scene = asRecord(instance[\"scene\"]);\n if (scene === null || typeof scene[\"$asset\"] !== \"string\") {\n issues.push({ path: `${path}/scene`, message: 'expected { \"$asset\": \"<address>\" }.' });\n }\n if (instance[\"hash\"] !== undefined && typeof instance[\"hash\"] !== \"string\") {\n issues.push({ path: `${path}/hash`, message: \"expected a string.\" });\n }\n const overrides = instance[\"overrides\"];\n if (overrides === undefined) {\n return;\n }\n if (!Array.isArray(overrides)) {\n issues.push({ path: `${path}/overrides`, message: \"expected an array.\" });\n return;\n }\n for (let index = 0; index < overrides.length; index += 1) {\n const at = `${path}/overrides/${String(index)}`;\n const override = asRecord(overrides[index]);\n if (override === null || typeof override[\"path\"] !== \"string\" || override[\"path\"] === \"\") {\n issues.push({ path: at, message: \"expected an object with a non-empty path.\" });\n continue;\n }\n const op = override[\"op\"];\n if (op !== undefined && op !== \"replace\" && op !== \"remove\" && op !== \"add\") {\n issues.push({ path: `${at}/op`, message: 'expected \"replace\", \"remove\", or \"add\".' });\n }\n }\n}\n\n/**\n * Validates a `transform` entry.\n *\n * @param value - The entry.\n * @param path - Its path.\n * @param issues - Where problems are appended.\n */\nfunction validateTransform(value: unknown, path: string, issues: SceneFileIssue[]): void {\n const transform = asRecord(value);\n if (transform === null) {\n issues.push({ path, message: \"expected an object with position, rotation, and scale.\" });\n return;\n }\n requireNumbers(transform[\"position\"], `${path}/position`, 3, issues);\n requireNumbers(transform[\"rotation\"], `${path}/rotation`, 4, issues);\n requireNumbers(transform[\"scale\"], `${path}/scale`, 3, issues);\n}\n\n/**\n * Validates a `tags` array.\n *\n * @param value - The array, or `undefined`.\n * @param path - Its path.\n * @param issues - Where problems are appended.\n */\nfunction validateTags(value: unknown, path: string, issues: SceneFileIssue[]): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n issues.push({ path, message: \"expected an array of strings.\" });\n return;\n }\n for (let index = 0; index < value.length; index += 1) {\n if (typeof value[index] !== \"string\") {\n issues.push({ path: `${path}/${String(index)}`, message: \"expected a string.\" });\n }\n }\n}\n\n/**\n * Checks a uid: a non-empty string, unique within the file.\n *\n * @param value - The candidate.\n * @param path - Its path.\n * @param uids - Uids already seen.\n * @param issues - Where problems are appended.\n */\nfunction requireUid(value: unknown, path: string, uids: Set<string>, issues: SceneFileIssue[]): void {\n if (typeof value !== \"string\" || value === \"\") {\n issues.push({ path, message: \"expected a non-empty uid string.\" });\n return;\n }\n if (uids.has(value)) {\n issues.push({ path, message: `the uid ${value} is used twice; uids are unique within a file.` });\n return;\n }\n uids.add(value);\n}\n\n/**\n * Checks an optional boolean.\n *\n * @param value - The candidate.\n * @param path - Its path.\n * @param issues - Where problems are appended.\n */\nfunction requireBoolean(value: unknown, path: string, issues: SceneFileIssue[]): void {\n if (value !== undefined && typeof value !== \"boolean\") {\n issues.push({ path, message: \"expected a boolean.\" });\n }\n}\n\n/**\n * Checks a fixed-length array of finite numbers.\n *\n * @param value - The candidate.\n * @param path - Its path.\n * @param length - How many entries are required.\n * @param issues - Where problems are appended.\n */\nfunction requireNumbers(value: unknown, path: string, length: number, issues: SceneFileIssue[]): void {\n if (!Array.isArray(value) || value.length !== length) {\n issues.push({ path, message: `expected an array of ${String(length)} numbers.` });\n return;\n }\n for (let index = 0; index < value.length; index += 1) {\n const entry: unknown = value[index];\n if (typeof entry !== \"number\" || !Number.isFinite(entry)) {\n issues.push({ path: `${path}/${String(index)}`, message: \"expected a finite number.\" });\n }\n }\n}\n\n/**\n * Narrows a value to a string-keyed object.\n *\n * @param value - The candidate.\n * @returns The record, or `null` when the value is not a plain object.\n */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // Boundary assertion (coding standards §5.2): the guard above is exactly \"a plain object\", which\n // is a string-keyed bag of unknowns.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as Record<string, unknown>;\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { asJsonArray, asJsonObject } from \"./json-view.js\";\nimport { computeSceneHash } from \"./scene-asset.js\";\nimport { isSceneFileHeader, SCENE_ASSET_TYPE, SCENE_FILE_EXTENSIONS, SCENE_FORMAT_VERSION } from \"./scene-file.js\";\nimport { asSceneFile, validateSceneFile } from \"./validate.js\";\nimport type { SceneAsset } from \"./scene-asset.js\";\nimport type { SceneFile, SceneFileComponent, SceneFileEntity } from \"./scene-file.js\";\nimport type { AssetHandle, AssetLoader, LoaderContext } from \"../assets/types.js\";\nimport type { JsonValue } from \"../schema/json.js\";\n\n/**\n * Options accepted by {@link createSceneLoader}.\n *\n * @public\n */\nexport interface SceneLoaderOptions {\n /**\n * `true` (the default) validates every file against the scene format before building anything,\n * reporting `IGX-0608` with the issue list. Production builds may switch it off once the content\n * has been validated at build time by the Vite plugin\n * (`docs/architecture/06-serialization-and-scene-format.md` §8).\n */\n readonly validate?: boolean;\n}\n\n/**\n * The `AssetLoader` for `*.scene.json` and `*.prefab.json`\n * (`docs/architecture/06-serialization-and-scene-format.md` §4 steps 1 and 2, ADR-0005 — one\n * loader for levels and prefabs).\n *\n * @remarks\n * The loader does everything the file needs *before* the world sees it: parse, check the header and\n * the format version, validate the structure, then resolve every `$asset` it can find — in\n * `settings`, in every component's `props`, and in every `instance.scene`, recursively through the\n * scene assets those pull in. The resulting `SceneAsset` therefore carries a fully loaded\n * dependency set, which is what makes `world.instantiate` synchronous\n * (`02-scene-graph.md` §2).\n *\n * @param options - Whether to validate.\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createSceneLoader());\n * const level = await app.assets.loadAsync<SceneAsset>(\"levels/level01.scene.json\");\n * ```\n *\n * @public\n */\nexport function createSceneLoader(options?: SceneLoaderOptions): AssetLoader<SceneAsset> {\n const validate = options?.validate ?? true;\n return {\n type: SCENE_ASSET_TYPE,\n extensions: SCENE_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<SceneAsset> {\n const parsed: unknown = await ctx.fetchJson();\n const file = readSceneFile(parsed, ctx.address, validate);\n const dependencies = await loadDependencies(file, ctx);\n return { address: ctx.address, file, dependencies, hash: await computeSceneHash(file) };\n },\n };\n}\n\n/**\n * Checks a parsed file's header, version, and structure.\n *\n * @param parsed - The parsed JSON.\n * @param address - The address, for diagnostics.\n * @param validate - `true` runs the structural validation.\n * @returns The file.\n * @throws IgnifxError with code `IGX-0308` when the header is missing, `IGX-0603` when the format\n * version is not readable, and `IGX-0608` when the structure does not match.\n *\n * @internal\n */\nexport function readSceneFile(parsed: unknown, address: string, validate: boolean): SceneFile {\n if (!isSceneFileHeader(parsed)) {\n throw new IgnifxError(CoreErrorCode.notASceneFile, `${address} is not an ignifx scene file.`, {\n context: { file: address },\n hint: 'A scene file carries { \"format\": \"ignifx.scene\", \"formatVersion\": 1 }.',\n });\n }\n // Boundary assertion (coding standards §5.2): `isSceneFileHeader` established that the value is a\n // plain object, which is all this read of `formatVersion` needs.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const version = (parsed as Record<string, unknown>)[\"formatVersion\"];\n if (version !== SCENE_FORMAT_VERSION) {\n throw new IgnifxError(\n CoreErrorCode.unsupportedFormatVersion,\n `${address} declares format version ${String(version)}, which this build cannot read.`,\n {\n context: { file: address, version: String(version) },\n hint: `This build reads ignifx.scene version ${String(SCENE_FORMAT_VERSION)}.`,\n },\n );\n }\n if (validate) {\n const issues = validateSceneFile(parsed);\n const first = issues[0];\n if (first !== undefined) {\n throw new IgnifxError(\n CoreErrorCode.sceneFileInvalid,\n `${address} does not match the scene file schema: ${issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"; \")}`,\n { context: { file: address, issues: issues.length, first: first.path } },\n );\n }\n }\n return asSceneFile(parsed);\n}\n\n/**\n * Loads every asset the file references, in a stable order: `settings` first, then each entity's\n * `instance.scene`, then each component's `props`\n * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 2).\n *\n * @param file - The parsed file.\n * @param ctx - The loader context.\n * @returns The loaded handles, deduplicated by address, in discovery order.\n */\nasync function loadDependencies(file: SceneFile, ctx: LoaderContext): Promise<readonly AssetHandle[]> {\n const requests: { readonly address: string; readonly type: string | null }[] = [];\n const seen = new Set<string>();\n const add = (address: string, type: string | null): void => {\n if (address === \"\" || seen.has(address)) {\n return;\n }\n seen.add(address);\n requests.push({ address, type });\n };\n const settings = file.settings;\n if (settings !== undefined) {\n collectAssetRefs(settings, add);\n }\n for (let index = 0; index < file.entities.length; index += 1) {\n const entity = file.entities[index];\n if (entity !== undefined) {\n collectEntityRefs(entity, add);\n }\n }\n // Every dependency is requested at once and awaited together: the asset service already applies\n // the project's concurrency limit, so serialising here would only make a scene load slower.\n return Promise.all(\n requests.map(async (request) =>\n ctx.loadDependency(request.address, request.type === null ? undefined : { type: request.type }),\n ),\n );\n}\n\n/**\n * Collects the asset references of one entity: its `instance.scene` first, so a nested scene is\n * loaded before the props that may name sub-assets of it, then every component's props.\n *\n * @param entity - The entity record.\n * @param add - Called with each address and its declared type.\n */\nfunction collectEntityRefs(entity: SceneFileEntity, add: (address: string, type: string | null) => void): void {\n const instance = entity.instance;\n if (instance !== undefined) {\n add(instance.scene.$asset, instance.scene.type ?? SCENE_ASSET_TYPE);\n const overrides = instance.overrides ?? [];\n for (let index = 0; index < overrides.length; index += 1) {\n const value = overrides[index]?.value;\n if (value !== undefined) {\n collectAssetRefs(value, add);\n }\n }\n }\n const components = entity.components ?? [];\n for (let index = 0; index < components.length; index += 1) {\n const component: SceneFileComponent | undefined = components[index];\n const props = component?.props;\n if (props !== undefined) {\n collectAssetRefs(props, add);\n }\n }\n}\n\n/**\n * Walks any JSON and reports every `{ \"$asset\": … }` it finds, at any depth.\n *\n * @param value - The JSON to walk.\n * @param add - Called with each address and its declared type.\n */\nfunction collectAssetRefs(value: JsonValue, add: (address: string, type: string | null) => void): void {\n const items = asJsonArray(value);\n if (items !== null) {\n for (let index = 0; index < items.length; index += 1) {\n collectAssetRefs(items[index] ?? null, add);\n }\n return;\n }\n const object = asJsonObject(value);\n if (object === null) {\n return;\n }\n const address = object[\"$asset\"];\n if (typeof address === \"string\") {\n const type = object[\"type\"];\n add(address, typeof type === \"string\" ? type : null);\n return;\n }\n for (const key of Object.keys(object)) {\n collectAssetRefs(object[key] ?? null, add);\n }\n}\n","import { Mat4 } from \"./mat4.js\";\nimport { EPSILON, lerp } from \"./math-utils.js\";\nimport type { Mat4Like, MutableVec3, Vec3Like } from \"./types.js\";\n\n/**\n * A 3-component vector: a position or a direction in metres, or a per-axis scale. ignifx is\n * left-handed with Y up and +Z forward (ADR-0011), so {@link Vec3.forward} is `(0, 0, 1)` and\n * {@link Vec3.right} is `(1, 0, 0)`.\n *\n * The fields are plain mutable numbers, which is what makes a `Vec3` interchangeable with Babylon\n * Lite's `{ x, y, z }` vectors and with the live {@link MutableVec3} views a `Transform` exposes.\n *\n * Three families of operations, and the names say which is which:\n *\n * - instance methods mutate the receiver and return `this` (`a.add(b)` means `a += b`);\n * - `ToRef` statics write into a final `out` argument, allocate nothing, and are safe when `out`\n * aliases an input — these are what per-frame code uses (coding standards section 7);\n * - the remaining statics return a fresh vector and are documented as allocating.\n *\n * @example\n * ```ts\n * // convenience code\n * const offset = Vec3.add(position, Vec3.scale(direction, distance));\n *\n * // per-frame code: no allocation\n * Vec3.scaleToRef(direction, distance, scratch);\n * Vec3.addToRef(position, scratch, position);\n * ```\n *\n * @public\n */\nexport class Vec3 {\n /** The X component; positive is right. */\n x: number;\n /** The Y component; positive is up. */\n y: number;\n /** The Z component; positive is forward. */\n z: number;\n\n /**\n * Creates a vector.\n *\n * @param x - The X component. Defaults to 0.\n * @param y - The Y component. Defaults to 0.\n * @param z - The Z component. Defaults to 0.\n */\n constructor(x: number = 0, y: number = 0, z: number = 0) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n /**\n * Assigns every component at once.\n *\n * @param x - The new X component.\n * @param y - The new Y component.\n * @param z - The new Z component.\n * @returns This vector.\n */\n set(x: number, y: number, z: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n\n /**\n * Copies every component from another vector.\n *\n * @param v - The vector to read.\n * @returns This vector.\n */\n copyFrom(v: Vec3Like): this {\n this.x = v.x;\n this.y = v.y;\n this.z = v.z;\n return this;\n }\n\n /**\n * Copies this vector into a new one.\n *\n * @returns A new vector. **Allocates.**\n */\n clone(): Vec3 {\n return new Vec3(this.x, this.y, this.z);\n }\n\n /**\n * Adds another vector to this one.\n *\n * @param v - The vector to add.\n * @returns This vector.\n */\n add(v: Vec3Like): this {\n this.x += v.x;\n this.y += v.y;\n this.z += v.z;\n return this;\n }\n\n /**\n * Adds a scaled vector to this one — the \"move by velocity times delta time\" step, without a\n * temporary.\n *\n * @param v - The vector to add.\n * @param scale - The factor to multiply `v` by first.\n * @returns This vector.\n *\n * @example\n * ```ts\n * position.addScaled(velocity, time.deltaTime);\n * ```\n */\n addScaled(v: Vec3Like, scale: number): this {\n this.x += v.x * scale;\n this.y += v.y * scale;\n this.z += v.z * scale;\n return this;\n }\n\n /**\n * Subtracts another vector from this one.\n *\n * @param v - The vector to subtract.\n * @returns This vector.\n */\n subtract(v: Vec3Like): this {\n this.x -= v.x;\n this.y -= v.y;\n this.z -= v.z;\n return this;\n }\n\n /**\n * Multiplies this vector by another component by component.\n *\n * @param v - The vector to multiply by.\n * @returns This vector.\n */\n multiply(v: Vec3Like): this {\n this.x *= v.x;\n this.y *= v.y;\n this.z *= v.z;\n return this;\n }\n\n /**\n * Multiplies every component by a number.\n *\n * @param scale - The factor.\n * @returns This vector.\n */\n scale(scale: number): this {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n return this;\n }\n\n /**\n * Flips this vector to point the other way.\n *\n * @returns This vector.\n */\n negate(): this {\n this.x = -this.x;\n this.y = -this.y;\n this.z = -this.z;\n return this;\n }\n\n /**\n * Scales this vector to unit length. A zero-length vector is left at zero rather than becoming\n * `NaN`, so callers can normalize an unchecked direction safely.\n *\n * @returns This vector.\n */\n normalize(): this {\n const length = Math.hypot(this.x, this.y, this.z);\n if (length === 0) {\n return this;\n }\n return this.scale(1 / length);\n }\n\n /**\n * Replaces this vector with its cross product with another (`this = this x v`).\n *\n * @param v - The right-hand vector.\n * @returns This vector.\n */\n cross(v: Vec3Like): this {\n return Vec3.crossToRef(this, v, this);\n }\n\n /**\n * Moves this vector towards a target by an interpolant.\n *\n * @param target - The vector reached at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns This vector.\n */\n lerp(target: Vec3Like, t: number): this {\n return Vec3.lerpToRef(this, target, t, this);\n }\n\n /**\n * The dot product of this vector with another.\n *\n * @param v - The other vector.\n * @returns The dot product.\n */\n dot(v: Vec3Like): number {\n return this.x * v.x + this.y * v.y + this.z * v.z;\n }\n\n /**\n * The length of this vector, in metres.\n *\n * @returns The length.\n */\n length(): number {\n return Math.hypot(this.x, this.y, this.z);\n }\n\n /**\n * The squared length of this vector. Prefer it over `length()` when comparing distances:\n * it skips the square root.\n *\n * @returns The squared length.\n */\n lengthSquared(): number {\n return this.x * this.x + this.y * this.y + this.z * this.z;\n }\n\n /**\n * The distance from this vector to another, in metres.\n *\n * @param v - The other position.\n * @returns The distance.\n */\n distance(v: Vec3Like): number {\n return Math.hypot(this.x - v.x, this.y - v.y, this.z - v.z);\n }\n\n /**\n * The squared distance from this vector to another.\n *\n * @param v - The other position.\n * @returns The squared distance.\n */\n distanceSquared(v: Vec3Like): number {\n return Vec3.distanceSquared(this, v);\n }\n\n /**\n * Compares this vector with another, component by component, with a tolerance.\n *\n * @param v - The vector to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(v: Vec3Like, epsilon: number = EPSILON): boolean {\n return Vec3.equalsWithEpsilon(this, v, epsilon);\n }\n\n /**\n * Writes this vector into a `Float32Array`, for GPU upload. The output comes first to mirror\n * Babylon Lite's `ObservableVec3.toArray`, the shape the adapter has to interoperate with.\n *\n * @param out - The array to write into.\n * @param offset - The index of the X component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.x;\n out[offset + 1] = this.y;\n out[offset + 2] = this.z;\n return out;\n }\n\n /**\n * The zero vector.\n *\n * @returns A new `(0, 0, 0)`. **Allocates**; use {@link VEC3_ZERO} when a read-only value will do.\n */\n static zero(): Vec3 {\n return new Vec3(0, 0, 0);\n }\n\n /**\n * The vector whose components are all one.\n *\n * @returns A new `(1, 1, 1)`. **Allocates.**\n */\n static one(): Vec3 {\n return new Vec3(1, 1, 1);\n }\n\n /**\n * The world up direction.\n *\n * @returns A new `(0, 1, 0)`. **Allocates**; see {@link VEC3_UP}.\n */\n static up(): Vec3 {\n return new Vec3(0, 1, 0);\n }\n\n /**\n * The world down direction.\n *\n * @returns A new `(0, -1, 0)`. **Allocates.**\n */\n static down(): Vec3 {\n return new Vec3(0, -1, 0);\n }\n\n /**\n * The world right direction.\n *\n * @returns A new `(1, 0, 0)`. **Allocates**; see {@link VEC3_RIGHT}.\n */\n static right(): Vec3 {\n return new Vec3(1, 0, 0);\n }\n\n /**\n * The world left direction.\n *\n * @returns A new `(-1, 0, 0)`. **Allocates.**\n */\n static left(): Vec3 {\n return new Vec3(-1, 0, 0);\n }\n\n /**\n * The world forward direction. ignifx is left-handed, so forward is **+Z** (ADR-0011).\n *\n * @returns A new `(0, 0, 1)`. **Allocates**; see {@link VEC3_FORWARD}.\n */\n static forward(): Vec3 {\n return new Vec3(0, 0, 1);\n }\n\n /**\n * The world backward direction.\n *\n * @returns A new `(0, 0, -1)`. **Allocates.**\n */\n static backward(): Vec3 {\n return new Vec3(0, 0, -1);\n }\n\n /**\n * Copies any vector-shaped value into a `Vec3`.\n *\n * @param v - The vector to copy.\n * @returns A new vector. **Allocates.**\n *\n * @example\n * ```ts\n * const position = Vec3.from(node.position); // snapshot of a live Lite view\n * ```\n */\n static from(v: Vec3Like): Vec3 {\n return new Vec3(v.x, v.y, v.z);\n }\n\n /**\n * Adds two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns A new vector. **Allocates**; use {@link Vec3.addToRef} in per-frame code.\n */\n static add(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.addToRef(a, b, new Vec3());\n }\n\n /**\n * Subtracts one vector from another.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @returns A new vector holding `a - b`. **Allocates.**\n */\n static subtract(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.subtractToRef(a, b, new Vec3());\n }\n\n /**\n * Multiplies a vector by a number.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @returns A new vector. **Allocates.**\n */\n static scale(v: Vec3Like, scale: number): Vec3 {\n return Vec3.scaleToRef(v, scale, new Vec3());\n }\n\n /**\n * The cross product of two vectors.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @returns A new vector holding `a x b`. **Allocates.**\n */\n static cross(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.crossToRef(a, b, new Vec3());\n }\n\n /**\n * A unit-length copy of a vector.\n *\n * @param v - The vector to normalize.\n * @returns A new vector. **Allocates.**\n */\n static normalize(v: Vec3Like): Vec3 {\n return Vec3.normalizeToRef(v, new Vec3());\n }\n\n /**\n * Linearly interpolates between two vectors.\n *\n * @param a - The vector returned at `t === 0`.\n * @param b - The vector returned at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns A new vector. **Allocates.**\n */\n static lerp(a: Vec3Like, b: Vec3Like, t: number): Vec3 {\n return Vec3.lerpToRef(a, b, t, new Vec3());\n }\n\n /**\n * Writes `a + b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static addToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x + b.x, a.y + b.y, a.z + b.z);\n return out;\n }\n\n /**\n * Writes `a - b` into `out`.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static subtractToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x - b.x, a.y - b.y, a.z - b.z);\n return out;\n }\n\n /**\n * Writes the component-wise product `a * b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x * b.x, a.y * b.y, a.z * b.z);\n return out;\n }\n\n /**\n * Writes `v * scale` into `out`.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static scaleToRef<TOut extends MutableVec3>(v: Vec3Like, scale: number, out: TOut): TOut {\n out.set(v.x * scale, v.y * scale, v.z * scale);\n return out;\n }\n\n /**\n * Writes `-v` into `out`.\n *\n * @param v - The vector to flip.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static negateToRef<TOut extends MutableVec3>(v: Vec3Like, out: TOut): TOut {\n out.set(-v.x, -v.y, -v.z);\n return out;\n }\n\n /**\n * Writes a unit-length copy of `v` into `out`. A zero-length input is written as zero rather than\n * `NaN`.\n *\n * @param v - The vector to normalize.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static normalizeToRef<TOut extends MutableVec3>(v: Vec3Like, out: TOut): TOut {\n const length = Math.hypot(v.x, v.y, v.z);\n if (length === 0) {\n out.set(0, 0, 0);\n return out;\n }\n const inv = 1 / length;\n out.set(v.x * inv, v.y * inv, v.z * inv);\n return out;\n }\n\n /**\n * Writes `a x b` into `out`.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static crossToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n const ax = a.x;\n const ay = a.y;\n const az = a.z;\n const bx = b.x;\n const by = b.y;\n const bz = b.z;\n out.set(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);\n return out;\n }\n\n /**\n * Writes the interpolation of `a` and `b` into `out`.\n *\n * @param a - The vector written at `t === 0`.\n * @param b - The vector written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static lerpToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, t: number, out: TOut): TOut {\n out.set(lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t));\n return out;\n }\n\n /**\n * Writes the component-wise minimum of two vectors into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static minToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));\n return out;\n }\n\n /**\n * Writes the component-wise maximum of two vectors into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static maxToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));\n return out;\n }\n\n /**\n * Transforms a **position** by a matrix into `out`: the matrix's translation is applied and the\n * result is divided by w, so a projection matrix gives clip-space coordinates.\n *\n * @param v - The position to transform, in metres.\n * @param m - The transformation, column-major.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n *\n * @example\n * ```ts\n * Vec3.transformCoordinatesToRef(localPoint, node.worldMatrix, worldPoint);\n * ```\n */\n static transformCoordinatesToRef<TOut extends MutableVec3>(v: Vec3Like, m: Mat4Like, out: TOut): TOut {\n return Mat4.transformPointToRef(m, v, out);\n }\n\n /**\n * Transforms a **direction** by a matrix into `out`, ignoring the matrix's translation.\n *\n * @param v - The direction to transform.\n * @param m - The transformation, column-major.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static transformNormalToRef<TOut extends MutableVec3>(v: Vec3Like, m: Mat4Like, out: TOut): TOut {\n return Mat4.transformDirectionToRef(m, v, out);\n }\n\n /**\n * The dot product of two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The dot product.\n */\n static dot(a: Vec3Like, b: Vec3Like): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n }\n\n /**\n * The length of a vector, in metres.\n *\n * @param v - The vector to measure.\n * @returns The length.\n */\n static length(v: Vec3Like): number {\n return Math.hypot(v.x, v.y, v.z);\n }\n\n /**\n * The squared length of a vector.\n *\n * @param v - The vector to measure.\n * @returns The squared length.\n */\n static lengthSquared(v: Vec3Like): number {\n return v.x * v.x + v.y * v.y + v.z * v.z;\n }\n\n /**\n * The distance between two positions, in metres.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The distance.\n */\n static distance(a: Vec3Like, b: Vec3Like): number {\n return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);\n }\n\n /**\n * The squared distance between two positions. Compare squared distances to avoid a square root.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The squared distance.\n */\n static distanceSquared(a: Vec3Like, b: Vec3Like): number {\n const dx = a.x - b.x;\n const dy = a.y - b.y;\n const dz = a.z - b.z;\n return dx * dx + dy * dy + dz * dz;\n }\n\n /**\n * Compares two vectors component by component, with a tolerance.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: Vec3Like, b: Vec3Like, epsilon: number = EPSILON): boolean {\n return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon;\n }\n}\n\n/**\n * The frozen zero vector, `(0, 0, 0)`. Read-only: pass it anywhere a {@link Vec3Like} is wanted, and\n * call {@link Vec3.zero} when you need a vector you can write to.\n *\n * @public\n */\nexport const VEC3_ZERO: Vec3Like = Object.freeze({ x: 0, y: 0, z: 0 });\n\n/**\n * The frozen vector whose components are all one, `(1, 1, 1)` — the identity scale.\n *\n * @public\n */\nexport const VEC3_ONE: Vec3Like = Object.freeze({ x: 1, y: 1, z: 1 });\n\n/**\n * The frozen world up direction, `(0, 1, 0)`.\n *\n * @public\n */\nexport const VEC3_UP: Vec3Like = Object.freeze({ x: 0, y: 1, z: 0 });\n\n/**\n * The frozen world down direction, `(0, -1, 0)`.\n *\n * @public\n */\nexport const VEC3_DOWN: Vec3Like = Object.freeze({ x: 0, y: -1, z: 0 });\n\n/**\n * The frozen world right direction, `(1, 0, 0)`.\n *\n * @public\n */\nexport const VEC3_RIGHT: Vec3Like = Object.freeze({ x: 1, y: 0, z: 0 });\n\n/**\n * The frozen world left direction, `(-1, 0, 0)`.\n *\n * @public\n */\nexport const VEC3_LEFT: Vec3Like = Object.freeze({ x: -1, y: 0, z: 0 });\n\n/**\n * The frozen world forward direction, `(0, 0, 1)`. ignifx is left-handed, so forward is +Z\n * (ADR-0011).\n *\n * @public\n */\nexport const VEC3_FORWARD: Vec3Like = Object.freeze({ x: 0, y: 0, z: 1 });\n\n/**\n * The frozen world backward direction, `(0, 0, -1)`.\n *\n * @public\n */\nexport const VEC3_BACKWARD: Vec3Like = Object.freeze({ x: 0, y: 0, z: -1 });\n","import { basisToQuatToRef, Mat4 } from \"./mat4.js\";\nimport { clamp, degToRad, EPSILON, radToDeg } from \"./math-utils.js\";\nimport { VEC3_UP } from \"./vec3.js\";\nimport type { Mat4Like, MutableQuat, MutableVec3, QuatLike, Vec3Like } from \"./types.js\";\n\n/**\n * A rotation, stored as a unit quaternion. Quaternions are how ignifx stores every rotation:\n * they interpolate smoothly, never gimbal-lock, and compose without matrix round-trips. Euler\n * angles exist only at the edges of the API, always in **degrees** (ADR-0011, coding standards\n * section 5.1).\n *\n * Conventions, all verified against Babylon Lite 1.27.0's implementation so a `Quat` and a Lite\n * quaternion mean the same rotation:\n *\n * - Euler order is **intrinsic XYZ** (`lib/math/quat-euler.js`), the inverse of Lite's\n * `quatToEulerXYZ`.\n * - `a * b` is the Hamilton product: applied to a vector it performs `b` first, then `a`, matching\n * the matrix product `Ma * Mb`.\n * - The space is left-handed with Y up and +Z forward, so rotating `(1, 0, 0)` by 90 degrees about\n * +Y gives `(0, 0, -1)`, and {@link Quat.lookRotation} maps +Z onto `forward`.\n *\n * Instance methods mutate the receiver and return `this`; `ToRef` statics write into a final `out`\n * argument and allocate nothing; the remaining statics allocate and say so.\n *\n * @example\n * ```ts\n * // face the movement direction, then blend into it over time\n * const target = Quat.lookRotation(velocity);\n * Quat.slerpToRef(transform.localRotation, target, 0.2, transform.localRotation);\n * ```\n *\n * @public\n */\nexport class Quat {\n /** The imaginary X component. */\n x: number;\n /** The imaginary Y component. */\n y: number;\n /** The imaginary Z component. */\n z: number;\n /** The real (scalar) component. */\n w: number;\n\n /**\n * Creates a quaternion. The defaults are the identity rotation.\n *\n * @param x - The imaginary X component. Defaults to 0.\n * @param y - The imaginary Y component. Defaults to 0.\n * @param z - The imaginary Z component. Defaults to 0.\n * @param w - The real component. Defaults to 1.\n */\n constructor(x: number = 0, y: number = 0, z: number = 0, w: number = 1) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n\n /**\n * Assigns every component at once.\n *\n * @param x - The new imaginary X component.\n * @param y - The new imaginary Y component.\n * @param z - The new imaginary Z component.\n * @param w - The new real component.\n * @returns This quaternion.\n */\n set(x: number, y: number, z: number, w: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n }\n\n /**\n * Copies every component from another quaternion.\n *\n * @param q - The quaternion to read.\n * @returns This quaternion.\n */\n copyFrom(q: QuatLike): this {\n this.x = q.x;\n this.y = q.y;\n this.z = q.z;\n this.w = q.w;\n return this;\n }\n\n /**\n * Copies this quaternion into a new one.\n *\n * @returns A new quaternion. **Allocates.**\n */\n clone(): Quat {\n return new Quat(this.x, this.y, this.z, this.w);\n }\n\n /**\n * Resets this quaternion to the identity rotation.\n *\n * @returns This quaternion.\n */\n identity(): this {\n return this.set(0, 0, 0, 1);\n }\n\n /**\n * Scales this quaternion to unit length. Compositions drift over time, so normalize rotations you\n * keep integrating. A zero-length quaternion becomes the identity rather than `NaN`.\n *\n * @returns This quaternion.\n */\n normalize(): this {\n return Quat.normalizeToRef(this, this);\n }\n\n /**\n * Conjugates this quaternion, negating its imaginary part. For a unit quaternion this is the\n * inverse rotation.\n *\n * @returns This quaternion.\n */\n conjugate(): this {\n this.x = -this.x;\n this.y = -this.y;\n this.z = -this.z;\n return this;\n }\n\n /**\n * Inverts this rotation. Unlike {@link Quat.conjugate} this also divides by the squared length, so\n * it is correct for quaternions that have drifted from unit length.\n *\n * @returns This quaternion.\n */\n invert(): this {\n return Quat.invertToRef(this, this);\n }\n\n /**\n * Post-multiplies this rotation by another (`this = this * q`): applied to a vector, `q` happens\n * first.\n *\n * @param q - The right-hand rotation.\n * @returns This quaternion.\n */\n multiply(q: QuatLike): this {\n return Quat.multiplyToRef(this, q, this);\n }\n\n /**\n * The dot product of this quaternion with another. Its magnitude is the cosine of half the angle\n * between the two rotations.\n *\n * @param q - The other rotation.\n * @returns The dot product.\n */\n dot(q: QuatLike): number {\n return this.x * q.x + this.y * q.y + this.z * q.z + this.w * q.w;\n }\n\n /**\n * The length of this quaternion; 1 for a well-formed rotation.\n *\n * @returns The length.\n */\n length(): number {\n return Math.hypot(this.x, this.y, this.z, this.w);\n }\n\n /**\n * The squared length of this quaternion.\n *\n * @returns The squared length.\n */\n lengthSquared(): number {\n return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;\n }\n\n /**\n * Compares this quaternion with another, component by component, with a tolerance. Note that `q`\n * and `-q` are the same rotation but are **not** equal by this test.\n *\n * @param q - The quaternion to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(q: QuatLike, epsilon: number = EPSILON): boolean {\n return Quat.equalsWithEpsilon(this, q, epsilon);\n }\n\n /**\n * Writes this quaternion into a `Float32Array`, for GPU upload. The output comes first to mirror\n * Babylon Lite's `ObservableQuat.toArray`.\n *\n * @param out - The array to write into.\n * @param offset - The index of the X component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.x;\n out[offset + 1] = this.y;\n out[offset + 2] = this.z;\n out[offset + 3] = this.w;\n return out;\n }\n\n /**\n * The identity rotation.\n *\n * @returns A new `(0, 0, 0, 1)`. **Allocates**; see {@link QUAT_IDENTITY}.\n */\n static identity(): Quat {\n return new Quat(0, 0, 0, 1);\n }\n\n /**\n * Copies any quaternion-shaped value into a `Quat`.\n *\n * @param q - The quaternion to copy.\n * @returns A new quaternion. **Allocates.**\n */\n static from(q: QuatLike): Quat {\n return new Quat(q.x, q.y, q.z, q.w);\n }\n\n /**\n * Builds a rotation from Euler angles in degrees, in intrinsic XYZ order.\n *\n * @param xDegrees - Rotation about X (pitch), in degrees.\n * @param yDegrees - Rotation about Y (yaw), in degrees.\n * @param zDegrees - Rotation about Z (roll), in degrees.\n * @returns A new quaternion. **Allocates.**\n *\n * @example\n * ```ts\n * transform.localRotation.copyFrom(Quat.fromEulerDegrees(0, 90, 0)); // face +X\n * ```\n */\n static fromEulerDegrees(xDegrees: number, yDegrees: number, zDegrees: number): Quat {\n return Quat.fromEulerDegreesToRef(xDegrees, yDegrees, zDegrees, new Quat());\n }\n\n /**\n * Writes a rotation built from Euler degrees into `out`.\n *\n * @param xDegrees - Rotation about X (pitch), in degrees.\n * @param yDegrees - Rotation about Y (yaw), in degrees.\n * @param zDegrees - Rotation about Z (roll), in degrees.\n * @param out - The quaternion to write.\n * @returns `out`.\n */\n static fromEulerDegreesToRef<TOut extends MutableQuat>(\n xDegrees: number,\n yDegrees: number,\n zDegrees: number,\n out: TOut,\n ): TOut {\n return Quat.fromEulerRadiansToRef(degToRad(xDegrees), degToRad(yDegrees), degToRad(zDegrees), out);\n }\n\n /**\n * Builds a rotation from Euler angles in radians, in intrinsic XYZ order.\n *\n * @param xRadians - Rotation about X, in radians.\n * @param yRadians - Rotation about Y, in radians.\n * @param zRadians - Rotation about Z, in radians.\n * @returns A new quaternion. **Allocates.**\n */\n static fromEulerRadians(xRadians: number, yRadians: number, zRadians: number): Quat {\n return Quat.fromEulerRadiansToRef(xRadians, yRadians, zRadians, new Quat());\n }\n\n /**\n * Writes a rotation built from Euler radians into `out`. This is Babylon Lite's `eulerToQuat`\n * (`lib/math/quat-euler.js`) element for element, so a rotation built here means the same thing\n * to Lite's node hierarchy.\n *\n * @param xRadians - Rotation about X, in radians.\n * @param yRadians - Rotation about Y, in radians.\n * @param zRadians - Rotation about Z, in radians.\n * @param out - The quaternion to write.\n * @returns `out`.\n */\n static fromEulerRadiansToRef<TOut extends MutableQuat>(\n xRadians: number,\n yRadians: number,\n zRadians: number,\n out: TOut,\n ): TOut {\n const cx = Math.cos(xRadians * 0.5);\n const sx = Math.sin(xRadians * 0.5);\n const cy = Math.cos(yRadians * 0.5);\n const sy = Math.sin(yRadians * 0.5);\n const cz = Math.cos(zRadians * 0.5);\n const sz = Math.sin(zRadians * 0.5);\n out.set(\n sx * cy * cz + cx * sy * sz,\n cx * sy * cz - sx * cy * sz,\n cx * cy * sz + sx * sy * cz,\n cx * cy * cz - sx * sy * sz,\n );\n return out;\n }\n\n /**\n * Writes a rotation's Euler angles in degrees into `out`, in intrinsic XYZ order — the inverse of\n * {@link Quat.fromEulerDegreesToRef}.\n *\n * @param q - The rotation to convert; assumed to be a unit quaternion.\n * @param out - The vector to write; `x` is pitch, `y` is yaw, `z` is roll, all in degrees.\n * @returns `out`.\n */\n static toEulerDegreesToRef<TOut extends MutableVec3>(q: QuatLike, out: TOut): TOut {\n Quat.toEulerRadiansToRef(q, out);\n out.set(radToDeg(out.x), radToDeg(out.y), radToDeg(out.z));\n return out;\n }\n\n /**\n * Writes a rotation's Euler angles in radians into `out`, in intrinsic XYZ order. This is Babylon\n * Lite's `quatToEulerXYZ` (`lib/math/quat-euler.js`) line for line, including its behaviour near\n * the poles: at a Y rotation of plus or minus 90 degrees the X and Z angles are not separable and\n * the result is one of the infinitely many valid answers.\n *\n * @param q - The rotation to convert; assumed to be a unit quaternion.\n * @param out - The vector to write, in radians.\n * @returns `out`.\n */\n static toEulerRadiansToRef<TOut extends MutableVec3>(q: QuatLike, out: TOut): TOut {\n const qx = q.x;\n const qy = q.y;\n const qz = q.z;\n const qw = q.w;\n const sinY = 2 * (qx * qz + qw * qy);\n const ry = Math.asin(clamp(sinY, -1, 1));\n const rx = Math.atan2(-(2 * (qy * qz - qw * qx)), 1 - 2 * (qx * qx + qy * qy));\n const rz = Math.atan2(-(2 * (qx * qy - qw * qz)), 1 - 2 * (qy * qy + qz * qz));\n out.set(rx, ry, rz);\n return out;\n }\n\n /**\n * Builds a rotation of `degrees` about an axis.\n *\n * @param axis - The axis to turn about; normalized internally.\n * @param degrees - The angle, in degrees.\n * @returns A new quaternion. **Allocates.**\n */\n static fromAxisAngle(axis: Vec3Like, degrees: number): Quat {\n return Quat.fromAxisAngleToRef(axis, degrees, new Quat());\n }\n\n /**\n * Writes a rotation of `degrees` about an axis into `out`.\n *\n * @param axis - The axis to turn about; normalized internally. A zero-length axis writes the\n * identity rotation.\n * @param degrees - The angle, in degrees.\n * @param out - The quaternion to write.\n * @returns `out`.\n */\n static fromAxisAngleToRef<TOut extends MutableQuat>(axis: Vec3Like, degrees: number, out: TOut): TOut {\n const length = Math.hypot(axis.x, axis.y, axis.z);\n if (length === 0) {\n out.set(0, 0, 0, 1);\n return out;\n }\n const half = degToRad(degrees) * 0.5;\n const s = Math.sin(half) / length;\n out.set(axis.x * s, axis.y * s, axis.z * s, Math.cos(half));\n return out;\n }\n\n /**\n * Composes two rotations.\n *\n * @param a - The rotation applied second.\n * @param b - The rotation applied first.\n * @returns A new quaternion holding `a * b`. **Allocates.**\n */\n static multiply(a: QuatLike, b: QuatLike): Quat {\n return Quat.multiplyToRef(a, b, new Quat());\n }\n\n /**\n * Writes the Hamilton product `a * b` into `out`. Applied to a vector, `b` is performed first.\n *\n * @param a - The left-hand rotation.\n * @param b - The right-hand rotation.\n * @param out - The quaternion to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends MutableQuat>(a: QuatLike, b: QuatLike, out: TOut): TOut {\n const ax = a.x;\n const ay = a.y;\n const az = a.z;\n const aw = a.w;\n const bx = b.x;\n const by = b.y;\n const bz = b.z;\n const bw = b.w;\n out.set(\n aw * bx + ax * bw + ay * bz - az * by,\n aw * by - ax * bz + ay * bw + az * bx,\n aw * bz + ax * by - ay * bx + az * bw,\n aw * bw - ax * bx - ay * by - az * bz,\n );\n return out;\n }\n\n /**\n * Writes the conjugate of `q` into `out`.\n *\n * @param q - The rotation to conjugate.\n * @param out - The quaternion to write; may alias `q`.\n * @returns `out`.\n */\n static conjugateToRef<TOut extends MutableQuat>(q: QuatLike, out: TOut): TOut {\n out.set(-q.x, -q.y, -q.z, q.w);\n return out;\n }\n\n /**\n * Writes the inverse of `q` into `out`, dividing the conjugate by the squared length.\n *\n * @param q - The rotation to invert.\n * @param out - The quaternion to write; may alias `q`. A zero-length input writes the identity.\n * @returns `out`.\n */\n static invertToRef<TOut extends MutableQuat>(q: QuatLike, out: TOut): TOut {\n const lengthSquared = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;\n if (lengthSquared === 0) {\n out.set(0, 0, 0, 1);\n return out;\n }\n const inv = 1 / lengthSquared;\n out.set(-q.x * inv, -q.y * inv, -q.z * inv, q.w * inv);\n return out;\n }\n\n /**\n * Writes a unit-length copy of `q` into `out`.\n *\n * @param q - The rotation to normalize.\n * @param out - The quaternion to write; may alias `q`. A zero-length input writes the identity.\n * @returns `out`.\n */\n static normalizeToRef<TOut extends MutableQuat>(q: QuatLike, out: TOut): TOut {\n const length = Math.hypot(q.x, q.y, q.z, q.w);\n if (length === 0) {\n out.set(0, 0, 0, 1);\n return out;\n }\n const inv = 1 / length;\n out.set(q.x * inv, q.y * inv, q.z * inv, q.w * inv);\n return out;\n }\n\n /**\n * Interpolates between two rotations along the shortest arc, at a constant angular rate.\n *\n * @param a - The rotation returned at `t === 0`.\n * @param b - The rotation returned at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns A new quaternion. **Allocates.**\n */\n static slerp(a: QuatLike, b: QuatLike, t: number): Quat {\n return Quat.slerpToRef(a, b, t, new Quat());\n }\n\n /**\n * Writes the spherical interpolation of `a` and `b` into `out`, taking the shortest arc: when the\n * two rotations point away from each other one is negated first, which is the same rotation. Very\n * close rotations fall back to a normalized linear blend, where slerp is numerically unstable.\n *\n * @param a - The rotation written at `t === 0`.\n * @param b - The rotation written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The quaternion to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static slerpToRef<TOut extends MutableQuat>(a: QuatLike, b: QuatLike, t: number, out: TOut): TOut {\n const ax = a.x;\n const ay = a.y;\n const az = a.z;\n const aw = a.w;\n let bx = b.x;\n let by = b.y;\n let bz = b.z;\n let bw = b.w;\n let cosine = ax * bx + ay * by + az * bz + aw * bw;\n if (cosine < 0) {\n cosine = -cosine;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n }\n let scaleA = 1 - t;\n let scaleB = t;\n if (cosine < 1 - 1e-6) {\n const angle = Math.acos(cosine);\n const invSin = 1 / Math.sin(angle);\n scaleA = Math.sin(scaleA * angle) * invSin;\n scaleB = Math.sin(scaleB * angle) * invSin;\n }\n out.set(ax * scaleA + bx * scaleB, ay * scaleA + by * scaleB, az * scaleA + bz * scaleB, aw * scaleA + bw * scaleB);\n return Quat.normalizeToRef(out, out);\n }\n\n /**\n * Rotates a vector by a quaternion, writing the result into `out`. This is the allocation-free\n * way to turn a local direction into a world direction.\n *\n * @param q - The rotation; assumed to be a unit quaternion.\n * @param v - The vector to rotate.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n *\n * @example\n * ```ts\n * // world-space forward of an entity\n * Quat.rotateVectorToRef(transform.localRotation, VEC3_FORWARD, forward);\n * ```\n */\n static rotateVectorToRef<TOut extends MutableVec3>(q: QuatLike, v: Vec3Like, out: TOut): TOut {\n const qx = q.x;\n const qy = q.y;\n const qz = q.z;\n const qw = q.w;\n const vx = v.x;\n const vy = v.y;\n const vz = v.z;\n const tx = 2 * (qy * vz - qz * vy);\n const ty = 2 * (qz * vx - qx * vz);\n const tz = 2 * (qx * vy - qy * vx);\n out.set(vx + qw * tx + qy * tz - qz * ty, vy + qw * ty + qz * tx - qx * tz, vz + qw * tz + qx * ty - qy * tx);\n return out;\n }\n\n /**\n * Builds the rotation that points local +Z along `forward` and local +Y as close to `up` as it\n * can (left-handed, ADR-0011).\n *\n * @param forward - The direction to face; normalized internally.\n * @param up - The reference up direction. Defaults to world up, `(0, 1, 0)`.\n * @returns A new quaternion. **Allocates.**\n */\n static lookRotation(forward: Vec3Like, up: Vec3Like = VEC3_UP): Quat {\n return Quat.lookRotationToRef(forward, up, new Quat());\n }\n\n /**\n * Writes the rotation that points local +Z along `forward` into `out`. The basis is built the way\n * Babylon Lite builds it in `quatFromLookDirectionRH` (`lib/math/quat-from-look-direction-rh.js`):\n * `right = up x forward`, `up' = forward x right`, columns `(right, up', forward)` — which in\n * ignifx's left-handed space is exactly the Unity-style look rotation, whatever the Lite function\n * is named.\n *\n * @param forward - The direction to face; normalized internally.\n * @param up - The reference up direction; normalized internally.\n * @param out - The quaternion to write. Degenerate input (a zero-length `forward`, or an `up`\n * parallel to it) writes the identity rotation, where Lite would produce a meaningless basis.\n * @returns `out`.\n */\n static lookRotationToRef<TOut extends MutableQuat>(forward: Vec3Like, up: Vec3Like, out: TOut): TOut {\n const forwardLength = Math.hypot(forward.x, forward.y, forward.z);\n if (forwardLength === 0) {\n out.set(0, 0, 0, 1);\n return out;\n }\n const invForward = 1 / forwardLength;\n const fx = forward.x * invForward;\n const fy = forward.y * invForward;\n const fz = forward.z * invForward;\n let rx = up.y * fz - up.z * fy;\n let ry = up.z * fx - up.x * fz;\n let rz = up.x * fy - up.y * fx;\n const rightLength = Math.hypot(rx, ry, rz);\n if (rightLength < 1e-10) {\n out.set(0, 0, 0, 1);\n return out;\n }\n const invRight = 1 / rightLength;\n rx *= invRight;\n ry *= invRight;\n rz *= invRight;\n const ux = fy * rz - fz * ry;\n const uy = fz * rx - fx * rz;\n const uz = fx * ry - fy * rx;\n basisToQuatToRef(rx, ux, fx, ry, uy, fy, rz, uz, fz, out);\n return Quat.normalizeToRef(out, out);\n }\n\n /**\n * Reads the rotation out of a transformation matrix.\n *\n * @param m - The matrix to read; scale is divided out first.\n * @returns A new quaternion. **Allocates.**\n */\n static fromRotationMatrix(m: Mat4Like): Quat {\n return Quat.fromRotationMatrixToRef(m, new Quat());\n }\n\n /**\n * Writes the rotation of a transformation matrix into `out`, dividing out the scale exactly as\n * {@link Mat4.decomposeToRef} does.\n *\n * @param m - The matrix to read.\n * @param out - The quaternion to write. Left untouched when a basis column has zero length.\n * @returns `out`.\n */\n static fromRotationMatrixToRef<TOut extends MutableQuat>(m: Mat4Like, out: TOut): TOut {\n return Mat4.getRotationToRef(m, out);\n }\n\n /**\n * The dot product of two rotations.\n *\n * @param a - The first rotation.\n * @param b - The second rotation.\n * @returns The dot product.\n */\n static dot(a: QuatLike, b: QuatLike): number {\n return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;\n }\n\n /**\n * The angle between two rotations, in degrees, along the shortest arc.\n *\n * @param a - The first rotation; assumed to be a unit quaternion.\n * @param b - The second rotation; assumed to be a unit quaternion.\n * @returns The angle in `[0, 180]` degrees.\n */\n static angleDegrees(a: QuatLike, b: QuatLike): number {\n const cosine = Math.abs(clamp(Quat.dot(a, b), -1, 1));\n return radToDeg(2 * Math.acos(cosine));\n }\n\n /**\n * Compares two quaternions component by component, with a tolerance. Note that `q` and `-q` are\n * the same rotation but are **not** equal by this test; compare with {@link Quat.angleDegrees}\n * when that matters.\n *\n * @param a - The first quaternion.\n * @param b - The second quaternion.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: QuatLike, b: QuatLike, epsilon: number = EPSILON): boolean {\n return (\n Math.abs(a.x - b.x) <= epsilon &&\n Math.abs(a.y - b.y) <= epsilon &&\n Math.abs(a.z - b.z) <= epsilon &&\n Math.abs(a.w - b.w) <= epsilon\n );\n }\n}\n\n/**\n * The frozen identity rotation, `(0, 0, 0, 1)`. Read-only: pass it anywhere a {@link QuatLike} is\n * wanted, and call `Quat.identity()` when you need one you can write to.\n *\n * @public\n */\nexport const QUAT_IDENTITY: QuatLike = Object.freeze({ x: 0, y: 0, z: 0, w: 1 });\n","import { EPSILON, lerp } from \"./math-utils.js\";\nimport type { MutableVec2, Vec2Like } from \"./types.js\";\n\n/**\n * A 2-component vector: a position or direction in the 2D toolkit's world space (Y up, X right,\n * metres — ADR-0011), a UV coordinate, or a 2D scale.\n *\n * Instance methods mutate the receiver and return `this`; `ToRef` statics write into a final `out`\n * argument and allocate nothing; the remaining statics allocate and say so.\n *\n * @example\n * ```ts\n * const velocity = new Vec2(1, 0);\n * velocity.scale(speed);\n * Vec2.addToRef(position, velocity, position);\n * ```\n *\n * @public\n */\nexport class Vec2 {\n /** The X component; positive is right. */\n x: number;\n /** The Y component; positive is up. */\n y: number;\n\n /**\n * Creates a vector.\n *\n * @param x - The X component. Defaults to 0.\n * @param y - The Y component. Defaults to 0.\n */\n constructor(x: number = 0, y: number = 0) {\n this.x = x;\n this.y = y;\n }\n\n /**\n * Assigns every component at once.\n *\n * @param x - The new X component.\n * @param y - The new Y component.\n * @returns This vector.\n */\n set(x: number, y: number): this {\n this.x = x;\n this.y = y;\n return this;\n }\n\n /**\n * Copies every component from another vector.\n *\n * @param v - The vector to read.\n * @returns This vector.\n */\n copyFrom(v: Vec2Like): this {\n this.x = v.x;\n this.y = v.y;\n return this;\n }\n\n /**\n * Copies this vector into a new one.\n *\n * @returns A new vector. **Allocates.**\n */\n clone(): Vec2 {\n return new Vec2(this.x, this.y);\n }\n\n /**\n * Adds another vector to this one.\n *\n * @param v - The vector to add.\n * @returns This vector.\n */\n add(v: Vec2Like): this {\n this.x += v.x;\n this.y += v.y;\n return this;\n }\n\n /**\n * Adds a scaled vector to this one, without a temporary.\n *\n * @param v - The vector to add.\n * @param scale - The factor to multiply `v` by first.\n * @returns This vector.\n */\n addScaled(v: Vec2Like, scale: number): this {\n this.x += v.x * scale;\n this.y += v.y * scale;\n return this;\n }\n\n /**\n * Subtracts another vector from this one.\n *\n * @param v - The vector to subtract.\n * @returns This vector.\n */\n subtract(v: Vec2Like): this {\n this.x -= v.x;\n this.y -= v.y;\n return this;\n }\n\n /**\n * Multiplies this vector by another component by component.\n *\n * @param v - The vector to multiply by.\n * @returns This vector.\n */\n multiply(v: Vec2Like): this {\n this.x *= v.x;\n this.y *= v.y;\n return this;\n }\n\n /**\n * Multiplies every component by a number.\n *\n * @param scale - The factor.\n * @returns This vector.\n */\n scale(scale: number): this {\n this.x *= scale;\n this.y *= scale;\n return this;\n }\n\n /**\n * Flips this vector to point the other way.\n *\n * @returns This vector.\n */\n negate(): this {\n this.x = -this.x;\n this.y = -this.y;\n return this;\n }\n\n /**\n * Scales this vector to unit length; a zero-length vector is left at zero rather than becoming\n * `NaN`.\n *\n * @returns This vector.\n */\n normalize(): this {\n const length = Math.hypot(this.x, this.y);\n if (length === 0) {\n return this;\n }\n return this.scale(1 / length);\n }\n\n /**\n * Moves this vector towards a target by an interpolant.\n *\n * @param target - The vector reached at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns This vector.\n */\n lerp(target: Vec2Like, t: number): this {\n return Vec2.lerpToRef(this, target, t, this);\n }\n\n /**\n * The dot product of this vector with another.\n *\n * @param v - The other vector.\n * @returns The dot product.\n */\n dot(v: Vec2Like): number {\n return this.x * v.x + this.y * v.y;\n }\n\n /**\n * The 2D cross product — the Z component of the 3D cross product. Its sign says which side of\n * this vector the other one falls on.\n *\n * @param v - The other vector.\n * @returns The scalar cross product.\n */\n cross(v: Vec2Like): number {\n return this.x * v.y - this.y * v.x;\n }\n\n /**\n * The length of this vector, in metres.\n *\n * @returns The length.\n */\n length(): number {\n return Math.hypot(this.x, this.y);\n }\n\n /**\n * The squared length of this vector.\n *\n * @returns The squared length.\n */\n lengthSquared(): number {\n return this.x * this.x + this.y * this.y;\n }\n\n /**\n * The distance from this vector to another, in metres.\n *\n * @param v - The other position.\n * @returns The distance.\n */\n distance(v: Vec2Like): number {\n return Math.hypot(this.x - v.x, this.y - v.y);\n }\n\n /**\n * The squared distance from this vector to another.\n *\n * @param v - The other position.\n * @returns The squared distance.\n */\n distanceSquared(v: Vec2Like): number {\n const dx = this.x - v.x;\n const dy = this.y - v.y;\n return dx * dx + dy * dy;\n }\n\n /**\n * Compares this vector with another, component by component, with a tolerance.\n *\n * @param v - The vector to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(v: Vec2Like, epsilon: number = EPSILON): boolean {\n return Vec2.equalsWithEpsilon(this, v, epsilon);\n }\n\n /**\n * Writes this vector into a `Float32Array`, for GPU upload. The output comes first to mirror\n * Babylon Lite's `toArray` helpers.\n *\n * @param out - The array to write into.\n * @param offset - The index of the X component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.x;\n out[offset + 1] = this.y;\n return out;\n }\n\n /**\n * The zero vector.\n *\n * @returns A new `(0, 0)`. **Allocates.**\n */\n static zero(): Vec2 {\n return new Vec2(0, 0);\n }\n\n /**\n * The vector whose components are both one.\n *\n * @returns A new `(1, 1)`. **Allocates.**\n */\n static one(): Vec2 {\n return new Vec2(1, 1);\n }\n\n /**\n * Copies any vector-shaped value into a `Vec2`.\n *\n * @param v - The vector to copy.\n * @returns A new vector. **Allocates.**\n */\n static from(v: Vec2Like): Vec2 {\n return new Vec2(v.x, v.y);\n }\n\n /**\n * Adds two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns A new vector. **Allocates.**\n */\n static add(a: Vec2Like, b: Vec2Like): Vec2 {\n return Vec2.addToRef(a, b, new Vec2());\n }\n\n /**\n * Subtracts one vector from another.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @returns A new vector holding `a - b`. **Allocates.**\n */\n static subtract(a: Vec2Like, b: Vec2Like): Vec2 {\n return Vec2.subtractToRef(a, b, new Vec2());\n }\n\n /**\n * Multiplies a vector by a number.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @returns A new vector. **Allocates.**\n */\n static scale(v: Vec2Like, scale: number): Vec2 {\n return Vec2.scaleToRef(v, scale, new Vec2());\n }\n\n /**\n * A unit-length copy of a vector.\n *\n * @param v - The vector to normalize.\n * @returns A new vector. **Allocates.**\n */\n static normalize(v: Vec2Like): Vec2 {\n return Vec2.normalizeToRef(v, new Vec2());\n }\n\n /**\n * Linearly interpolates between two vectors.\n *\n * @param a - The vector returned at `t === 0`.\n * @param b - The vector returned at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns A new vector. **Allocates.**\n */\n static lerp(a: Vec2Like, b: Vec2Like, t: number): Vec2 {\n return Vec2.lerpToRef(a, b, t, new Vec2());\n }\n\n /**\n * Writes `a + b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static addToRef<TOut extends MutableVec2>(a: Vec2Like, b: Vec2Like, out: TOut): TOut {\n out.set(a.x + b.x, a.y + b.y);\n return out;\n }\n\n /**\n * Writes `a - b` into `out`.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static subtractToRef<TOut extends MutableVec2>(a: Vec2Like, b: Vec2Like, out: TOut): TOut {\n out.set(a.x - b.x, a.y - b.y);\n return out;\n }\n\n /**\n * Writes the component-wise product `a * b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends MutableVec2>(a: Vec2Like, b: Vec2Like, out: TOut): TOut {\n out.set(a.x * b.x, a.y * b.y);\n return out;\n }\n\n /**\n * Writes `v * scale` into `out`.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static scaleToRef<TOut extends MutableVec2>(v: Vec2Like, scale: number, out: TOut): TOut {\n out.set(v.x * scale, v.y * scale);\n return out;\n }\n\n /**\n * Writes `-v` into `out`.\n *\n * @param v - The vector to flip.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static negateToRef<TOut extends MutableVec2>(v: Vec2Like, out: TOut): TOut {\n out.set(-v.x, -v.y);\n return out;\n }\n\n /**\n * Writes a unit-length copy of `v` into `out`; a zero-length input is written as zero.\n *\n * @param v - The vector to normalize.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static normalizeToRef<TOut extends MutableVec2>(v: Vec2Like, out: TOut): TOut {\n const length = Math.hypot(v.x, v.y);\n if (length === 0) {\n out.set(0, 0);\n return out;\n }\n const inv = 1 / length;\n out.set(v.x * inv, v.y * inv);\n return out;\n }\n\n /**\n * Writes the interpolation of `a` and `b` into `out`.\n *\n * @param a - The vector written at `t === 0`.\n * @param b - The vector written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static lerpToRef<TOut extends MutableVec2>(a: Vec2Like, b: Vec2Like, t: number, out: TOut): TOut {\n out.set(lerp(a.x, b.x, t), lerp(a.y, b.y, t));\n return out;\n }\n\n /**\n * The dot product of two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The dot product.\n */\n static dot(a: Vec2Like, b: Vec2Like): number {\n return a.x * b.x + a.y * b.y;\n }\n\n /**\n * The 2D cross product of two vectors — the Z component of their 3D cross product.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @returns The scalar cross product.\n */\n static cross(a: Vec2Like, b: Vec2Like): number {\n return a.x * b.y - a.y * b.x;\n }\n\n /**\n * The length of a vector, in metres.\n *\n * @param v - The vector to measure.\n * @returns The length.\n */\n static length(v: Vec2Like): number {\n return Math.hypot(v.x, v.y);\n }\n\n /**\n * The squared length of a vector.\n *\n * @param v - The vector to measure.\n * @returns The squared length.\n */\n static lengthSquared(v: Vec2Like): number {\n return v.x * v.x + v.y * v.y;\n }\n\n /**\n * The distance between two positions, in metres.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The distance.\n */\n static distance(a: Vec2Like, b: Vec2Like): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n }\n\n /**\n * Compares two vectors component by component, with a tolerance.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: Vec2Like, b: Vec2Like, epsilon: number = EPSILON): boolean {\n return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon;\n }\n}\n\n/**\n * The frozen zero vector, `(0, 0)`.\n *\n * @public\n */\nexport const VEC2_ZERO: Vec2Like = Object.freeze({ x: 0, y: 0 });\n\n/**\n * The frozen vector whose components are both one, `(1, 1)` — the identity 2D scale.\n *\n * @public\n */\nexport const VEC2_ONE: Vec2Like = Object.freeze({ x: 1, y: 1 });\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { Transform } from \"./transform.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\n\n/**\n * The link between a `Transform` and the Babylon Lite node it is a view over. It lives behind a\n * module symbol for the same reason the component's engine state does: the entity creates the node\n * and hands it to a transform that has already been constructed, and the property must not be\n * nameable from game code (`transform.lite` is the documented way in).\n */\n\n/**\n * The key the Lite node hangs off a transform.\n *\n * @internal\n */\nexport const TRANSFORM_NODE: unique symbol = Symbol(\"ignifx.transform.node\");\n\n/**\n * Binds a freshly constructed transform to its entity's Lite node. Called once, by the entity\n * constructor, before the transform is attached.\n *\n * @param transform - The transform.\n * @param node - The entity's Lite node.\n *\n * @internal\n */\nexport function attachTransform(transform: Transform, node: LiteSceneNode): void {\n transform[TRANSFORM_NODE] = node;\n}\n\n/**\n * The Lite node a transform views.\n *\n * @param transform - The transform.\n * @returns The node.\n * @throws IgnifxError with code `IGX-0206` when the transform has not been bound to a node — only\n * possible for a `new Transform()` that the engine never attached.\n *\n * @internal\n */\nexport function transformNode(transform: Transform): LiteSceneNode {\n const node = transform[TRANSFORM_NODE];\n if (node === null) {\n throw new IgnifxError(CoreErrorCode.componentNotAttached, \"This Transform is not attached to an entity yet.\", {\n context: { component: \"Transform\" },\n hint: \"Transforms are created by the engine; use `world.createEntity()` and read `entity.transform`.\",\n });\n }\n return node;\n}\n\n/**\n * Builds the \"a transform cannot be removed or disabled\" error\n * (`docs/architecture/01-lifecycle-and-time.md` §6).\n *\n * @returns The error to throw.\n *\n * @internal\n */\nexport function transformIsNotRemovable(): IgnifxError {\n return new IgnifxError(CoreErrorCode.transformIsNotRemovable, \"Transform cannot be removed or disabled.\", {\n context: { component: \"Transform\" },\n hint: \"Every entity keeps exactly one transform for its whole life; deactivate the entity instead.\",\n });\n}\n","import { Component } from \"../component/component.js\";\nimport { localPosition, localRotation, localScale, parentNode, readWorldMatrix } from \"../lite/node.js\";\nimport { Mat4 } from \"../math/mat4.js\";\nimport { Quat } from \"../math/quat.js\";\nimport { Vec2 } from \"../math/vec2.js\";\nimport { Vec3 } from \"../math/vec3.js\";\nimport { TRANSFORM_NODE, transformIsNotRemovable, transformNode } from \"./transform-internals.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\nimport type { Mat4Like, MutableQuat, MutableVec3, QuatLike, Vec3Like } from \"../math/types.js\";\n\n/**\n * The view over an entity's Babylon Lite `SceneNode`\n * (`docs/architecture/02-scene-graph.md` §5). Every entity has exactly one; it cannot be removed\n * and cannot be disabled (`IGX-0205`).\n *\n * @remarks\n * There is no second copy of position, rotation, or scale anywhere in ignifx: physics, animation,\n * and scripts all read and write the same Lite node. `localPosition`, `localRotation`, and\n * `localScale` are the node's own live values, so `transform.localPosition.x += 1` writes straight\n * through with no copy and no dirty flag of ignifx's own.\n *\n * World-space getters (`position`, `rotation`, `eulerAngles`, `lossyScale`, `forward`, `right`,\n * `up`) allocate a fresh value; every one of them has a `ToRef` twin that writes into a caller-owned\n * object and allocates nothing, and hot code uses those (coding standards §7).\n *\n * @example\n * ```ts\n * class Follow extends Script implements ScriptCallbacks {\n * #target = new Vec3();\n * lateUpdate(dt: number): void {\n * this.player.transform.positionToRef(this.#target); // no allocation\n * this.transform.localPosition.copyFrom(this.#target); // straight into the Lite node\n * }\n * }\n * ```\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- the merged interface below declares one engine-owned property that the constructor always assigns.\nexport class Transform extends Component {\n /** The registration id of the one component every entity carries. */\n static typeId = \"ignifx/Transform\";\n\n /** An entity has exactly one transform. */\n static allowMultiple = false;\n\n /** Creates an unbound transform. The entity constructor binds it to a Lite node immediately. */\n constructor() {\n super();\n this[TRANSFORM_NODE] = null;\n }\n\n /** The world matrix, copied out of Lite lazily; created on first read. */\n #worldMatrix: Mat4 | null = null;\n\n /** The `worldMatrixVersion` the cached world matrix was copied at. */\n #worldMatrixVersion = -1;\n\n /** The local matrix, composed lazily; created on first read. */\n #localMatrix: Mat4 | null = null;\n\n /** The `worldMatrixVersion` the cached local matrix was composed at. */\n #localMatrixVersion = -1;\n\n /**\n * A transform is always enabled: it is the entity's only view of its own position, and the\n * engine, physics, and animation all write through it.\n *\n * @returns Always `true`.\n * @throws IgnifxError with code `IGX-0205` on any attempt to set it to `false`. Deactivate the\n * entity instead (`docs/architecture/01-lifecycle-and-time.md` §6).\n */\n override get enabled(): boolean {\n return super.enabled;\n }\n\n override set enabled(value: boolean) {\n if (!value) {\n throw transformIsNotRemovable();\n }\n super.enabled = value;\n }\n\n /**\n * A transform cannot be destroyed on its own.\n *\n * @throws IgnifxError with code `IGX-0205`. Destroy the entity instead.\n */\n override destroy(): void {\n throw transformIsNotRemovable();\n }\n\n /**\n * The Babylon Lite node this transform is a view over. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3); excluded from the stability guarantees of\n * `CONSTITUTION.md` Article IV.\n *\n * @returns The node.\n */\n get lite(): LiteSceneNode {\n return transformNode(this);\n }\n\n /**\n * The position relative to the parent, as a **live** view over the Lite node: writing to it moves\n * the entity and invalidates the subtree's world matrices.\n *\n * @returns The live local position. Never hold it past the entity's lifetime.\n */\n get localPosition(): MutableVec3 {\n return localPosition(transformNode(this));\n }\n\n /**\n * The rotation relative to the parent, as a live view over the Lite node.\n *\n * @returns The live local rotation.\n */\n get localRotation(): MutableQuat {\n return localRotation(transformNode(this));\n }\n\n /**\n * The scale relative to the parent, as a live view over the Lite node. Non-uniform scale is\n * supported; negative scale is allowed but shadows and physics shapes do not support it.\n *\n * @returns The live local scale.\n */\n get localScale(): MutableVec3 {\n return localScale(transformNode(this));\n }\n\n /**\n * The local rotation as intrinsic XYZ Euler angles in **degrees** (ADR-0011).\n *\n * @returns A freshly allocated vector. Use `Transform.localEulerAnglesToRef` in hot code.\n */\n get localEulerAngles(): Vec3 {\n return this.localEulerAnglesToRef(new Vec3());\n }\n\n set localEulerAngles(value: Vec3Like) {\n Quat.fromEulerDegreesToRef(value.x, value.y, value.z, localRotation(transformNode(this)));\n }\n\n /**\n * The world position.\n *\n * @returns A freshly allocated vector. Use `Transform.positionToRef` in hot code.\n */\n get position(): Vec3 {\n return this.positionToRef(new Vec3());\n }\n\n set position(value: Vec3Like) {\n const node = transformNode(this);\n const parent = parentNode(node);\n if (parent === null) {\n localPosition(node).set(value.x, value.y, value.z);\n return;\n }\n const scratch = getScratch();\n readWorldMatrix(parent, scratch.matrixA.elements);\n if (!Mat4.invertToRef(scratch.matrixA.elements, scratch.matrixB)) {\n // A singular parent matrix cannot be inverted, so no local value reproduces the world one.\n // Lite's own `setParent` takes the same escape hatch: keep the value as a local one.\n localPosition(node).set(value.x, value.y, value.z);\n return;\n }\n Mat4.transformPointToRef(scratch.matrixB.elements, value, localPosition(node));\n }\n\n /**\n * The world rotation.\n *\n * @returns A freshly allocated quaternion. Use `Transform.rotationToRef` in hot code.\n */\n get rotation(): Quat {\n return this.rotationToRef(new Quat());\n }\n\n set rotation(value: QuatLike) {\n const node = transformNode(this);\n const parent = parentNode(node);\n if (parent === null) {\n localRotation(node).set(value.x, value.y, value.z, value.w);\n return;\n }\n const scratch = getScratch();\n readWorldMatrix(parent, scratch.matrixA.elements);\n Mat4.getRotationToRef(scratch.matrixA.elements, scratch.setRotA);\n Quat.invertToRef(scratch.setRotA, scratch.setRotB);\n Quat.multiplyToRef(scratch.setRotB, value, localRotation(node));\n }\n\n /**\n * The world rotation as intrinsic XYZ Euler angles in degrees.\n *\n * @returns A freshly allocated vector. Use `Transform.eulerAnglesToRef` in hot code.\n */\n get eulerAngles(): Vec3 {\n return this.eulerAnglesToRef(new Vec3());\n }\n\n set eulerAngles(value: Vec3Like) {\n const scratch = getScratch();\n Quat.fromEulerDegreesToRef(value.x, value.y, value.z, scratch.quatC);\n this.rotation = scratch.quatC;\n }\n\n /**\n * The world scale, read as the lengths of the world matrix's basis columns. It is *lossy*: a\n * rotated parent with non-uniform scale has no exact per-axis world scale, so this is the closest\n * approximation, exactly as Unity's `lossyScale` is.\n *\n * @returns A freshly allocated vector. Use `Transform.lossyScaleToRef` in hot code.\n */\n get lossyScale(): Vec3 {\n return this.lossyScaleToRef(new Vec3());\n }\n\n /**\n * The world unit vector pointing along the entity's local +Z (ADR-0011: left-handed, Y up, +Z\n * forward).\n *\n * @returns A freshly allocated vector. Use `Transform.forwardToRef` in hot code.\n */\n get forward(): Vec3 {\n return this.forwardToRef(new Vec3());\n }\n\n /**\n * The world unit vector pointing along the entity's local +X.\n *\n * @returns A freshly allocated vector. Use `Transform.rightToRef` in hot code.\n */\n get right(): Vec3 {\n return this.rightToRef(new Vec3());\n }\n\n /**\n * The world unit vector pointing along the entity's local +Y.\n *\n * @returns A freshly allocated vector. Use `Transform.upToRef` in hot code.\n */\n get up(): Vec3 {\n return this.upToRef(new Vec3());\n }\n\n /**\n * The world matrix, copied out of Lite's cache the first time it is read after a change.\n *\n * @remarks\n * Lite documents its `Mat4` as opaque and recomputes it lazily up the parent chain, so the\n * adapter copies it element by element rather than handing out Lite's own object (ADR-0003\n * Validation). The returned view is this transform's own storage: it is read-only, its identity\n * is stable, and its contents change the next time the matrix is read after the entity moves.\n *\n * @returns The 16 column-major elements, translation in slots 12/13/14.\n */\n get worldMatrix(): Mat4Like {\n const node = transformNode(this);\n const version = node.worldMatrixVersion;\n let matrix = this.#worldMatrix;\n if (matrix === null) {\n matrix = new Mat4();\n this.#worldMatrix = matrix;\n }\n if (this.#worldMatrixVersion !== version) {\n readWorldMatrix(node, matrix.elements);\n this.#worldMatrixVersion = version;\n }\n return matrix.elements;\n }\n\n /**\n * The matrix that takes local space to the parent's space, composed from the local TRS as\n * `T * R * S`.\n *\n * @returns The 16 column-major elements. The same storage and staleness rules as\n * `Transform.worldMatrix`.\n */\n get localMatrix(): Mat4Like {\n const node = transformNode(this);\n const version = node.worldMatrixVersion;\n let matrix = this.#localMatrix;\n if (matrix === null) {\n matrix = new Mat4();\n this.#localMatrix = matrix;\n }\n if (this.#localMatrixVersion !== version) {\n Mat4.composeToRef(localPosition(node), localRotation(node), localScale(node), matrix);\n this.#localMatrixVersion = version;\n }\n return matrix.elements;\n }\n\n /**\n * A counter that increases whenever this transform's world matrix is invalidated, by its own TRS\n * or by any ancestor's. Snapshot it to detect movement without comparing matrices — how\n * extensions feed spatial acceleration structures (`docs/architecture/02-scene-graph.md` §9).\n *\n * @returns The current version.\n */\n get worldMatrixVersion(): number {\n return transformNode(this).worldMatrixVersion;\n }\n\n /**\n * The world position, in metres, in the plane 2D games use.\n *\n * @returns A freshly allocated 2D vector.\n */\n get position2D(): Vec2 {\n const scratch = getScratch();\n this.positionToRef(scratch.vecA);\n return new Vec2(scratch.vecA.x, scratch.vecA.y);\n }\n\n set position2D(value: Vec2) {\n const scratch = getScratch();\n this.positionToRef(scratch.vecA);\n scratch.vecA.set(value.x, value.y, scratch.vecA.z);\n this.position = scratch.vecA;\n }\n\n /**\n * The local position in the 2D plane; the Z depth is left alone by the setter, because 2D uses it\n * only as a sorting fallback (`docs/architecture/00-overview.md` §4).\n *\n * @returns A freshly allocated 2D vector.\n */\n get localPosition2D(): Vec2 {\n const local = localPosition(transformNode(this));\n return new Vec2(local.x, local.y);\n }\n\n set localPosition2D(value: Vec2) {\n const local = localPosition(transformNode(this));\n local.set(value.x, value.y, local.z);\n }\n\n /**\n * The local rotation about +Z in degrees, counter-clockwise — the only rotation 2D uses\n * (ADR-0011).\n *\n * @returns The angle in degrees.\n */\n get rotation2D(): number {\n const scratch = getScratch();\n Quat.toEulerDegreesToRef(localRotation(transformNode(this)), scratch.vecA);\n return scratch.vecA.z;\n }\n\n set rotation2D(degrees: number) {\n Quat.fromEulerDegreesToRef(0, 0, degrees, localRotation(transformNode(this)));\n }\n\n /**\n * The local scale in the 2D plane.\n *\n * @returns A freshly allocated 2D vector.\n */\n get localScale2D(): Vec2 {\n const scale = localScale(transformNode(this));\n return new Vec2(scale.x, scale.y);\n }\n\n set localScale2D(value: Vec2) {\n const scale = localScale(transformNode(this));\n scale.set(value.x, value.y, scale.z);\n }\n\n /**\n * Writes the world position into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`.\n */\n positionToRef<TOut extends MutableVec3>(out: TOut): TOut {\n return Mat4.getTranslationToRef(this.worldMatrix, out);\n }\n\n /**\n * Writes the world rotation into a caller-owned quaternion. Allocates nothing.\n *\n * @param out - The quaternion to write.\n * @returns `out`.\n */\n rotationToRef<TOut extends MutableQuat>(out: TOut): TOut {\n return Mat4.getRotationToRef(this.worldMatrix, out);\n }\n\n /**\n * Writes the world Euler angles in degrees into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`.\n */\n eulerAnglesToRef<TOut extends MutableVec3>(out: TOut): TOut {\n const scratch = getScratch();\n this.rotationToRef(scratch.quatA);\n return Quat.toEulerDegreesToRef(scratch.quatA, out);\n }\n\n /**\n * Writes the local Euler angles in degrees into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`.\n */\n localEulerAnglesToRef<TOut extends MutableVec3>(out: TOut): TOut {\n return Quat.toEulerDegreesToRef(localRotation(transformNode(this)), out);\n }\n\n /**\n * Writes the lossy world scale into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`.\n */\n lossyScaleToRef<TOut extends MutableVec3>(out: TOut): TOut {\n return Mat4.getScaleToRef(this.worldMatrix, out);\n }\n\n /**\n * Writes the world +Z axis into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`, normalised.\n */\n forwardToRef<TOut extends MutableVec3>(out: TOut): TOut {\n return axisToRef(this.worldMatrix, 8, out);\n }\n\n /**\n * Writes the world +X axis into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`, normalised.\n */\n rightToRef<TOut extends MutableVec3>(out: TOut): TOut {\n return axisToRef(this.worldMatrix, 0, out);\n }\n\n /**\n * Writes the world +Y axis into a caller-owned vector. Allocates nothing.\n *\n * @param out - The vector to write.\n * @returns `out`, normalised.\n */\n upToRef<TOut extends MutableVec3>(out: TOut): TOut {\n return axisToRef(this.worldMatrix, 4, out);\n }\n\n /**\n * Moves the entity by a delta. Allocates nothing.\n *\n * @param delta - How far to move, in metres.\n * @param space - `\"local\"` (the default) rotates the delta by the entity's own rotation first, so\n * `{ z: 1 }` means \"one metre forward\"; `\"world\"` adds the delta to the world position.\n *\n * @example\n * ```ts\n * this.transform.translate({ x: 0, y: 0, z: this.speed * dt }); // forward\n * ```\n */\n translate(delta: Vec3Like, space: \"local\" | \"world\" = \"local\"): void {\n const node = transformNode(this);\n if (space === \"local\") {\n const scratch = getScratch();\n Quat.rotateVectorToRef(localRotation(node), delta, scratch.vecA);\n const local = localPosition(node);\n local.set(local.x + scratch.vecA.x, local.y + scratch.vecA.y, local.z + scratch.vecA.z);\n return;\n }\n const scratch = getScratch();\n this.positionToRef(scratch.vecB);\n scratch.vecB.set(scratch.vecB.x + delta.x, scratch.vecB.y + delta.y, scratch.vecB.z + delta.z);\n this.position = scratch.vecB;\n }\n\n /**\n * Rotates the entity by intrinsic XYZ Euler angles in degrees. Allocates nothing.\n *\n * @param eulerDegrees - The rotation to apply.\n * @param space - `\"local\"` (the default) applies the rotation in the entity's own space;\n * `\"world\"` applies it in world space.\n */\n rotate(eulerDegrees: Vec3Like, space: \"local\" | \"world\" = \"local\"): void {\n const scratch = getScratch();\n Quat.fromEulerDegreesToRef(eulerDegrees.x, eulerDegrees.y, eulerDegrees.z, scratch.quatC);\n const local = localRotation(transformNode(this));\n if (space === \"local\") {\n Quat.multiplyToRef(local, scratch.quatC, local);\n return;\n }\n this.rotationToRef(scratch.quatA);\n Quat.multiplyToRef(scratch.quatC, scratch.quatA, scratch.quatB);\n this.rotation = scratch.quatB;\n }\n\n /**\n * Orbits the entity around a world-space point.\n *\n * @param point - The pivot, in world space.\n * @param axis - The axis to rotate about, in world space; need not be normalised.\n * @param degrees - How far to rotate, counter-clockwise about the axis.\n */\n rotateAround(point: Vec3Like, axis: Vec3Like, degrees: number): void {\n const scratch = getScratch();\n Quat.fromAxisAngleToRef(axis, degrees, scratch.quatC);\n this.positionToRef(scratch.vecA);\n scratch.vecA.set(scratch.vecA.x - point.x, scratch.vecA.y - point.y, scratch.vecA.z - point.z);\n Quat.rotateVectorToRef(scratch.quatC, scratch.vecA, scratch.vecB);\n scratch.vecB.set(scratch.vecB.x + point.x, scratch.vecB.y + point.y, scratch.vecB.z + point.z);\n this.rotationToRef(scratch.quatA);\n Quat.multiplyToRef(scratch.quatC, scratch.quatA, scratch.quatB);\n this.setPositionAndRotation(scratch.vecB, scratch.quatB);\n }\n\n /**\n * Points the entity's +Z axis at a world-space target.\n *\n * @param target - Where to look, in world space.\n * @param up - The world up hint; defaults to +Y.\n */\n lookAt(target: Vec3Like, up: Vec3Like = WORLD_UP): void {\n const scratch = getScratch();\n this.positionToRef(scratch.vecA);\n scratch.vecB.set(target.x - scratch.vecA.x, target.y - scratch.vecA.y, target.z - scratch.vecA.z);\n Quat.lookRotationToRef(scratch.vecB, up, scratch.quatC);\n this.rotation = scratch.quatC;\n }\n\n /**\n * Sets world position and rotation together, which is cheaper than setting them one at a time\n * because the parent's world matrix is read once.\n *\n * @param position - The world position, in metres.\n * @param rotation - The world rotation.\n */\n setPositionAndRotation(position: Vec3Like, rotation: QuatLike): void {\n const node = transformNode(this);\n const parent = parentNode(node);\n if (parent === null) {\n localPosition(node).set(position.x, position.y, position.z);\n localRotation(node).set(rotation.x, rotation.y, rotation.z, rotation.w);\n return;\n }\n const scratch = getScratch();\n readWorldMatrix(parent, scratch.matrixA.elements);\n Mat4.getRotationToRef(scratch.matrixA.elements, scratch.setRotA);\n Quat.invertToRef(scratch.setRotA, scratch.setRotB);\n Quat.multiplyToRef(scratch.setRotB, rotation, localRotation(node));\n if (Mat4.invertToRef(scratch.matrixA.elements, scratch.matrixB)) {\n Mat4.transformPointToRef(scratch.matrixB.elements, position, localPosition(node));\n return;\n }\n localPosition(node).set(position.x, position.y, position.z);\n }\n\n /**\n * Takes a point from this entity's local space to world space.\n *\n * @param local - The point, in the entity's local space.\n * @param out - Where to write the result; a fresh `Vec3` is allocated when omitted.\n * @returns The world point.\n */\n transformPoint(local: Vec3Like, out: MutableVec3 = new Vec3()): MutableVec3 {\n return Mat4.transformPointToRef(this.worldMatrix, local, out);\n }\n\n /**\n * Takes a direction from this entity's local space to world space; translation is ignored.\n *\n * @param local - The direction, in the entity's local space.\n * @param out - Where to write the result; a fresh `Vec3` is allocated when omitted.\n * @returns The world direction.\n */\n transformDirection(local: Vec3Like, out: MutableVec3 = new Vec3()): MutableVec3 {\n return Mat4.transformDirectionToRef(this.worldMatrix, local, out);\n }\n\n /**\n * Takes a point from world space to this entity's local space.\n *\n * @param world - The point, in world space.\n * @param out - Where to write the result; a fresh `Vec3` is allocated when omitted.\n * @returns The local point; unchanged input when the world matrix is singular.\n */\n inverseTransformPoint(world: Vec3Like, out: MutableVec3 = new Vec3()): MutableVec3 {\n const scratch = getScratch();\n if (!Mat4.invertToRef(this.worldMatrix, scratch.matrixB)) {\n out.set(world.x, world.y, world.z);\n return out;\n }\n return Mat4.transformPointToRef(scratch.matrixB.elements, world, out);\n }\n\n /**\n * Takes a direction from world space to this entity's local space.\n *\n * @param world - The direction, in world space.\n * @param out - Where to write the result; a fresh `Vec3` is allocated when omitted.\n * @returns The local direction; unchanged input when the world matrix is singular.\n */\n inverseTransformDirection(world: Vec3Like, out: MutableVec3 = new Vec3()): MutableVec3 {\n const scratch = getScratch();\n if (!Mat4.invertToRef(this.worldMatrix, scratch.matrixB)) {\n out.set(world.x, world.y, world.z);\n return out;\n }\n return Mat4.transformDirectionToRef(scratch.matrixB.elements, world, out);\n }\n}\n\n/**\n * The Babylon Lite node a transform views, declared through interface merging: a symbol-keyed class\n * field is rejected by `isolatedDeclarations` (coding standards §3).\n *\n * @public\n */\n// Merging is deliberate and safe here: the class constructor assigns the one property the\n// interface declares. See the note on `Component`.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- see the note above\nexport interface Transform {\n /**\n * The Lite node, bound by the entity constructor.\n *\n * @internal\n */\n [TRANSFORM_NODE]: LiteSceneNode | null;\n}\n\n/** The default up hint for `Transform.lookAt`. Frozen, so it is safe at module scope. */\nconst WORLD_UP: Vec3Like = Object.freeze({ x: 0, y: 1, z: 0 });\n\n/** Scratch values shared by every transform in the process. */\ninterface TransformScratch {\n /** General-purpose vector slot A. */\n readonly vecA: Vec3;\n /** General-purpose vector slot B. */\n readonly vecB: Vec3;\n /** General-purpose quaternion slot A. */\n readonly quatA: Quat;\n /** General-purpose quaternion slot B. */\n readonly quatB: Quat;\n /** General-purpose quaternion slot C. */\n readonly quatC: Quat;\n /** Slot reserved for the world-rotation setters, so a caller may pass a general slot. */\n readonly setRotA: Quat;\n /** Second slot reserved for the world-rotation setters. */\n readonly setRotB: Quat;\n /** Matrix slot A, normally the parent's world matrix. */\n readonly matrixA: Mat4;\n /** Matrix slot B, normally an inverse. */\n readonly matrixB: Mat4;\n}\n\n/**\n * The shared scratch, created on first use rather than at import time (`CONSTITUTION.md` §3.5).\n *\n * Sharing one set across every transform is safe because nothing in this module calls out to user\n * code between taking a slot and finishing with it, and each method uses distinct slots — so no\n * re-entrant call can be in flight. Per-transform scratch would cost seven objects per entity for\n * no benefit.\n */\nlet sharedScratch: TransformScratch | null = null;\n\n/**\n * The shared scratch values, allocated on first use.\n *\n * @returns The scratch slots.\n */\nfunction getScratch(): TransformScratch {\n sharedScratch ??= {\n vecA: new Vec3(),\n vecB: new Vec3(),\n quatA: new Quat(),\n quatB: new Quat(),\n quatC: new Quat(),\n setRotA: new Quat(),\n setRotB: new Quat(),\n matrixA: new Mat4(),\n matrixB: new Mat4(),\n };\n return sharedScratch;\n}\n\n/**\n * Reads a normalised basis column out of a world matrix.\n *\n * @param matrix - The world matrix.\n * @param offset - The first element of the column: `0` for +X, `4` for +Y, `8` for +Z.\n * @param out - The vector to write.\n * @returns `out`, normalised, or the raw column when it has zero length.\n */\nfunction axisToRef<TOut extends MutableVec3>(matrix: Mat4Like, offset: number, out: TOut): TOut {\n const x = matrix[offset] ?? 0;\n const y = matrix[offset + 1] ?? 0;\n const z = matrix[offset + 2] ?? 0;\n const length = Math.hypot(x, y, z);\n if (length === 0) {\n out.set(x, y, z);\n return out;\n }\n const inverse = 1 / length;\n out.set(x * inverse, y * inverse, z * inverse);\n return out;\n}\n","import type { Extension } from \"../app/types.js\";\n\n/**\n * Wraps an extension factory so that it can be called with or without options\n * (`docs/architecture/04-extensions.md` §1). Every published extension is written this way; a game's\n * own extension should be too.\n *\n * @remarks\n * The wrapper does nothing at module import time (`CONSTITUTION.md` §3.5): the factory runs when the\n * game calls `physics()`, and even then only builds the descriptor — the work happens in `register`\n * and `onStart`.\n *\n * @typeParam O - The options object the factory accepts. Defaults to `void` for an extension that\n * takes none.\n * @param factory - Builds the extension descriptor from its options.\n * @returns A factory that may be called with no argument, in which case the options are `undefined`.\n *\n * @example\n * ```ts\n * export const spawner = defineExtension<{ readonly budget?: number }>((options = {}) => ({\n * name: \"game/spawner\",\n * version: \"1.0.0\",\n * requires: [\"@ignifx/core\"],\n * register(ctx) {\n * ctx.registerService(SpawnerService, new SpawnerService(options.budget ?? 32));\n * },\n * }));\n *\n * const app = await createApp({ headless: true, extensions: [spawner({ budget: 64 })] });\n * ```\n *\n * @public\n */\nexport function defineExtension<O = void>(factory: (options: O) => Extension): (options?: O) => Extension {\n return (options?: O): Extension => {\n // Boundary assertion (coding standards §5.2): the invariant is the contract of this helper —\n // a factory whose options are optional must tolerate `undefined`, which is exactly what the\n // `(options = {})` default parameter in every documented example does.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return factory(options as O);\n };\n}\n","import { Phase } from \"../app/types.js\";\nimport { VERSION } from \"../app/version.js\";\nimport { assetsInternals } from \"../assets/assets-service.js\";\nimport { ASSET_DELIVERY_ORDER, AssetDeliverySystem } from \"../assets/delivery-system.js\";\nimport { GENERIC_ASSET_LOADERS } from \"../assets/generic-loaders.js\";\nimport { DEFAULT_ASSET_ROOT } from \"../assets/manifest.js\";\nimport { DEFAULT_ASSET_CONCURRENCY } from \"../assets/request-queue.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { Camera } from \"../render/camera.js\";\nimport { Environment } from \"../render/environment.js\";\nimport { Light } from \"../render/light.js\";\nimport { createEnvironmentLoader } from \"../render/loaders/environment-loader.js\";\nimport { createFontLoader } from \"../render/loaders/font-loader.js\";\nimport { createMaterialLoader } from \"../render/loaders/material-loader.js\";\nimport { createModelLoader } from \"../render/loaders/model-loader.js\";\nimport { createTextureLoader } from \"../render/loaders/texture-loader.js\";\nimport { MESH_ASSET_TYPE, MeshAsset } from \"../render/mesh-asset.js\";\nimport { MeshRenderer } from \"../render/mesh-renderer.js\";\nimport { Model } from \"../render/model.js\";\nimport { PostProcessStack } from \"../render/post-process-stack.js\";\nimport { RENDER_SYNC_ORDER, RenderSyncSystem } from \"../render/render-sync-system.js\";\nimport { RendererImpl, RendererService } from \"../render/renderer.js\";\nimport {\n defaultRenderingSettings,\n RENDERING_SETTINGS_SECTION,\n renderingSettingsSchema,\n} from \"../render/rendering-settings.js\";\nimport { array, f64, str, u32 } from \"../schema/field-kinds.js\";\nimport { defineSchema } from \"../schema/schema.js\";\nimport { createSceneLoader } from \"../serialization/scene-loader.js\";\nimport { Transform } from \"../transform/transform.js\";\nimport { defineExtension } from \"./define-extension.js\";\nimport type {\n App,\n Extension,\n ExtensionContext,\n LayersSettings,\n SortingLayersSettings,\n TimeSettings,\n} from \"../app/types.js\";\nimport type { AssetsSettings } from \"../assets/types.js\";\nimport type { RenderingSettings } from \"../render/rendering-settings.js\";\n\n/**\n * The implicit core extension (`docs/architecture/04-extensions.md` §7). `@ignifx/core` registers\n * itself through the same contract as everything else, so there is one code path and one set of\n * guarantees.\n *\n * @remarks\n * It registers what the kernel owns: `Transform`, `Camera`, `Light`, `MeshRenderer`, `Model`,\n * `Environment`, and `PostProcessStack`; the `layers`, `sortingLayers`, `time`, `assets`, and\n * `rendering` settings sections; the `json`/`text`/`binary`/`scene` loaders and the GPU ones\n * (`texture`, `model`, `material`, `environment`, `font`); the service behind `app.renderer`; the\n * `PreUpdate` system that delivers completed loads; and the `PreRender` system that reconciles the\n * render components with the Lite scene (`04-extensions.md` §7, `05-assets-and-loading.md` §5,\n * `07-rendering.md` §2, `01-lifecycle-and-time.md` §3 steps 2 and 6).\n *\n * The core diagnostic codes are **not** registered here: `createErrorCodeRegistry()` already\n * pre-loads `CORE_ERROR_MESSAGES`, and registering them a second time is `IGX-1501`.\n *\n * The schemas and defaults are built inside `register`, not at module scope: a schema field is a\n * function call, and module scope holds declarations and immutable constants only\n * (`CONSTITUTION.md` §3.5, coding standards §4). They are built once per app, which is where the\n * cost belongs.\n */\n\n/**\n * The default project layer list (`docs/architecture/04-extensions.md` §5). It is the first five of\n * the eight engine-reserved names, which is why a default project consumes no user layer slot\n * (`02-scene-graph.md` §7).\n */\nconst DEFAULT_LAYERS: readonly string[] = Object.freeze([\"Default\", \"TransparentFX\", \"IgnoreRaycast\", \"Water\", \"UI\"]);\n\n/** The default sorting-layer list, consumed by the 2D toolkit. */\nconst DEFAULT_SORTING_LAYERS: readonly string[] = Object.freeze([\"Default\"]);\n\n/** The default fixed step, in seconds (`01-lifecycle-and-time.md` §2). */\nconst DEFAULT_FIXED_DELTA_TIME = 1 / 60;\n\n/** The default frame-delta clamp, in seconds. */\nconst DEFAULT_MAXIMUM_DELTA_TIME = 0.1;\n\n/** The default time scale. */\nconst DEFAULT_TIME_SCALE = 1;\n\n/** No manifest groups are preloaded unless the project names some. */\nconst DEFAULT_PRELOAD: readonly string[] = Object.freeze([]);\n\n/** How many seconds a zero-reference asset stays cached (`05-assets-and-loading.md` §4). */\nconst DEFAULT_GC_DELAY = 5;\n\n/** How many times a failed asset fetch is retried (`05-assets-and-loading.md` §9). */\nconst DEFAULT_ASSET_RETRIES = 2;\n\n/**\n * Registers the core settings sections and the core components.\n *\n * @param ctx - The registration surface.\n */\nfunction registerCore(ctx: ExtensionContext): void {\n ctx.registerSettings<LayersSettings>(\"layers\", defineSchema({ layers: array(str(), DEFAULT_LAYERS) }), {\n layers: DEFAULT_LAYERS,\n });\n ctx.registerSettings<SortingLayersSettings>(\n \"sortingLayers\",\n defineSchema({ sortingLayers: array(str(), DEFAULT_SORTING_LAYERS) }),\n { sortingLayers: DEFAULT_SORTING_LAYERS },\n );\n ctx.registerSettings<TimeSettings>(\n \"time\",\n defineSchema({\n fixedDeltaTime: f64(DEFAULT_FIXED_DELTA_TIME, { min: Number.EPSILON }),\n maximumDeltaTime: f64(DEFAULT_MAXIMUM_DELTA_TIME, { min: Number.EPSILON }),\n timeScale: f64(DEFAULT_TIME_SCALE, { min: 0 }),\n }),\n {\n fixedDeltaTime: DEFAULT_FIXED_DELTA_TIME,\n maximumDeltaTime: DEFAULT_MAXIMUM_DELTA_TIME,\n timeScale: DEFAULT_TIME_SCALE,\n },\n );\n ctx.registerSettings<AssetsSettings>(\n \"assets\",\n defineSchema({\n root: str(DEFAULT_ASSET_ROOT),\n preload: array(str(), DEFAULT_PRELOAD),\n concurrency: u32(DEFAULT_ASSET_CONCURRENCY, { min: 1 }),\n gcDelay: f64(DEFAULT_GC_DELAY, { min: 0 }),\n retries: u32(DEFAULT_ASSET_RETRIES, { min: 0 }),\n }),\n {\n root: DEFAULT_ASSET_ROOT,\n preload: DEFAULT_PRELOAD,\n concurrency: DEFAULT_ASSET_CONCURRENCY,\n gcDelay: DEFAULT_GC_DELAY,\n retries: DEFAULT_ASSET_RETRIES,\n },\n );\n ctx.registerComponent(Transform);\n registerAssets(ctx);\n registerRendering(ctx);\n}\n\n/**\n * Registers the rendering layer: the `rendering` settings section, the service behind\n * `app.renderer`, the five components `docs/architecture/04-extensions.md` §7 lists, the GPU asset\n * loaders, and the `PreRender` system that reconciles them with the Lite scene.\n *\n * @remarks\n * The order matters in one place: the section is registered *first*, because `ctx.registerSettings`\n * resolves it immediately and {@link RendererImpl} is constructed from the resolved value inside\n * this same `register` call. Everything after that only needs the service to exist.\n *\n * @param ctx - The registration surface.\n */\nfunction registerRendering(ctx: ExtensionContext): void {\n ctx.registerSettings<RenderingSettings>(\n RENDERING_SETTINGS_SECTION,\n renderingSettingsSchema(),\n defaultRenderingSettings(),\n );\n const renderer = new RendererImpl(ctx.app, ctx.settings<RenderingSettings>(RENDERING_SETTINGS_SECTION));\n ctx.registerService(RendererService, renderer);\n ctx.registerComponents([Camera, Light, MeshRenderer, Model, Environment, PostProcessStack]);\n ctx.registerAssetLoader(createTextureLoader());\n ctx.registerAssetLoader(createModelLoader());\n ctx.registerAssetLoader(createMaterialLoader());\n ctx.registerAssetLoader(createEnvironmentLoader());\n ctx.registerAssetLoader(createFontLoader());\n // `MeshAsset.box(...)` and friends publish through `Assets.register`, which needs the type to\n // exist so a `memory:mesh/<n>` handle can be collected — and its `unload` is what frees the\n // template's GPU buffers.\n ctx.registerAssetLoader({\n type: MESH_ASSET_TYPE,\n extensions: [],\n load: (): Promise<never> => Promise.reject(noMeshFileFormat()),\n unload: (value: unknown): void => {\n if (value instanceof MeshAsset) {\n value.dispose();\n }\n },\n });\n const sync = new RenderSyncSystem(renderer);\n renderer.attachSyncSystem(sync);\n ctx.registerSystem(sync, { phase: Phase.PreRender, order: RENDER_SYNC_ORDER });\n ctx.onDispose((): void => {\n renderer.dispose();\n });\n}\n\n/**\n * Builds the failure a `mesh` **address** produces: there is no mesh file format, because geometry\n * arrives either as a primitive built in code or inside a `ModelAsset`.\n *\n * @returns The error to reject with.\n */\nfunction noMeshFileFormat(): IgnifxError {\n return new IgnifxError(CoreErrorCode.assetNoLoader, \"There is no mesh file format; build one in code.\", {\n context: { type: MESH_ASSET_TYPE },\n hint: \"Use MeshAsset.box/sphere/plane/ground/... for primitives, or load a .glb as a model.\",\n });\n}\n\n/**\n * Registers the headless half of the asset service: the generic loaders, the `PreUpdate` delivery\n * system, and the disposer that cancels whatever is still in flight\n * (`docs/architecture/05-assets-and-loading.md` §5, §9).\n *\n * @param ctx - The registration surface.\n */\nfunction registerAssets(ctx: ExtensionContext): void {\n const assets = assetsInternals(ctx.app.assets);\n for (const loader of GENERIC_ASSET_LOADERS) {\n ctx.registerAssetLoader(loader);\n }\n ctx.registerAssetLoader(createSceneLoader());\n ctx.registerSystem(new AssetDeliverySystem(assets), { phase: Phase.PreUpdate, order: ASSET_DELIVERY_ORDER });\n ctx.onDispose((): void => {\n assets.dispose();\n });\n}\n\n/**\n * Starts the manifest groups the `assets` settings section names\n * (`docs/architecture/04-extensions.md` §5: `assets: { root: \"./assets\", preload: [\"boot\"] }`).\n *\n * @remarks\n * The batches are deliberately **not** awaited. Delivery happens in `PreUpdate`, and `onStart` runs\n * before the first frame, so awaiting here would deadlock a headless app that has not been stepped\n * yet. A preloaded group is retained for the life of the app — that is what \"preload\" means — and a\n * failure is reported through `app.onError` rather than being swallowed (coding standards §5.5).\n *\n * @param app - The app being started.\n */\nfunction startPreload(app: App): void {\n const assets = assetsInternals(app.assets);\n for (const group of assets.preloadGroups) {\n const batch = assets.preloadGroup(group);\n void batch.promise.catch((error: unknown): void => {\n app.onError.emit({ error, source: \"asset\", phase: null, entity: null, component: null });\n });\n }\n}\n\n/**\n * Builds the extension `createApp` always puts first (`docs/architecture/04-extensions.md` §2\n * rule 1).\n *\n * @returns The core extension descriptor.\n *\n * @example\n * ```ts\n * // createApp does this for you; the list is only ever built by the kernel.\n * const extensions = [coreExtension(), physics(), input()];\n * ```\n *\n * @public\n */\nexport const coreExtension: (options?: void) => Extension = defineExtension(() => ({\n name: \"@ignifx/core\",\n version: VERSION,\n register: registerCore,\n onStart: startPreload,\n}));\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { ServiceKey, ServiceRegistry } from \"../app/types.js\";\n\n/**\n * The per-app service table (`docs/architecture/04-extensions.md` §1, §3). Extensions write to it\n * through `ExtensionContext.registerService`; scripts read from it through `app.services`, or\n * through the typed property `defineAppProperty` adds.\n */\n\n/**\n * The human-readable name of a service key, for `IGX-0405` messages.\n *\n * @param key - A class token or a named token.\n * @returns The class name, or the name the token was created with.\n *\n * @internal\n */\nexport function serviceKeyName(key: ServiceKey<unknown>): string {\n return typeof key === \"function\" ? key.name : key.serviceName;\n}\n\n/**\n * The service table of one app.\n *\n * @internal\n */\nexport class ServiceRegistryImpl implements ServiceRegistry {\n readonly #entries = new Map<ServiceKey<unknown>, unknown>();\n\n /**\n * Looks a service up, requiring it to be present.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @returns The registered instance.\n * @throws IgnifxError with code `IGX-0405` when no extension registered the service.\n */\n get<T>(key: ServiceKey<T>): T {\n const found = this.tryGet(key);\n if (found === null) {\n throw new IgnifxError(\n CoreErrorCode.serviceNotRegistered,\n `The service ${serviceKeyName(key)} is not registered.`,\n {\n context: { service: serviceKeyName(key) },\n hint: \"Add the extension that registers it, and list that extension in `requires`.\",\n },\n );\n }\n return found;\n }\n\n /**\n * Looks a service up, tolerating its absence.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @returns The instance, or `null` when it is not registered.\n */\n tryGet<T>(key: ServiceKey<T>): T | null {\n const value = this.#entries.get(key);\n if (value === undefined) {\n return null;\n }\n // Boundary assertion (coding standards §5.2): the invariant is enforced by\n // `set<T>(key: ServiceKey<T>, value: T)`, which is the only writer. A `Map` cannot carry the\n // relationship between a key's type parameter and its value.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as T;\n }\n\n /**\n * Reports whether a service is registered.\n *\n * @param key - The class or named key.\n * @returns `true` when an instance is registered under the key.\n */\n has(key: ServiceKey<unknown>): boolean {\n return this.#entries.has(key);\n }\n\n /**\n * Registers an instance.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @param instance - The service.\n */\n set<T>(key: ServiceKey<T>, instance: T): void {\n this.#entries.set(key, instance);\n }\n\n /** Drops every registration, for app disposal. */\n clear(): void {\n this.#entries.clear();\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { physicsCallbackKind, type PhysicsCallbackName } from \"../lifecycle/callbacks.js\";\nimport { serviceKeyName } from \"./service-registry.js\";\nimport type { ServiceRegistryImpl } from \"./service-registry.js\";\nimport type {\n App,\n Extension,\n ExtensionContext,\n RegisterComponentOptions,\n RegisterSystemOptions,\n ServiceKey,\n System,\n} from \"../app/types.js\";\nimport type { AssetLoader, AssetTypeDefinition } from \"../assets/types.js\";\nimport type { ComponentRegistry } from \"../component/component-registry.js\";\nimport type { ConcreteComponentType } from \"../component/component-type.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { ErrorCodeRegistry } from \"../errors/error-code-registry.js\";\nimport type { LiteScene } from \"../lite/scene.js\";\nimport type { Logger } from \"../log/logger.js\";\nimport type { RenderingFeature } from \"../render/renderer.js\";\nimport type { Scheduler } from \"../scheduler/scheduler.js\";\nimport type { Schema } from \"../schema/types.js\";\nimport type { SettingsStore } from \"../settings/settings-store.js\";\n\n/**\n * What the context needs from the host that owns it.\n *\n * @internal\n */\nexport interface ExtensionContextHost {\n /**\n * The single `Object.defineProperty` call site of the engine.\n *\n * @param name - The property name.\n * @param getter - Returns the value on each read.\n * @param owner - The extension defining it, named in `IGX-0401`.\n */\n defineAppProperty(name: string, getter: () => unknown, owner: string): void;\n /**\n * Records a teardown callback to run when the app is disposed.\n *\n * @param callback - The teardown.\n */\n addDisposer(callback: () => void): void;\n /** Whether the app is being disposed, in which case the world is already gone. */\n readonly isDisposing: boolean;\n}\n\n/**\n * Everything an {@link ExtensionContextImpl} writes into.\n *\n * @internal\n */\nexport interface ExtensionContextOptions {\n /** The app being built. */\n readonly app: App;\n /** The extension this context belongs to. */\n readonly extension: Extension;\n /** A logger scoped to the extension. */\n readonly log: Logger;\n /** The component-class table shared with the world. */\n readonly registry: ComponentRegistry;\n /** The service table. */\n readonly services: ServiceRegistryImpl;\n /** The project settings table. */\n readonly settings: SettingsStore;\n /** The diagnostic-code table. */\n readonly errorCodes: ErrorCodeRegistry;\n /** The frame function systems are registered with. */\n readonly scheduler: Scheduler;\n /** The host, for the two operations only it can perform. */\n readonly host: ExtensionContextHost;\n}\n\n/**\n * One extension's registration surface (`docs/architecture/04-extensions.md` §1). A fresh context is\n * built for each extension so that every contribution is attributed to its owner in diagnostics.\n *\n * @internal\n */\nexport class ExtensionContextImpl implements ExtensionContext {\n /** The app being built. */\n readonly app: App;\n\n /** A logger scoped to this extension. */\n readonly log: Logger;\n\n readonly #extension: Extension;\n\n readonly #registry: ComponentRegistry;\n\n readonly #services: ServiceRegistryImpl;\n\n readonly #settings: SettingsStore;\n\n readonly #errorCodes: ErrorCodeRegistry;\n\n readonly #scheduler: Scheduler;\n\n readonly #host: ExtensionContextHost;\n\n /**\n * Creates the context of one extension.\n *\n * @param options - The app and the tables the extension contributes to.\n */\n constructor(options: ExtensionContextOptions) {\n this.app = options.app;\n this.log = options.log;\n this.#extension = options.extension;\n this.#registry = options.registry;\n this.#services = options.services;\n this.#settings = options.settings;\n this.#errorCodes = options.errorCodes;\n this.#scheduler = options.scheduler;\n this.#host = options.host;\n }\n\n /**\n * Registers one component class, making its `typeId` known to the serializer and the inspector.\n *\n * @param type - The component class.\n * @param options - An explicit `typeId`, when the class does not declare one.\n */\n registerComponent(type: ConcreteComponentType, options?: RegisterComponentOptions): void {\n this.#registry.register(type, options?.typeId);\n }\n\n /**\n * Registers several component classes.\n *\n * @param types - The component classes.\n */\n registerComponents(types: readonly ConcreteComponentType[]): void {\n this.#registry.registerAll(types);\n }\n\n /**\n * Registers a system in a phase.\n *\n * @param system - The system.\n * @param options - The phase and the ascending order within it.\n */\n registerSystem(system: System, options: RegisterSystemOptions): void {\n this.#scheduler.registerSystem(system, options);\n }\n\n /**\n * Registers a service instance under a key.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @param instance - The service.\n */\n registerService<T>(key: ServiceKey<T>, instance: T): void {\n this.#services.set(key, instance);\n }\n\n /**\n * Declares an asset type whose loader is registered separately, or not at all\n * (`docs/architecture/04-extensions.md` §1).\n *\n * @param type - The type name and the extensions that select it.\n */\n registerAssetType(type: AssetTypeDefinition): void {\n this.app.assets.registerType(type);\n }\n\n /**\n * Registers an asset loader (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @param loader - The loader, which also declares the extensions that select its type.\n * @throws IgnifxError with code `IGX-0506` when another extension already owns the type.\n */\n registerAssetLoader(loader: AssetLoader): void {\n this.app.assets.registerLoader(loader);\n }\n\n /**\n * Declares that this extension needs a rendering feature switched on\n * (`docs/architecture/07-rendering.md` §1.1).\n *\n * @param feature - The feature the extension needs.\n * @throws IgnifxError with code `IGX-0704` when the render scene has already been registered.\n */\n requireRenderingFeature(feature: RenderingFeature): void {\n this.app.renderer.requireFeature(feature);\n }\n\n /**\n * Defines a property on `App`, pairing with a module augmentation of the `App` interface\n * (`docs/architecture/03-scripting-and-components.md` §7).\n *\n * @param name - The property name, for example `\"input\"`.\n * @param getter - Returns the value each time the property is read.\n * @throws IgnifxError with code `IGX-0401` when the property already exists on the app.\n */\n defineAppProperty(name: string, getter: () => unknown): void {\n this.#host.defineAppProperty(name, getter, this.#extension.name);\n }\n\n /**\n * Registers a project settings section and resolves it immediately, so `ctx.settings(section)`\n * works inside the same `register` call.\n *\n * @typeParam S - The section's resolved shape.\n * @param section - The section name as it appears in `ignifx.config.ts`.\n * @param schema - The schema the section is validated against.\n * @param defaults - The values used when the project omits the section.\n * @throws IgnifxError with code `IGX-0408` in development when the project's values do not\n * validate against the schema.\n */\n // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- see `AppSettings.section`.\n registerSettings<S>(section: string, schema: Schema, defaults: S): void {\n this.#settings.register(section, schema, defaults, this.#extension.name);\n }\n\n /**\n * Adds diagnostic codes to the app's error-code registry.\n *\n * @param codes - `IGX-####` to one-line message template.\n */\n registerErrorCodes(codes: Readonly<Record<string, string>>): void {\n this.#errorCodes.register(codes, this.#extension.name);\n }\n\n /**\n * Delivers one physics callback to every implementing script on an entity, through the world's\n * single guarded call site (`docs/architecture/09-physics.md` §4).\n *\n * @param entity - The entity whose scripts should receive the callback.\n * @param kind - Which physics callback to deliver.\n * @param argument - The collision or trigger event the callback receives.\n * @throws IgnifxError with code `IGX-0409` in development when called outside the fixed loop.\n */\n dispatchScriptCallback(entity: Entity, kind: PhysicsCallbackName, argument: unknown): void {\n const app = this.app;\n if (!app.time.inFixedStep && app.diagnostics.isDevelopment) {\n throw new IgnifxError(\n CoreErrorCode.physicsCallbackOutsideFixedStep,\n `${this.#extension.name} dispatched ${kind} outside a fixed step.`,\n {\n context: { callback: kind, extension: this.#extension.name },\n hint: \"Dispatch physics callbacks from a system registered in Phase.FixedUpdate.\",\n },\n );\n }\n app.world.lifecycle.dispatchToEntity(entity, physicsCallbackKind(kind), argument);\n }\n\n /**\n * Whether any script on an entity implements a physics callback, whatever its `enabled` state\n * (`docs/architecture/09-physics.md` §2.1).\n *\n * @param entity - The entity to inspect.\n * @param kind - Which physics callback.\n * @returns `true` when at least one script on the entity implements it.\n */\n entityImplements(entity: Entity, kind: PhysicsCallbackName): boolean {\n return this.app.world.lifecycle.entityImplements(entity, physicsCallbackKind(kind));\n }\n\n /**\n * Publishes the scene this extension simulates in as `world.lite.simulationScene`\n * (`docs/architecture/09-physics.md` §1).\n *\n * @param scene - The simulation scene, or `null` to clear it.\n * @throws IgnifxError with code `IGX-0410` when the world already has a different one.\n */\n setSimulationScene(scene: LiteScene | null): void {\n if (scene === null && this.#host.isDisposing) {\n // `App.dispose()` disposes the world before the extensions, and `World.dispose()` clears the\n // simulation scene itself, so a clear from an extension's `dispose` has nothing left to do —\n // and `app.world` would refuse the disposed app with `IGX-0106`.\n return;\n }\n this.app.world.setSimulationScene(scene);\n }\n\n /**\n * Registers a callback that runs when the app is disposed, in reverse registration order.\n *\n * @param callback - The teardown to run.\n */\n onDispose(callback: () => void): void {\n this.#host.addDisposer(callback);\n }\n\n /**\n * Looks up a service registered by an earlier extension.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @returns The instance.\n * @throws IgnifxError with code `IGX-0405` when the service is not registered.\n */\n require<T>(key: ServiceKey<T>): T {\n const found = this.#services.tryGet(key);\n if (found === null) {\n throw new IgnifxError(\n CoreErrorCode.serviceNotRegistered,\n `The service ${serviceKeyName(key)} required by ${this.#extension.name} is not registered.`,\n {\n context: { service: serviceKeyName(key), extension: this.#extension.name },\n hint: \"List the extension that registers it in `requires` so it registers first.\",\n },\n );\n }\n return found;\n }\n\n /**\n * Looks up a service registered by an earlier extension, tolerating its absence.\n *\n * @typeParam T - The service instance type.\n * @param key - The class or named key.\n * @returns The instance, or `null` when it is not registered.\n */\n tryGet<T>(key: ServiceKey<T>): T | null {\n return this.#services.tryGet(key);\n }\n\n /**\n * Reads a resolved settings section.\n *\n * @typeParam S - The section's resolved shape.\n * @param section - The section name.\n * @returns The resolved section.\n * @throws IgnifxError with code `IGX-0407` when the section was never registered.\n */\n // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- see `AppSettings.section`.\n settings<S>(section: string): S {\n return this.#settings.section<S>(section);\n }\n}\n","/**\n * The semver range matcher the extension host uses for `Extension.engine`\n * (`docs/architecture/04-extensions.md` §1, §2 rule 3). It is deliberately in-house and tiny:\n * coding standards §13 makes every runtime dependency an ADR paragraph, and the only ranges the\n * contract asks for are the comparator forms below.\n *\n * ## Supported grammar\n *\n * ```text\n * range := set ( \" || \" set )*\n * set := comparator ( \" \" comparator )*\n * comparator := ( \"^\" | \">=\" | \"<=\" | \">\" | \"<\" | \"=\" )? version\n * version := <digits> \".\" <digits> \".\" <digits>\n * ```\n *\n * A range matches when **any** set matches; a set matches when **every** comparator in it matches.\n * `^` follows npm's rules, including the 0.x special cases: `^1.2.3` is `>=1.2.3 <2.0.0`,\n * `^0.2.3` is `>=0.2.3 <0.3.0`, and `^0.0.3` is `>=0.0.3 <0.0.4`.\n *\n * Not supported, and rejected rather than guessed at: prerelease and build metadata (`1.0.0-rc.1`),\n * `x`/`*` wildcards, hyphen ranges, and `~`. A range this module cannot parse never matches, so the\n * extension host reports `IGX-0404` naming the range, which is the actionable failure.\n */\n\n/** A parsed `major.minor.patch` triple. */\ninterface Version {\n /** The major component. */\n readonly major: number;\n /** The minor component. */\n readonly minor: number;\n /** The patch component. */\n readonly patch: number;\n}\n\n/** `major.minor.patch`, digits only. */\nconst VERSION_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/u;\n\n/** The comparator prefixes, longest first so `>=` is matched before `>`. */\nconst OPERATORS: readonly string[] = Object.freeze([\">=\", \"<=\", \"^\", \">\", \"<\", \"=\"]);\n\n/**\n * Parses a `major.minor.patch` string.\n *\n * @param text - The candidate version.\n * @returns The parsed triple, or `null` when the text is not a plain three-part version.\n */\nfunction parseVersion(text: string): Version | null {\n const match = VERSION_PATTERN.exec(text.trim());\n if (match === null) {\n return null;\n }\n return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };\n}\n\n/**\n * Orders two versions.\n *\n * @param left - The first version.\n * @param right - The second version.\n * @returns A negative number when `left` is older, `0` when they are equal, a positive number when\n * `left` is newer.\n */\nfunction compare(left: Version, right: Version): number {\n if (left.major !== right.major) {\n return left.major - right.major;\n }\n if (left.minor !== right.minor) {\n return left.minor - right.minor;\n }\n return left.patch - right.patch;\n}\n\n/**\n * The exclusive upper bound of a caret comparator, following npm's 0.x rules.\n *\n * @param version - The caret's base version.\n * @returns The first version the caret no longer accepts.\n */\nfunction caretLimit(version: Version): Version {\n if (version.major > 0) {\n return { major: version.major + 1, minor: 0, patch: 0 };\n }\n if (version.minor > 0) {\n return { major: 0, minor: version.minor + 1, patch: 0 };\n }\n return { major: 0, minor: 0, patch: version.patch + 1 };\n}\n\n/**\n * Tests one comparator.\n *\n * @param version - The version being checked.\n * @param comparator - One comparator, for example `\">=0.1.0\"`.\n * @returns `true` when the version satisfies it; `false` when it does not, or when the comparator\n * cannot be parsed.\n */\nfunction satisfiesComparator(version: Version, comparator: string): boolean {\n let operator = \"=\";\n let rest = comparator;\n for (let index = 0; index < OPERATORS.length; index += 1) {\n const candidate = OPERATORS[index];\n if (candidate !== undefined && comparator.startsWith(candidate)) {\n operator = candidate;\n rest = comparator.slice(candidate.length);\n break;\n }\n }\n const bound = parseVersion(rest);\n if (bound === null) {\n return false;\n }\n const order = compare(version, bound);\n switch (operator) {\n case \">=\": {\n return order >= 0;\n }\n case \"<=\": {\n return order <= 0;\n }\n case \">\": {\n return order > 0;\n }\n case \"<\": {\n return order < 0;\n }\n case \"^\": {\n return order >= 0 && compare(version, caretLimit(bound)) < 0;\n }\n default: {\n return order === 0;\n }\n }\n}\n\n/**\n * Reports whether a version satisfies a range.\n *\n * @param version - The `major.minor.patch` version being checked, normally the running\n * `@ignifx/core` version.\n * @param range - The range an extension declared in `Extension.engine`.\n * @returns `true` when the version satisfies the range. An empty range matches everything; a range\n * this module cannot parse matches nothing.\n *\n * @example\n * ```ts\n * satisfiesRange(\"0.4.2\", \">=0.4.0 <1.0.0\"); // true\n * satisfiesRange(\"1.0.0\", \"^0.4.0 || ^1.0.0\"); // true\n * satisfiesRange(\"0.0.0\", \">=0.1.0\"); // false\n * ```\n *\n * @internal\n */\nexport function satisfiesRange(version: string, range: string): boolean {\n const parsed = parseVersion(version);\n const trimmed = range.trim();\n if (parsed === null) {\n return false;\n }\n if (trimmed === \"\") {\n return true;\n }\n const sets = trimmed.split(\"||\");\n for (let index = 0; index < sets.length; index += 1) {\n const set = sets[index]?.trim() ?? \"\";\n if (set === \"\") {\n continue;\n }\n const comparators = set.split(\" \");\n let matches = true;\n for (let at = 0; at < comparators.length; at += 1) {\n const comparator = comparators[at]?.trim() ?? \"\";\n if (comparator === \"\") {\n continue;\n }\n if (!satisfiesComparator(parsed, comparator)) {\n matches = false;\n break;\n }\n }\n if (matches) {\n return true;\n }\n }\n return false;\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { ExtensionContextImpl } from \"./extension-context.js\";\nimport { satisfiesRange } from \"./semver-range.js\";\nimport type { ExtensionContextHost } from \"./extension-context.js\";\nimport type { ServiceRegistryImpl } from \"./service-registry.js\";\nimport type { App, ErrorReport, Extension } from \"../app/types.js\";\nimport type { ComponentRegistry } from \"../component/component-registry.js\";\nimport type { ErrorCodeRegistry } from \"../errors/error-code-registry.js\";\nimport type { ErrorFormatMode } from \"../errors/ignifx-error.js\";\nimport type { Logger } from \"../log/logger.js\";\nimport type { Scheduler } from \"../scheduler/scheduler.js\";\nimport type { SettingsStore } from \"../settings/settings-store.js\";\n\n/**\n * The extension host (`docs/architecture/04-extensions.md` §2). It builds the extension list, sorts\n * it, validates it, runs `register` in order, and later runs `onStart` in order and\n * `onStop`/`dispose` in reverse.\n *\n * Decisions the documents leave open:\n *\n * - **`register` and `onStart` failures propagate.** They are construction, not frame work: a game\n * whose physics extension could not fetch its WASM should see `createApp()` reject, not start and\n * misbehave. `onStop`, `dispose`, and the `onDispose` callbacks are caught and reported through\n * `app.onError` with `source: \"extension\"` instead, so one failing teardown never strands the\n * rest.\n * - **Sorting is a depth-first walk of the list in the order the game wrote it.** That makes the\n * result stable and predictable: extensions with no relationship keep their list order, and a\n * dependency is only pulled forward as far as it has to be.\n */\n\n/** The DFS colour of an extension while the list is being sorted. */\nconst Visit = {\n /** Not yet reached. */\n unvisited: 0,\n /** On the current DFS stack. */\n visiting: 1,\n /** Placed in the sorted list. */\n placed: 2,\n} as const;\n\n/** The union of {@link Visit} states. */\ntype Visit = (typeof Visit)[keyof typeof Visit];\n\n/**\n * What the host needs from the app.\n *\n * @internal\n */\nexport interface ExtensionHostOptions {\n /** The app being built; `defineAppProperty` writes onto this object. */\n readonly app: App;\n /** The app logger; each extension gets a child of it. */\n readonly log: Logger;\n /** The component-class table shared with the world. */\n readonly registry: ComponentRegistry;\n /** The service table. */\n readonly services: ServiceRegistryImpl;\n /** The project settings table. */\n readonly settings: SettingsStore;\n /** The diagnostic-code table. */\n readonly errorCodes: ErrorCodeRegistry;\n /** The frame function systems are registered with. */\n readonly scheduler: Scheduler;\n /** The running `@ignifx/core` version, checked against each `engine` range. */\n readonly version: string;\n /** `\"development\"` throws on a validation failure; `\"production\"` warns where §2 allows it. */\n readonly mode: ErrorFormatMode;\n /**\n * Reports a teardown failure.\n *\n * @param report - What failed, and where.\n */\n report(report: ErrorReport): void;\n}\n\n/**\n * The extension host of one app.\n *\n * @internal\n */\nexport class ExtensionHost implements ExtensionContextHost {\n readonly #options: ExtensionHostOptions;\n\n readonly #sorted: Extension[] = [];\n\n readonly #disposers: (() => void)[] = [];\n #isDisposing = false;\n\n readonly #properties = new Set<string>();\n\n /**\n * Creates the host of one app.\n *\n * @param options - The app and the tables extensions contribute to.\n */\n constructor(options: ExtensionHostOptions) {\n this.#options = options;\n }\n\n /**\n * The extensions in the order they were registered in.\n *\n * @returns The sorted list.\n */\n get extensions(): readonly Extension[] {\n return this.#sorted;\n }\n\n /**\n * Sorts, validates, and registers every extension (§2 rules 1–4).\n *\n * @param list - The implicit core extension followed by the game's list.\n * @returns A promise that settles once every `register` hook has finished.\n * @throws IgnifxError with code `IGX-0406` on a duplicate name, `IGX-0403` on a missing required\n * extension, `IGX-0402` on a `requires` cycle, or `IGX-0404` on an `engine` mismatch in\n * development.\n */\n async register(list: readonly Extension[]): Promise<void> {\n const sorted = this.#sort(list);\n for (let index = 0; index < sorted.length; index += 1) {\n const extension = sorted[index];\n if (extension !== undefined) {\n this.#checkEngineRange(extension);\n }\n }\n this.#sorted.push(...sorted);\n for (let index = 0; index < sorted.length; index += 1) {\n const extension = sorted[index];\n if (extension === undefined) {\n continue;\n }\n const context = new ExtensionContextImpl({\n app: this.#options.app,\n extension,\n log: this.#options.log.child(extension.name),\n registry: this.#options.registry,\n services: this.#options.services,\n settings: this.#options.settings,\n errorCodes: this.#options.errorCodes,\n scheduler: this.#options.scheduler,\n host: this,\n });\n const result = extension.register(context);\n if (result !== undefined) {\n // Sequential on purpose (§2 rule 4): an extension's `register` may `ctx.require` a service\n // an earlier one registered, so running them in parallel would break the contract.\n // oxlint-disable-next-line eslint/no-await-in-loop -- see above\n await result;\n }\n }\n }\n\n /**\n * Runs every `onStart` hook in registration order (§2 rule 5).\n *\n * @returns A promise that settles once every hook has finished.\n */\n async start(): Promise<void> {\n const app = this.#options.app;\n for (let index = 0; index < this.#sorted.length; index += 1) {\n const result = this.#sorted[index]?.onStart?.(app);\n if (result !== undefined) {\n // Sequential on purpose (§2 rule 5): `onStart` runs \"in order\", and a later extension may\n // depend on what an earlier one loaded.\n // oxlint-disable-next-line eslint/no-await-in-loop -- see above\n await result;\n }\n }\n }\n\n /** Runs every `onStop` hook in reverse registration order (§2 rule 6), guarded. */\n stop(): void {\n const app = this.#options.app;\n for (let index = this.#sorted.length - 1; index >= 0; index -= 1) {\n const extension = this.#sorted[index];\n if (extension === undefined) {\n continue;\n }\n try {\n extension.onStop?.(app);\n } catch (error) {\n this.#reportTeardown(error);\n }\n }\n }\n\n /** Runs every `dispose` hook and `onDispose` callback in reverse order, guarded. */\n dispose(): void {\n this.#isDisposing = true;\n const app = this.#options.app;\n for (let index = this.#sorted.length - 1; index >= 0; index -= 1) {\n const extension = this.#sorted[index];\n if (extension === undefined) {\n continue;\n }\n try {\n extension.dispose?.(app);\n } catch (error) {\n this.#reportTeardown(error);\n }\n }\n for (let index = this.#disposers.length - 1; index >= 0; index -= 1) {\n try {\n this.#disposers[index]?.();\n } catch (error) {\n this.#reportTeardown(error);\n }\n }\n this.#disposers.length = 0;\n }\n\n /**\n * Whether {@link ExtensionHost.dispose} has begun, for the context's dispose-time checks.\n *\n * @returns `true` from the first line of `dispose()` onwards.\n */\n get isDisposing(): boolean {\n return this.#isDisposing;\n }\n\n /**\n * Defines a typed service property on the app object.\n *\n * @remarks\n * Coding standards §5.3 bans `Object.defineProperty` tricks *except* this call site, which\n * `docs/architecture/04-extensions.md` §1 requires: `ctx.defineAppProperty(\"input\", () => service)`\n * is the runtime half of the module augmentation that makes `this.app.input` typed. The property\n * is an accessor rather than a value so that a service replaced during hot reload is picked up on\n * the next read, and `configurable: false` is what makes a second definition impossible even\n * outside the guard below.\n *\n * @param name - The property name.\n * @param getter - Returns the value on each read.\n * @param owner - The extension defining it, named in the error.\n * @throws IgnifxError with code `IGX-0401` when the name is already taken, whether by another\n * extension or by the `App` surface itself.\n */\n defineAppProperty(name: string, getter: () => unknown, owner: string): void {\n const app = this.#options.app;\n if (this.#properties.has(name) || name in app) {\n throw new IgnifxError(CoreErrorCode.appPropertyAlreadyDefined, `The app property ${name} is already defined.`, {\n context: { property: name, owner },\n hint: \"Pick a name no other extension and no core App member uses.\",\n });\n }\n this.#properties.add(name);\n Object.defineProperty(app, name, { get: getter, enumerable: true, configurable: false });\n }\n\n /**\n * Records a teardown callback.\n *\n * @param callback - The teardown to run at disposal.\n */\n addDisposer(callback: () => void): void {\n this.#disposers.push(callback);\n }\n\n /**\n * Checks an extension's `engine` range against the running core version (§2 rule 3).\n *\n * @param extension - The extension to check.\n * @throws IgnifxError with code `IGX-0404` in development when the range does not match.\n */\n #checkEngineRange(extension: Extension): void {\n const range = extension.engine;\n if (range === undefined || satisfiesRange(this.#options.version, range)) {\n return;\n }\n const message = `${extension.name} supports engine ${range} but the running core is ${this.#options.version}.`;\n if (this.#options.mode === \"development\") {\n throw new IgnifxError(CoreErrorCode.extensionEngineMismatch, message, {\n context: { extension: extension.name, range, version: this.#options.version },\n hint: \"Upgrade the extension, or widen its `engine` range if it really does support this core.\",\n });\n }\n this.#options.log.warn(message);\n }\n\n /**\n * Topologically sorts the extension list (§2 rule 2).\n *\n * @param list - The extensions in the order the game wrote them.\n * @returns A new list in which every extension follows everything it requires.\n * @throws IgnifxError with code `IGX-0406`, `IGX-0403`, or `IGX-0402`.\n */\n #sort(list: readonly Extension[]): Extension[] {\n const byName = new Map<string, Extension>();\n for (let index = 0; index < list.length; index += 1) {\n const extension = list[index];\n if (extension === undefined) {\n continue;\n }\n if (byName.has(extension.name)) {\n throw new IgnifxError(\n CoreErrorCode.duplicateExtensionName,\n `The extension name ${extension.name} is registered twice.`,\n { context: { extension: extension.name }, hint: \"Every extension name must be unique within one app.\" },\n );\n }\n byName.set(extension.name, extension);\n }\n const state = new Map<string, Visit>();\n const stack: string[] = [];\n const sorted: Extension[] = [];\n for (let index = 0; index < list.length; index += 1) {\n const extension = list[index];\n if (extension !== undefined) {\n this.#visit(extension, byName, state, stack, sorted);\n }\n }\n return sorted;\n }\n\n /**\n * Places one extension after everything it depends on.\n *\n * @param extension - The extension to place.\n * @param byName - Every extension in the app, by name.\n * @param state - The DFS colour of each extension.\n * @param stack - The names on the current DFS stack, for the cycle message.\n * @param sorted - The list being built.\n */\n #visit(\n extension: Extension,\n byName: ReadonlyMap<string, Extension>,\n state: Map<string, Visit>,\n stack: string[],\n sorted: Extension[],\n ): void {\n if (state.get(extension.name) === Visit.placed) {\n return;\n }\n state.set(extension.name, Visit.visiting);\n stack.push(extension.name);\n const required = extension.requires ?? [];\n for (let index = 0; index < required.length; index += 1) {\n const name = required[index];\n if (name === undefined) {\n continue;\n }\n const dependency = byName.get(name);\n if (dependency === undefined) {\n throw new IgnifxError(\n CoreErrorCode.extensionMissing,\n `${extension.name} requires ${name}, which is not registered.`,\n {\n context: { extension: extension.name, required: name },\n hint: \"Add the extension to the `extensions` list passed to createApp().\",\n },\n );\n }\n if (state.get(name) === Visit.visiting) {\n throw new IgnifxError(\n CoreErrorCode.extensionRequiresCycle,\n `The extension requires graph contains a cycle: ${stack.join(\" -> \")} -> ${name}.`,\n {\n context: { cycle: `${stack.join(\" -> \")} -> ${name}` },\n hint: \"Turn one of the edges into an `optional` dependency resolved lazily in onStart.\",\n },\n );\n }\n this.#visit(dependency, byName, state, stack, sorted);\n }\n const optional = extension.optional ?? [];\n for (let index = 0; index < optional.length; index += 1) {\n const name = optional[index];\n if (name === undefined) {\n continue;\n }\n const dependency = byName.get(name);\n if (dependency === undefined) {\n continue;\n }\n if (state.get(name) === Visit.visiting) {\n // §2 rule 2: two extensions that optionally integrate with each other are legal. The edge\n // is dropped, the pair registers in list order, and each resolves the other lazily through\n // `ctx.tryGet` in `onStart`.\n if (this.#options.mode === \"development\") {\n this.#options.log.debug(\n \"Dropped the optional dependency {extension} -> {optional} because it would form a cycle.\",\n extension.name,\n name,\n );\n }\n continue;\n }\n this.#visit(dependency, byName, state, stack, sorted);\n }\n stack.pop();\n state.set(extension.name, Visit.placed);\n sorted.push(extension);\n }\n\n /**\n * Reports a teardown failure through `app.onError`.\n *\n * @param error - Whatever the hook threw.\n */\n #reportTeardown(error: unknown): void {\n this.#options.report({ error, source: \"extension\", phase: null, entity: null, component: null });\n }\n}\n","import type { LayerTable } from \"./layer-table.js\";\n\n/**\n * A set of layer slots as one 32-bit word (`docs/architecture/02-scene-graph.md` §7). Masks are\n * immutable: {@link LayerMask.with} and {@link LayerMask.without} return new masks, so a mask\n * handed to a physics query can be shared without defensive copying.\n */\n\n/** The mask with every one of the 32 slots set. Written unsigned so it stays a positive number. */\nconst ALL_BITS = 0xff_ff_ff_ff;\n\n/**\n * An immutable set of layer slots.\n *\n * @remarks\n * Two ways in, deliberately:\n *\n * - **Scripts use `world.layers.mask(\"Player\", \"Enemy\")`** — names, resolved through the project's\n * {@link LayerTable}, which is what makes files rename-safe.\n * - {@link LayerMask.of} takes slot **indices**, for code that already resolved names (a system\n * caching `entity.layer` at `awake`, say) and for tests.\n *\n * There is no name-taking static, because resolving a name needs the project's table and a static\n * has no access to one; {@link LayerMask.fromNames} is the standalone form that takes the table\n * explicitly.\n *\n * @example\n * ```ts\n * class Hitbox extends Script {\n * #hostiles = LayerMask.nothing();\n * awake(): void {\n * this.#hostiles = this.world.layers.mask(\"Enemy\", \"Projectile\");\n * }\n * onTriggerEnter(other: TriggerEvent): void {\n * if (this.#hostiles.has(other.entity.layer)) {\n * this.takeDamage();\n * }\n * }\n * }\n * ```\n *\n * @public\n */\nexport class LayerMask {\n /** The 32 slot bits, read as an unsigned word. */\n readonly bits: number;\n\n /**\n * Wraps a raw bit word. Prefer {@link LayerMask.of}, {@link LayerMask.fromNames}, or\n * `world.layers.mask(...)`.\n *\n * @param bits - The bit word; only the low 32 bits are kept.\n */\n constructor(bits: number) {\n this.bits = bits >>> 0;\n }\n\n /**\n * Builds a mask from layer slot indices.\n *\n * @param layers - The slots to include; values outside `[0, 31]` are ignored.\n * @returns The mask.\n *\n * @example\n * ```ts\n * LayerMask.of(0, 8).bits; // 0b100000001\n * ```\n */\n static of(...layers: readonly number[]): LayerMask {\n let bits = 0;\n for (let index = 0; index < layers.length; index += 1) {\n const layer = layers[index] ?? -1;\n if (layer >= 0 && layer < 32) {\n bits |= 1 << layer;\n }\n }\n return new LayerMask(bits);\n }\n\n /**\n * Builds a mask from layer names resolved through a table — the standalone form of\n * `world.layers.mask(...)`.\n *\n * @param table - The project's layer table.\n * @param names - The layer names to include.\n * @returns The mask.\n * @throws IgnifxError with code `IGX-0303` when a name is not declared.\n */\n static fromNames(table: LayerTable, names: readonly string[]): LayerMask {\n let bits = 0;\n for (let index = 0; index < names.length; index += 1) {\n const name = names[index];\n if (name !== undefined) {\n bits |= 1 << table.requireIndex(name);\n }\n }\n return new LayerMask(bits);\n }\n\n /**\n * Wraps a bit word that was stored or received from another system.\n *\n * @param bits - The bit word.\n * @returns The mask.\n */\n static fromBits(bits: number): LayerMask {\n return new LayerMask(bits);\n }\n\n /**\n * The mask with no slots set.\n *\n * @returns An empty mask.\n */\n static nothing(): LayerMask {\n return new LayerMask(0);\n }\n\n /**\n * The mask with all 32 slots set.\n *\n * @returns A full mask.\n */\n static everything(): LayerMask {\n return new LayerMask(ALL_BITS);\n }\n\n /**\n * Reports whether a slot is in the mask.\n *\n * @param layer - The slot index.\n * @returns `true` when the slot's bit is set.\n */\n has(layer: number): boolean {\n if (layer < 0 || layer >= 32) {\n return false;\n }\n return (this.bits & (1 << layer)) !== 0;\n }\n\n /**\n * Adds a slot.\n *\n * @param layer - The slot index; out-of-range values are ignored.\n * @returns A new mask; this one is unchanged.\n */\n with(layer: number): LayerMask {\n if (layer < 0 || layer >= 32) {\n return this;\n }\n return new LayerMask(this.bits | (1 << layer));\n }\n\n /**\n * Removes a slot.\n *\n * @param layer - The slot index; out-of-range values are ignored.\n * @returns A new mask; this one is unchanged.\n */\n without(layer: number): LayerMask {\n if (layer < 0 || layer >= 32) {\n return this;\n }\n return new LayerMask(this.bits & ~(1 << layer));\n }\n\n /**\n * Reports whether the mask shares at least one slot with another.\n *\n * @param other - The mask to test against.\n * @returns `true` when the two masks overlap.\n */\n intersects(other: LayerMask): boolean {\n return (this.bits & other.bits) !== 0;\n }\n\n /**\n * The names of every slot in the mask, in slot order — what the serializer writes, because files\n * store names rather than bits (`docs/architecture/06-serialization-and-scene-format.md` §3).\n *\n * @param table - The project's layer table.\n * @returns The names of the set slots that the table declares; unnamed slots are skipped.\n */\n toNames(table: LayerTable): string[] {\n const names: string[] = [];\n for (let layer = 0; layer < 32; layer += 1) {\n if ((this.bits & (1 << layer)) !== 0) {\n const name = table.nameOf(layer);\n if (name !== null) {\n names.push(name);\n }\n }\n }\n return names;\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { LayerMask } from \"./layer-mask.js\";\n\n/**\n * The project's layer names, resolved once from settings\n * (`docs/architecture/02-scene-graph.md` §7). Layers drive physics collision matrices and raycast\n * masks; files store layer **names**, never indices, so reordering the project list is safe.\n */\n\n/**\n * How many layer slots exist. One bit each, in a 32-bit mask.\n *\n * @public\n */\nexport const MAX_LAYERS = 32;\n\n/**\n * The names of the eight engine-reserved slots, in slot order. They always occupy slots 0–7,\n * whether or not the project lists them (`docs/architecture/02-scene-graph.md` §7).\n *\n * @public\n */\nexport const RESERVED_LAYER_NAMES: readonly string[] = Object.freeze([\n \"Default\",\n \"TransparentFX\",\n \"IgnoreRaycast\",\n \"Water\",\n \"UI\",\n \"Reserved5\",\n \"Reserved6\",\n \"Reserved7\",\n]);\n\n/**\n * The slot every entity starts on, and the fallback for an unknown name in a file.\n *\n * @public\n */\nexport const DEFAULT_LAYER = 0;\n\n/** The first slot a project-declared layer can occupy. */\nconst FIRST_USER_LAYER = 8;\n\n/**\n * The resolved mapping between layer names and the 32 layer slots.\n *\n * @remarks\n * How the project list is interpreted (the settings example in\n * `docs/architecture/04-extensions.md` §5 opens with `\"Default\"`, while\n * `docs/architecture/02-scene-graph.md` §7 reserves slots 0–7, so one rule has to reconcile the\n * two): the eight reserved names always occupy slots 0–7. A project entry that repeats a reserved\n * name keeps that reserved slot and consumes no user slot; every other entry takes the next free\n * slot from 8 upwards, in declaration order. A name declared twice is `IGX-0304`; more names than\n * slots is `IGX-0305`.\n *\n * @example\n * ```ts\n * const table = createLayerTable([\"Default\", \"Ground\", \"Player\"]);\n * table.indexOf(\"Ground\"); // 8\n * table.mask(\"Ground\", \"Player\").bits; // 0b1100000000\n * ```\n *\n * @public\n */\nexport class LayerTable {\n /** Name per slot; the empty string marks an unassigned user slot. */\n readonly #names: string[];\n\n /** Slot per name, for O(1) resolution at load and at mask construction. */\n readonly #indices: Map<string, number>;\n\n /**\n * Builds a table. Prefer {@link createLayerTable}, which is the documented entry point.\n *\n * @param names - The project's layer names in declaration order.\n * @throws IgnifxError with code `IGX-0304` on a duplicate name, or `IGX-0305` when the names do\n * not fit in the 32 slots.\n *\n * @internal\n */\n constructor(names: readonly string[]) {\n const slots: string[] = [];\n const indices = new Map<string, number>();\n for (let index = 0; index < MAX_LAYERS; index += 1) {\n const reserved = index < FIRST_USER_LAYER ? (RESERVED_LAYER_NAMES[index] ?? \"\") : \"\";\n slots.push(reserved);\n if (reserved !== \"\") {\n indices.set(reserved, index);\n }\n }\n let next = FIRST_USER_LAYER;\n for (let index = 0; index < names.length; index += 1) {\n const name = names[index] ?? \"\";\n if (name === \"\") {\n continue;\n }\n const existing = indices.get(name);\n if (existing !== undefined) {\n if (existing >= FIRST_USER_LAYER) {\n throw new IgnifxError(CoreErrorCode.duplicateLayerName, `The layer name ${name} is declared twice.`, {\n context: { layer: name, slot: existing },\n hint: \"Every layer name must be unique across the project list and the eight reserved names.\",\n });\n }\n continue;\n }\n if (next >= MAX_LAYERS) {\n throw new IgnifxError(\n CoreErrorCode.tooManyLayers,\n `The project declares more layers than the ${String(MAX_LAYERS)} slots allow.`,\n {\n context: { layer: name, limit: MAX_LAYERS - FIRST_USER_LAYER },\n hint: \"Slots 0-7 are reserved for engine defaults, leaving 24 for the project.\",\n },\n );\n }\n slots[next] = name;\n indices.set(name, next);\n next += 1;\n }\n this.#names = slots;\n this.#indices = indices;\n }\n\n /**\n * Every slot's name, indexed by slot. Unassigned user slots hold the empty string.\n *\n * @returns The 32 slot names.\n */\n get names(): readonly string[] {\n return this.#names;\n }\n\n /**\n * How many slots carry a name.\n *\n * @returns The count, always at least eight.\n */\n get count(): number {\n return this.#indices.size;\n }\n\n /**\n * Resolves a layer name to its slot.\n *\n * @param name - The layer name.\n * @returns The slot index, or `-1` when the project does not declare the name.\n */\n indexOf(name: string): number {\n return this.#indices.get(name) ?? -1;\n }\n\n /**\n * Resolves a layer name to its slot, requiring it to exist.\n *\n * @param name - The layer name.\n * @returns The slot index.\n * @throws IgnifxError with code `IGX-0303` when the project does not declare the name. Scene\n * loading* is more forgiving: an unknown name in a file resolves to `Default` with the same code\n * reported as a diagnostic (`docs/architecture/02-scene-graph.md` §7).\n */\n requireIndex(name: string): number {\n const index = this.#indices.get(name);\n if (index === undefined) {\n throw new IgnifxError(CoreErrorCode.unknownLayer, `${name} is not a layer declared in the project settings.`, {\n context: { layer: name },\n hint: \"Add it to `layers` in ignifx.config.ts, or use one of the reserved names.\",\n });\n }\n return index;\n }\n\n /**\n * The name of a slot.\n *\n * @param index - The slot index.\n * @returns The name, or `null` when the slot is out of range or unassigned.\n */\n nameOf(index: number): string | null {\n const name = this.#names[index];\n return name === undefined || name === \"\" ? null : name;\n }\n\n /**\n * Reports whether a name is declared.\n *\n * @param name - The layer name.\n * @returns `true` when the name resolves to a slot.\n */\n has(name: string): boolean {\n return this.#indices.has(name);\n }\n\n /**\n * Builds a mask from layer names — the ergonomic form scripts use, reached as\n * `world.layers.mask(\"Player\", \"Enemy\")`.\n *\n * @param names - The layer names to include.\n * @returns The mask.\n * @throws IgnifxError with code `IGX-0303` when a name is not declared.\n *\n * @example\n * ```ts\n * const hostiles = this.world.layers.mask(\"Enemy\", \"Projectile\");\n * if (hostiles.has(other.layer)) {\n * this.takeDamage();\n * }\n * ```\n */\n mask(...names: readonly string[]): LayerMask {\n return LayerMask.fromNames(this, names);\n }\n}\n\n/**\n * Resolves the project's layer names into a table.\n *\n * @param names - The `layers` project settings section, in declaration order.\n * @returns The resolved table.\n * @throws IgnifxError with code `IGX-0304` on a duplicate name, or `IGX-0305` when the names do not\n * fit in the 32 slots.\n *\n * @example\n * ```ts\n * const layers = createLayerTable([\"Default\", \"Ground\", \"Player\", \"Enemy\"]);\n * ```\n *\n * @public\n */\nexport function createLayerTable(names: readonly string[] = []): LayerTable {\n return new LayerTable(names);\n}\n\n/**\n * Checks that a number is a usable layer slot.\n *\n * @param layer - The candidate slot.\n * @returns `true` when the value is an integer in `[0, 31]`.\n *\n * @internal\n */\nexport function isValidLayer(layer: number): boolean {\n return Number.isInteger(layer) && layer >= 0 && layer < MAX_LAYERS;\n}\n","import type { FrameState } from \"../app/types.js\";\n\n/**\n * The writable half of {@link FrameState}. The scheduler owns one per app and hands it to the\n * world; the lifecycle queue brackets every callback with it, so `destroyImmediate` can refuse to\n * run inside a callback (`IGX-0102`) and so `awake` knows to run nested and synchronously\n * (`docs/architecture/01-lifecycle-and-time.md` §4, §6).\n *\n * @internal\n */\nexport interface FrameStateController {\n /** The read-only view handed to the world and to game-facing code. */\n readonly state: FrameState;\n /**\n * Marks the fixed loop as entered or left.\n *\n * @param value - `true` while `fixedUpdate` and physics run.\n */\n setInsideFixedStep(value: boolean): void;\n /** Enters a callback. Nests: the depth is what makes a callback inside a callback still count. */\n beginCallback(): void;\n /** Leaves a callback. */\n endCallback(): void;\n}\n\n/** The controller and the state it exposes, in one object so no closure is allocated per call. */\nclass FrameStateImpl implements FrameStateController, FrameState {\n #callbackDepth = 0;\n\n #insideFixedStep = false;\n\n get state(): FrameState {\n return this;\n }\n\n get isInsideCallback(): boolean {\n return this.#callbackDepth > 0;\n }\n\n get isInsideFixedStep(): boolean {\n return this.#insideFixedStep;\n }\n\n setInsideFixedStep(value: boolean): void {\n this.#insideFixedStep = value;\n }\n\n beginCallback(): void {\n this.#callbackDepth += 1;\n }\n\n endCallback(): void {\n if (this.#callbackDepth > 0) {\n this.#callbackDepth -= 1;\n }\n }\n}\n\n/**\n * Creates the frame-state controller for one app.\n *\n * @returns A controller whose `state` reports \"outside any callback, outside the fixed loop\".\n *\n * @example\n * ```ts\n * const frameState = createFrameState();\n * const world = createWorld({ app, scene, frameState, layers });\n * ```\n *\n * @internal\n */\nexport function createFrameState(): FrameStateController {\n return new FrameStateImpl();\n}\n","/**\n * A canvas ignifx can render into: a DOM canvas on the main thread, or an `OffscreenCanvas`\n * transferred to a worker. Declared here so public signatures do not depend on a Babylon Lite type.\n *\n * @public\n */\nexport type RenderSurface = HTMLCanvasElement | OffscreenCanvas;\n\n/**\n * Reports whether the current environment exposes a WebGPU entry point. This is a capability probe\n * only: it does not request an adapter, so it never blocks and never allocates GPU resources.\n * ignifx is WebGPU-only (`CONSTITUTION.md` §1.1), so this is the gate every renderer path runs first.\n *\n * @returns `true` when `navigator.gpu` is present.\n *\n * @example\n * ```ts\n * if (!isWebGpuAvailable()) {\n * showWebGpuUnsupportedPage();\n * }\n * ```\n *\n * @public\n */\nexport function isWebGpuAvailable(): boolean {\n // `@webgpu/types` declares `navigator.gpu` as always present, so a `!== undefined` check would be\n // statically dead. Probing with `in` reflects what Node and pre-WebGPU browsers actually expose\n // and needs no type assertion (coding standards §5.2).\n return typeof navigator !== \"undefined\" && \"gpu\" in navigator;\n}\n","import { addTask, createCopyToTextureTask, createRenderTarget, createRenderTask } from \"@babylonjs/lite\";\nimport type { EngineContext, RenderTarget, SceneContext, Task } from \"@babylonjs/lite\";\n\n/**\n * The offscreen render path (`docs/architecture/07-rendering.md` §2.7): the frame graph a scene gets\n * when the project declares `rendering.features.postProcessing`.\n *\n * Everything here needs a device.\n *\n * ## Why the default render task is not good enough\n *\n * `createSceneContext` appends a task named `\"scene\"` that draws straight into the surface's\n * swapchain target — `surface.scRT` for a single-sample surface, or an MSAA colour target that\n * resolves into `scRT` (`lib/scene/scene-core.js` 74-79). Either way the scene's colour ends up in\n * the swapchain texture, and a post-process pass cannot read it: `createSurface` configures the\n * canvas context with no `usage` (`lib/engine/surface.js` 30), so the swapchain texture is\n * `RENDER_ATTACHMENT` only. Binding it as a sampled texture fails WebGPU validation, the whole\n * frame's command buffer is rejected, and the page presents black. That is exactly what the Phase 2\n * visual suite measured, and it is why this module exists.\n *\n * Lite offers no way to retarget the default task after the fact — `RenderTaskConfig.rt` is read\n * when the task is created, and `FrameGraph`'s public surface is only `build`/`execute`/`dispose`\n * (`index.d.ts` 5367). So the scene is created with `defaultRenderTask: false` and this module\n * builds the replacement.\n *\n * ## The graph it builds\n *\n * ```text\n * [shadow] → scene ──→ sceneColor ──→ present ──→ swapchain\n * └─ (a PostProcessStack appends its effects here, and disables present)\n * ```\n *\n * - `scene` is a normal `createRenderTask`. With MSAA it draws into a multisampled colour target\n * that owns its depth and resolves into `sceneColor` through `rst`; without MSAA it draws into\n * `sceneColor` directly with a separate depth target, which is the same split Lite's own default\n * uses (`RenderTaskConfig.depth`, `index.d.ts` 9782).\n * - `sceneColor` is an ordinary `createRenderTarget`, so `buildRenderTarget` allocates it with\n * `RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC | COPY_DST` (`lib/engine/render-target.js`) —\n * the `TEXTURE_BINDING` the swapchain lacks.\n * - `present` is a `createCopyToTextureTask` from `sceneColor` to the swapchain. Copying *into* the\n * swapchain is supported and takes the blit path (`lib/frame-graph/copy-to-texture-task.js`,\n * `swapAsView`); copying *out of* it is refused (Lite error 80), which is the same limit stated\n * from the other side.\n * - The swapchain is written every frame whatever else happens: with no chain, `present` does it;\n * with a chain, the chain's last effect does it and `present` is switched off\n * ({@link ScenePresenter.setPresentEnabled}).\n *\n * ## Resize\n *\n * Every target here is sized by passing the **surface** as `RenderTargetDescriptor.size`, which\n * `resolveSize` re-reads from `canvas.width`/`canvas.height` on every `buildRenderTarget`\n * (`lib/engine/render-target.js`). A surface resize calls the scene's `_resize`, which is\n * `frameGraph.build()` (`lib/scene/scene-core.js` 67-68): every target is reallocated at the new\n * size and every task re-records, which is also what refreshes the bind groups that captured the old\n * texture views. Nothing here has to observe the canvas itself, and nothing is eagerly allocated —\n * `createRenderTargetTexture` would be, and Lite rejects a surface as its size for exactly that\n * reason.\n */\n\n/** The depth/stencil format Lite's own default render task uses (`lib/scene/scene-core.js` 76-77). */\nconst DEPTH_STENCIL_FORMAT: GPUTextureFormat = \"depth24plus-stencil8\";\n\n/**\n * A scene's offscreen render path: the colour a `PostProcessStack` reads, and the compositing blit\n * it takes over from.\n *\n * @internal\n */\nexport interface ScenePresenter {\n /**\n * The single-sample colour target the scene ends up in — resolved when MSAA is on. It carries\n * `TEXTURE_BINDING`, so it is a legal `sourceTexture` for a post-process task.\n */\n readonly sceneColor: RenderTarget;\n /** The surface's swapchain target, where the last pass of the frame has to land. */\n readonly swapchain: RenderTarget;\n /**\n * Switches the compositing blit on or off.\n *\n * @param enabled - `false` while an effect chain writes the swapchain itself.\n */\n setPresentEnabled(enabled: boolean): void;\n /** Whether the compositing blit currently runs. */\n readonly isPresentEnabled: boolean;\n}\n\n/**\n * Builds the scene's render task into an offscreen target and the blit that composites it, and\n * appends both to the scene's frame graph.\n *\n * @remarks\n * Call it immediately after `createSceneContext(engine, { defaultRenderTask: false })` and before\n * `registerScene`: `addTask` appends, so calling it first is what puts `\"scene\"` ahead of everything\n * a feature adds later, and `registerSceneWithShadowSupport` still unshifts its own `\"shadow\"` task\n * in front of both.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The scene created with no default render task.\n * @returns The presenter a `PostProcessStack` builds its chain against.\n *\n * @example\n * ```ts\n * const scene = createSceneContext(engine, { defaultRenderTask: false });\n * const presenter = installOffscreenRenderPath(engine, scene);\n * ```\n *\n * @internal\n */\nexport function installOffscreenRenderPath(engine: EngineContext, scene: SceneContext): ScenePresenter {\n const isMultisampled = engine.msaaSamples > 1;\n const sceneColor = createRenderTarget({\n lbl: \"ignifx:scene-color\",\n format: engine.format,\n samples: 1,\n size: engine,\n });\n const colorTarget = isMultisampled\n ? createRenderTarget({\n lbl: \"ignifx:scene-color-msaa\",\n format: engine.format,\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: engine.msaaSamples,\n size: engine,\n })\n : sceneColor;\n const config: {\n name: string;\n rt: RenderTarget;\n rst?: RenderTarget;\n depth?: RenderTarget;\n } = { name: \"scene\", rt: colorTarget };\n if (isMultisampled) {\n config.rst = sceneColor;\n } else {\n // A colour target that carries no `dFormat` allocates no depth of its own, so the pass needs a\n // separate one — the arrangement Lite's own single-sample default task uses.\n config.depth = createRenderTarget({\n lbl: \"ignifx:scene-depth\",\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: 1,\n size: engine,\n });\n }\n addTask(scene, createRenderTask(config, engine, scene));\n\n const present: Task = createCopyToTextureTask(\n { name: \"ignifx:present\", sourceTexture: sceneColor, targetTexture: engine.scRT },\n engine,\n scene,\n );\n addTask(scene, present);\n\n let isPresentEnabled = true;\n return {\n sceneColor,\n swapchain: engine.scRT,\n setPresentEnabled(enabled: boolean): void {\n isPresentEnabled = enabled;\n present.executionEnabled = enabled;\n },\n get isPresentEnabled(): boolean {\n return isPresentEnabled;\n },\n };\n}\n","import { createEngine, disposeEngine } from \"@babylonjs/lite\";\nimport type { LiteEngine } from \"./scene.js\";\nimport type { RenderSurface } from \"../platform/webgpu.js\";\nimport type { EngineOptions } from \"@babylonjs/lite\";\n\n/**\n * The GPU half of the Babylon Lite adapter: the two calls that need a real WebGPU device. They are\n * unreachable from Node, so this file is the one the root Vitest coverage config excludes\n * (`vitest.config.ts`); everything the null engine can exercise lives in `./engine.ts`,\n * `./scene.ts`, `./loop.ts`, and `./node.ts`.\n *\n * Coverage comes from the Vitest `browser` project (`*.browser.test.ts`) instead.\n */\n\n/**\n * Creates a Babylon Lite WebGPU engine bound to a canvas.\n *\n * @remarks\n * The WebGPU capability gate runs in `./engine.ts` *before* this is called, so an unsupported\n * browser produces `IGX-0701` rather than an opaque Lite failure (`CONSTITUTION.md` §1.1).\n *\n * @param canvas - The canvas or offscreen canvas to render into.\n * @param options - Device and surface options, mapped from the ignifx renderer block by\n * `toLiteEngineOptions` in `./render-diagnostics.ts`. Omit them for Lite's own defaults (4x MSAA,\n * opaque, unclamped device pixel ratio).\n * @returns The engine. Lite's engine is also its primary surface.\n *\n * @internal\n */\nexport async function createWebGpuEngine(canvas: RenderSurface, options?: EngineOptions): Promise<LiteEngine> {\n return createEngine(canvas, options);\n}\n\n/**\n * Releases a WebGPU engine and the device behind it.\n *\n * @remarks\n * Only ever called for a WebGPU engine: `disposeEngine` unconditionally reaches for\n * `surface._context` and `engine._device`, neither of which a null engine has, so calling it on one\n * throws (ADR-0009 Validation). The headless path disposes its scene and stops there.\n *\n * @param engine - The engine to release.\n *\n * @internal\n */\nexport function disposeWebGpuEngine(engine: LiteEngine): void {\n disposeEngine(engine);\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { isWebGpuAvailable } from \"../platform/webgpu.js\";\nimport { installOffscreenRenderPath } from \"./gpu/render-path.js\";\nimport { createWebGpuEngine, disposeWebGpuEngine } from \"./render.js\";\nimport { createHeadlessScene, createRenderScene, disposeSceneOnly } from \"./scene.js\";\nimport type { ScenePresenter } from \"./gpu/render-path.js\";\nimport type { LiteEngine, LiteScene } from \"./scene.js\";\nimport type { RenderSurface } from \"../platform/webgpu.js\";\nimport type { EngineOptions } from \"@babylonjs/lite\";\n\n/**\n * The engine/scene pair an app is built on, and the WebGPU capability gate in front of it\n * (`docs/architecture/01-lifecycle-and-time.md` §1, ADR-0001, ADR-0009). This is what `createApp`\n * calls; it is the only place that decides between the null engine and a real device.\n *\n * Everything here is `@internal`; the app exposes the objects through its documented `.lite`\n * escape hatch and nothing else.\n */\n\n/** A Lite engine and the scene a world renders into. */\nexport interface EngineHandles {\n /** The engine: a WebGPU engine, or Lite's null engine in headless mode. */\n readonly engine: LiteEngine;\n /** The scene the world's entities live in. */\n readonly scene: LiteScene;\n /** `true` when the engine is the null engine and there is nothing to present to. */\n readonly isHeadless: boolean;\n /**\n * The offscreen render path, when the project declared `rendering.features.postProcessing`;\n * `null` when the scene renders straight into the swapchain the way Lite does by default.\n */\n readonly presenter: ScenePresenter | null;\n}\n\n/**\n * Refuses to continue when the host has no WebGPU entry point. ignifx renders only through WebGPU\n * (`CONSTITUTION.md` §1.1), so this is the gate every rendering path runs first.\n *\n * @throws IgnifxError with code `IGX-0701` when `navigator.gpu` is absent.\n *\n * @internal\n */\nexport function assertWebGpuAvailable(): void {\n if (isWebGpuAvailable()) {\n return;\n }\n throw new IgnifxError(CoreErrorCode.webGpuUnavailable, \"WebGPU is not available in this environment.\", {\n hint: \"Check isWebGpuAvailable() before calling createApp({ canvas }), or run headless instead.\",\n });\n}\n\n/**\n * Builds the null engine and the scene a headless app runs on\n * (`docs/architecture/01-lifecycle-and-time.md` §8): components that wrap Lite objects still\n * construct, and no GPU work is ever recorded.\n *\n * @returns The engine and scene, marked headless.\n *\n * @example\n * ```ts\n * const handles = createHeadlessEngine();\n * disposeEngineHandles(handles);\n * ```\n *\n * @internal\n */\nexport function createHeadlessEngine(): EngineHandles {\n const headless = createHeadlessScene();\n return { engine: headless.engine, scene: headless.scene, isHeadless: true, presenter: null };\n}\n\n/**\n * Builds a WebGPU engine bound to a canvas and the render scene a world draws into.\n *\n * @remarks\n * `postProcessing` is decided here rather than in `app.start()` with the other rendering features,\n * because it chooses between two frame graphs and a frame graph is built inside `createSceneContext`\n * (`./gpu/render-path.ts`). Everything else about it — the `PostProcessStack` component, the\n * `IGX-0710` guard — hangs off that one decision.\n *\n * @param canvas - The canvas or offscreen canvas to render into.\n * @param options - Device and surface options; see `createWebGpuEngine`.\n * @param features - Which render path to build.\n * @param features.postProcessing - `true` to render into an offscreen target and composite it.\n * @returns The engine, the scene, and the presenter when there is one.\n * @throws IgnifxError with code `IGX-0701` when WebGPU is unavailable.\n *\n * @internal\n */\nexport async function createRenderEngine(\n canvas: RenderSurface,\n options?: EngineOptions,\n features?: { readonly postProcessing?: boolean },\n): Promise<EngineHandles> {\n assertWebGpuAvailable();\n const engine = await createWebGpuEngine(canvas, options);\n const offscreen = features?.postProcessing === true;\n const scene = createRenderScene(engine, { offscreen });\n return {\n engine,\n scene,\n isHeadless: false,\n presenter: offscreen ? installOffscreenRenderPath(engine, scene) : null,\n };\n}\n\n/**\n * Releases an engine and its scene, in the order `docs/architecture/07-rendering.md` §7 requires:\n * the scene first, the engine last.\n *\n * @remarks\n * A null engine is never handed to `disposeEngine`: it owns no `_context` and no `_device`, and\n * Lite's disposer reaches for both (ADR-0009 Validation). Disposing its scene is the complete\n * teardown.\n *\n * @param handles - What {@link createHeadlessEngine} or {@link createRenderEngine} returned.\n *\n * @internal\n */\nexport function disposeEngineHandles(handles: EngineHandles): void {\n disposeSceneOnly(handles.scene);\n if (!handles.isHeadless) {\n disposeWebGpuEngine(handles.engine);\n }\n}\n","import { enableDeviceLostSceneRecovery, forceWebGpuDeviceLossForTesting } from \"@babylonjs/lite\";\nimport type { DeviceLostRecoveryCallbacks, DeviceLostRecoveryHandle, EngineContext } from \"@babylonjs/lite\";\n\n/**\n * Device-loss recovery (`docs/architecture/07-rendering.md` §4). Enabling it reads the current\n * device's feature list immediately, so this module is GPU-only.\n *\n * Everything here is `@internal`.\n *\n * ## Why it must be enabled first (verified against `@babylonjs/lite@1.27.0`)\n *\n * `enableDeviceLostSceneRecovery(engine, callbacks)` (`index.d.ts` 4367) registers a recovery\n * strategy and calls `_retainDeviceLostRecoveryCapture(engine, true)`\n * (`lib/engine/device-lost-scene-recovery.js`). That capture is what stamps a *recovery source* —\n * the URL, bitmap, or pixel array a texture came from — onto every texture created **after** it is\n * installed (`lib/engine/device-lost-recovery-capture.js`). Resources created before it therefore\n * have no source to rebuild from, which is why `docs/architecture/07-rendering.md` §4 requires the\n * call before any resource exists, and why `createApp` makes it before the first scene is built.\n *\n * Two more facts from `lib/engine/device-lost-recovery.js`:\n *\n * - The very first registration snapshots `engine._device.features`, so the replacement device is\n * requested with the same feature set.\n * - A `\"destroyed\"` loss is ignored unless {@link forceDeviceLossForTesting} armed it. That is what\n * keeps `disposeEngine` from looking like a crash — and it is why forcing a loss without an\n * enabled recovery strategy throws instead of silently doing nothing.\n */\n\n/**\n * Enables best-effort recovery for every scene registered on an engine.\n *\n * @remarks\n * Call before creating any resource. Every kind of rendering context registered at loss time needs\n * its own strategy — the 2D and UI extensions enable the sprite and text ones — or recovery fails\n * rather than leave a context bound to the lost device.\n *\n * @param engine - The engine to protect.\n * @param callbacks - Fired on loss, on successful recovery, and on failure.\n * @returns A handle whose `disable()` removes this registration. Idempotent.\n *\n * @example\n * ```ts\n * const recovery = enableSceneDeviceLossRecovery(engine, {\n * onLost: () => app.events.onDeviceLost.emit(),\n * onRecovered: () => app.events.onDeviceRecovered.emit(),\n * });\n * ```\n *\n * @internal\n */\nexport function enableSceneDeviceLossRecovery(\n engine: EngineContext,\n callbacks: DeviceLostRecoveryCallbacks,\n): DeviceLostRecoveryHandle {\n return enableDeviceLostSceneRecovery(engine, callbacks);\n}\n\n/**\n * Destroys the engine's device in a way that looks like a real loss, so recovery runs.\n *\n * @remarks\n * Test-only. It throws when no recovery strategy is enabled on the engine\n * (`lib/engine/device-lost-recovery-testing.js`).\n *\n * @param engine - The engine to break.\n *\n * @internal\n */\nexport function forceDeviceLossForTesting(engine: EngineContext): void {\n forceWebGpuDeviceLossForTesting(engine);\n}\n","import {\n onBeforeRender,\n registerScene,\n startEngine,\n stepScene,\n stopEngine,\n type EngineContext,\n type SceneContext,\n} from \"@babylonjs/lite\";\n\n/**\n * Frame-driving half of the Babylon Lite adapter: the one before-render callback ignifx registers\n * per world, the headless step, and the browser render loop\n * (`docs/architecture/01-lifecycle-and-time.md` §1, ADR-0003).\n *\n * Everything here is `@internal`; the kernel's `App` is the public surface.\n *\n * ## What Lite does with a before-render callback (verified against `@babylonjs/lite@1.27.0`\n * `lib/scene/scene-core.js` and `lib/engine/null-engine.js`)\n *\n * - `onBeforeRender(scene, cb)` is `scene._beforeRender.unshift(cb)` and the list is walked\n * front-to-back, so **callbacks registered later run earlier**. Everything Lite registers itself\n * — the Havok step in `createHavokWorld`, sprite animation, flow graphs — also unshifts, so the\n * rule is uniform: last registration wins the front of the frame.\n * - There is no unregister function. Lite's own subscribers keep a private closure over\n * `_beforeRender` and splice themselves out; the public API exposes nothing, which is why\n * {@link registerFrameCallback} returns a handle guarding a flag instead (ADR-0003).\n * - The delta a callback receives is `scene.fixedDeltaMs > 0 ? scene.fixedDeltaMs :\n * engine._currentDelta`, and `stepScene(engine, scene, deltaMs)` is exactly\n * `engine._currentDelta = deltaMs; scene._update()`. ignifx leaves `fixedDeltaMs` at its default\n * of `0`, so the value {@link runFrame} converts is the value the callback receives, bit for bit.\n */\n\n/** Milliseconds in one second; the only unit conversion this adapter performs (00 §4). */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * The registration returned by {@link registerFrameCallback}. Lite cannot unregister a before-render\n * callback, so the wrapper it holds forever consults this handle and becomes a no-op once\n * {@link unregisterFrameCallback} has run.\n *\n * @internal\n */\nexport interface FrameCallbackHandle {\n /** Whether the wrapper still forwards frames to the callback. */\n readonly isActive: boolean;\n}\n\n/** The same handle from inside this module, where the flag is writable. */\ninterface MutableFrameCallbackHandle {\n /** Whether the wrapper still forwards frames to the callback. */\n isActive: boolean;\n}\n\n/**\n * Registers the **one** Lite before-render callback a world owns\n * (`docs/architecture/01-lifecycle-and-time.md` §1). The whole ignifx frame runs inside it.\n *\n * @remarks\n * Because Lite runs later registrations first, the world registers after every extension has\n * finished `register()` and before `startEngine`, which puts the ignifx frame at the front of the\n * scene's callback list. Extensions never call this themselves.\n *\n * @param scene - The scene to drive; for a world that is the render scene.\n * @param callback - Receives the frame delta **in milliseconds**, exactly as Lite delivers it.\n * @returns A handle that can deactivate the callback.\n *\n * @example\n * ```ts\n * const handle = registerFrameCallback(scene, (deltaMs) => runIgnifxFrame(deltaMs / 1000));\n * unregisterFrameCallback(handle); // the Lite-held closure survives but does nothing\n * ```\n *\n * @internal\n */\nexport function registerFrameCallback(scene: SceneContext, callback: (deltaMs: number) => void): FrameCallbackHandle {\n const handle: MutableFrameCallbackHandle = { isActive: true };\n onBeforeRender(scene, (deltaMs: number): void => {\n if (handle.isActive) {\n callback(deltaMs);\n }\n });\n return handle;\n}\n\n/**\n * Deactivates a frame callback. The closure Lite holds stays in `scene._beforeRender` for the life\n * of the scene — Lite offers no way to remove it — but it stops calling through, so the only\n * residue is one predictable branch per frame. Calling this twice is a no-op.\n *\n * @param handle - A handle from {@link registerFrameCallback}.\n *\n * @internal\n */\nexport function unregisterFrameCallback(handle: FrameCallbackHandle): void {\n // The public type keeps the flag read-only so nothing outside this module can flip it; readonly\n // does not affect assignability, so no type assertion is needed to widen it here.\n const mutable: MutableFrameCallbackHandle = handle;\n mutable.isActive = false;\n}\n\n/**\n * Runs one frame of a scene headlessly: converts ignifx seconds to Lite milliseconds and fires the\n * scene's before-render callbacks. No GPU work is recorded or submitted.\n *\n * @remarks\n * This is the headless driver behind `app.step(deltaSeconds)`\n * (`docs/architecture/01-lifecycle-and-time.md` §8) and the driver ignifx uses for the physics\n * simulation scene in every mode (ADR-0003). The delta arrives at the callback unchanged, so\n * `runFrame(engine, scene, 1 / 60)` delivers exactly `1000 / 60` — the two are the same double.\n * That holds only while `scene.fixedDeltaMs` is `0`, its default; setting it makes Lite ignore the\n * step delta entirely, so ignifx never touches it.\n *\n * @param engine - The engine that owns the scene; a null engine in headless mode.\n * @param scene - The scene to advance.\n * @param deltaSeconds - The step length in seconds.\n *\n * @internal\n */\nexport function runFrame(engine: EngineContext, scene: SceneContext, deltaSeconds: number): void {\n stepScene(engine, scene, deltaSeconds * MILLISECONDS_PER_SECOND);\n}\n\n/**\n * Starts Lite's requestAnimationFrame render loop: registers the scene with the engine, then starts\n * the engine. Resolves once the first frame has been rendered.\n *\n * @remarks\n * Browser and Electron only — a null engine has no render loop, and headless mode calls\n * {@link runFrame} instead. Every frame callback must already be registered when this is called;\n * scenes registered later join on subsequent frames.\n *\n * @param engine - The WebGPU engine to start.\n * @param scene - The scene to register before the first frame.\n *\n * @internal\n */\nexport async function startRenderLoop(engine: EngineContext, scene: SceneContext): Promise<void> {\n await registerScene(scene);\n await startEngine(engine);\n}\n\n/**\n * Starts Lite's requestAnimationFrame render loop on a scene that is **already** registered.\n *\n * @remarks\n * {@link startRenderLoop} registers the scene for you, which is the right call for a test harness.\n * An app cannot use it: `docs/architecture/07-rendering.md` §1 and §1.1 require the feature opt-ins\n * and the material warm-up to happen before registration, and registration itself has to choose\n * between `registerScene` and `registerSceneWithShadowSupport`. `app.start()` therefore calls\n * `registerRenderScene` from `./render-features.ts` itself and then this.\n *\n * @param engine - The WebGPU engine to start.\n * @returns A promise that resolves once the first frame has been rendered.\n *\n * @internal\n */\nexport async function startEngineLoop(engine: EngineContext): Promise<void> {\n await startEngine(engine);\n}\n\n/**\n * Stops Lite's render loop. Safe to call when the loop is not running.\n *\n * @param engine - The engine whose loop should stop.\n *\n * @internal\n */\nexport function stopRenderLoop(engine: EngineContext): void {\n stopEngine(engine);\n}\n","/**\n * Severity levels and the record shape the logging sinks receive\n * (`docs/architecture/15-devtools-and-diagnostics.md` §2).\n */\n\n/**\n * The severity of a log record.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const LogLevel = {\n /** Verbose engine tracing; off by default. */\n debug: \"debug\",\n /** Lifecycle milestones a developer wants to see once. */\n info: \"info\",\n /** Something is wrong but the frame continues. */\n warn: \"warn\",\n /** Something failed; usually paired with an `app.onError` report. */\n error: \"error\",\n} as const;\n\n/**\n * The union of the four severities a {@link LogRecord} can carry.\n *\n * @public\n */\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n\n/**\n * What a {@link Logger} is set to. A threshold is a `LogLevel` or `\"silent\"`, which drops\n * everything; `\"silent\"` is never the level of a record.\n *\n * @public\n */\nexport type LogThreshold = LogLevel | \"silent\";\n\n/**\n * The numeric severity of each threshold. A record is written when its level's severity is greater\n * than or equal to the logger's threshold severity, which is why `\"silent\"` sits above `\"error\"`.\n *\n * @public\n */\nexport const LOG_LEVEL_SEVERITY: Readonly<Record<LogThreshold, number>> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n silent: 50,\n};\n\n/**\n * One line of log output, as handed to a {@link LogSink}.\n *\n * @public\n */\nexport interface LogRecord {\n /** The severity of the line. */\n readonly level: LogLevel;\n /** The dotted scope of the logger that produced it, or `null` for the root logger. */\n readonly scope: string | null;\n /** The human-readable message. */\n readonly message: string;\n /** Structured extras passed after the message. Empty when there were none. */\n readonly data: readonly unknown[];\n /** The logger clock's reading when the line was produced, in milliseconds. */\n readonly timeMs: number;\n}\n\n/**\n * Where log records go: the console, a devtools panel, a file in Electron, or an in-memory buffer\n * in tests. A sink is passed to {@link createLogger} and is never discovered globally.\n *\n * @public\n */\nexport interface LogSink {\n /**\n * Writes one record. Called synchronously from the logging call site, so implementations must be\n * cheap and must not throw.\n *\n * @param record - The record to write.\n */\n write(record: LogRecord): void;\n}\n","// oxlint-disable no-console -- Coding standards §5.5 and §6 (`ignifx/no-console`): this file *is*\n// the console sink. It is the single place in `src/` allowed to touch the host console; every other\n// module logs through `app.log` / `ctx.log`.\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport { LogLevel, type LogRecord, type LogSink } from \"./log-level.js\";\n\n/**\n * The part of the host `console` a {@link LogSink} needs. Declaring it keeps the sink testable and\n * keeps ignifx off the DOM `Console` type, which Node's console does not implement in full.\n *\n * @public\n */\nexport interface ConsoleLike {\n /**\n * Writes a debug line.\n *\n * @param data - The message followed by its structured extras.\n */\n debug(...data: readonly unknown[]): void;\n\n /**\n * Writes an info line.\n *\n * @param data - The message followed by its structured extras.\n */\n info(...data: readonly unknown[]): void;\n\n /**\n * Writes a warning line.\n *\n * @param data - The message followed by its structured extras.\n */\n warn(...data: readonly unknown[]): void;\n\n /**\n * Writes an error line.\n *\n * @param data - The message followed by its structured extras.\n */\n error(...data: readonly unknown[]): void;\n}\n\n/**\n * Options for {@link createConsoleSink}.\n *\n * @public\n */\nexport interface ConsoleSinkOptions {\n /** The console to write to. Defaults to the host `console`. */\n readonly target?: ConsoleLike;\n}\n\n/**\n * Creates the default log sink: one console line per record, prefixed with the logger scope and\n * routed to the console method matching the record's level.\n *\n * @param options - An alternative console, for tests and for the Electron main process.\n * @returns A sink for {@link createLogger}.\n *\n * @example\n * ```ts\n * const log = createLogger({ sink: createConsoleSink(), level: \"warn\" });\n * ```\n *\n * @public\n */\nexport function createConsoleSink(options?: ConsoleSinkOptions): LogSink {\n const target: ConsoleLike = options?.target ?? console;\n return {\n write(record: LogRecord): void {\n const text = record.scope === null ? record.message : `[${record.scope}] ${record.message}`;\n switch (record.level) {\n case LogLevel.debug:\n target.debug(text, ...record.data);\n return;\n case LogLevel.info:\n target.info(text, ...record.data);\n return;\n case LogLevel.warn:\n target.warn(text, ...record.data);\n return;\n case LogLevel.error:\n target.error(text, ...record.data);\n return;\n default:\n assertNever(record.level, \"log level\");\n }\n },\n };\n}\n","import { LOG_LEVEL_SEVERITY, LogLevel, type LogRecord, type LogSink, type LogThreshold } from \"./log-level.js\";\n\n/**\n * The logging front end reached as `app.log` and, per extension, as `ctx.log`\n * (`docs/architecture/15-devtools-and-diagnostics.md` §2).\n *\n * @remarks\n * Calls below the current threshold return before any record is built, so a disabled `debug()` costs\n * one numeric comparison. The rest parameter itself is still materialised by the JavaScript engine,\n * so per-frame call sites guard with {@link Logger.isEnabled} instead (coding standards §7).\n *\n * @example\n * ```ts\n * const log = app.log.child(\"physics\");\n * log.info(\"stepping at {hz}Hz\", 60);\n * if (log.isEnabled(\"debug\")) {\n * log.debug(\"contacts\", collectContacts());\n * }\n * ```\n *\n * @public\n */\nexport interface Logger {\n /** The threshold below which records are dropped. Shared with every child logger. */\n readonly level: LogThreshold;\n\n /** The dotted scope prefix of this logger, or `null` for the root. */\n readonly scope: string | null;\n\n /**\n * Reports whether a record at this level would be written.\n *\n * @param level - The level to test.\n * @returns `true` when the level passes the current threshold.\n */\n isEnabled(level: LogLevel): boolean;\n\n /**\n * Raises or lowers the threshold for this logger, its parents, and its children — they share one\n * setting so devtools can turn `debug` on for the whole app at once.\n *\n * @param level - The new threshold.\n */\n setLevel(level: LogThreshold): void;\n\n /**\n * Writes a `debug` record.\n *\n * @param message - The message.\n * @param data - Structured extras.\n */\n debug(message: string, ...data: readonly unknown[]): void;\n\n /**\n * Writes an `info` record.\n *\n * @param message - The message.\n * @param data - Structured extras.\n */\n info(message: string, ...data: readonly unknown[]): void;\n\n /**\n * Writes a `warn` record.\n *\n * @param message - The message.\n * @param data - Structured extras.\n */\n warn(message: string, ...data: readonly unknown[]): void;\n\n /**\n * Writes an `error` record.\n *\n * @param message - The message.\n * @param data - Structured extras.\n */\n error(message: string, ...data: readonly unknown[]): void;\n\n /**\n * Writes a `warn` record the first time this key is seen and drops every later call with the same\n * key. This is the rate limiter for warnings that would otherwise repeat every frame.\n *\n * @param key - The de-duplication key, scoped to this logger's scope.\n * @param message - The message, used on the first call only.\n * @param data - Structured extras, used on the first call only.\n */\n warnOnce(key: string, message: string, ...data: readonly unknown[]): void;\n\n /**\n * Creates a logger that prefixes its records with an additional scope segment and shares this\n * logger's sink, threshold, clock, and `warnOnce` memory.\n *\n * @param scope - The segment to append, for example `\"physics\"`.\n * @returns The scoped logger.\n */\n child(scope: string): Logger;\n}\n\n/**\n * Options for {@link createLogger}.\n *\n * @public\n */\nexport interface LoggerOptions {\n /** Where records go. */\n readonly sink: LogSink;\n /** The initial threshold. Defaults to `\"info\"`. */\n readonly level?: LogThreshold;\n /** The root scope. Defaults to `null`. */\n readonly scope?: string | null;\n /**\n * The clock used for {@link LogRecord.timeMs}. Defaults to `performance.now` when the host has\n * it and `Date.now` otherwise; tests pass a counter so records are deterministic.\n */\n readonly now?: () => number;\n}\n\n/** State every logger in one tree shares, so `setLevel` on any of them moves all of them. */\ninterface LoggerState {\n readonly sink: LogSink;\n readonly now: () => number;\n readonly seen: Set<string>;\n level: LogThreshold;\n threshold: number;\n}\n\n/** The separator between scope segments. */\nconst SCOPE_SEPARATOR = \".\";\n\n/**\n * Picks the default clock: the high-resolution monotonic one when the host exposes it.\n *\n * @returns A function returning milliseconds.\n */\nfunction defaultNow(): () => number {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return () => performance.now();\n }\n return () => Date.now();\n}\n\nclass LoggerImpl implements Logger {\n readonly #state: LoggerState;\n readonly #scope: string | null;\n\n constructor(state: LoggerState, scope: string | null) {\n this.#state = state;\n this.#scope = scope;\n }\n\n get level(): LogThreshold {\n return this.#state.level;\n }\n\n get scope(): string | null {\n return this.#scope;\n }\n\n isEnabled(level: LogLevel): boolean {\n return LOG_LEVEL_SEVERITY[level] >= this.#state.threshold;\n }\n\n setLevel(level: LogThreshold): void {\n this.#state.level = level;\n this.#state.threshold = LOG_LEVEL_SEVERITY[level];\n }\n\n debug(message: string, ...data: readonly unknown[]): void {\n this.#write(LogLevel.debug, message, data);\n }\n\n info(message: string, ...data: readonly unknown[]): void {\n this.#write(LogLevel.info, message, data);\n }\n\n warn(message: string, ...data: readonly unknown[]): void {\n this.#write(LogLevel.warn, message, data);\n }\n\n error(message: string, ...data: readonly unknown[]): void {\n this.#write(LogLevel.error, message, data);\n }\n\n warnOnce(key: string, message: string, ...data: readonly unknown[]): void {\n const scopedKey = this.#scope === null ? key : `${this.#scope}${SCOPE_SEPARATOR}${key}`;\n if (this.#state.seen.has(scopedKey)) {\n return;\n }\n this.#state.seen.add(scopedKey);\n this.#write(LogLevel.warn, message, data);\n }\n\n child(scope: string): Logger {\n const nested = this.#scope === null ? scope : `${this.#scope}${SCOPE_SEPARATOR}${scope}`;\n return new LoggerImpl(this.#state, nested);\n }\n\n #write(level: LogLevel, message: string, data: readonly unknown[]): void {\n if (LOG_LEVEL_SEVERITY[level] < this.#state.threshold) {\n return;\n }\n const record: LogRecord = {\n level,\n scope: this.#scope,\n message,\n data,\n timeMs: this.#state.now(),\n };\n this.#state.sink.write(record);\n }\n}\n\n/**\n * Creates the root logger of one app.\n *\n * @param options - The sink, and optionally the threshold, root scope, and clock.\n * @returns The root logger; call {@link Logger.child} for scoped loggers.\n *\n * @example\n * ```ts\n * const log = createLogger({ sink: createConsoleSink(), level: \"debug\" });\n * log.child(\"assets\").warnOnce(\"missing-atlas\", \"No atlas for sprite {id}.\");\n * ```\n *\n * @public\n */\nexport function createLogger(options: LoggerOptions): Logger {\n const level = options.level ?? LogLevel.info;\n const state: LoggerState = {\n sink: options.sink,\n now: options.now ?? defaultNow(),\n seen: new Set<string>(),\n level,\n threshold: LOG_LEVEL_SEVERITY[level],\n };\n return new LoggerImpl(state, options.scope ?? null);\n}\n","/**\n * The minimal platform probe reached as `app.platform`\n * (`docs/architecture/14-platform-electron.md` §1). Phase 1 answers only the question the kernel\n * itself asks — is there a document to hang `visibilitychange` on? — and the rest of §1's surface\n * (`os`, `isMobile`, `hasPointerLock`, `hasGamepads`, `webgpu`, `locale`, `reducedMotion`) arrives\n * with `@ignifx/electron` in Phase 9 of `docs/plan/engineering-plan.md`.\n */\n\n/**\n * Where an app is running.\n *\n * @remarks\n * `\"electron\"` is deliberately absent until the Electron extension can detect it reliably: an\n * Electron renderer is a browser as far as the kernel is concerned, and guessing from the user\n * agent would be worse than saying `\"browser\"`.\n *\n * @public\n */\nexport type PlatformKind = \"browser\" | \"node\";\n\n/**\n * What the kernel knows about the host.\n *\n * @example\n * ```ts\n * if (app.platform.kind === \"browser\") {\n * document.title = \"playing\";\n * }\n * ```\n *\n * @public\n */\nexport interface PlatformInfo {\n /** Whether the app runs in a document or in a bare JavaScript runtime. */\n readonly kind: PlatformKind;\n}\n\n/**\n * Probes the host.\n *\n * @returns `{ kind: \"browser\" }` when a `document` is reachable, `{ kind: \"node\" }` otherwise.\n *\n * @internal\n */\nexport function detectPlatform(): PlatformInfo {\n const isBrowser = \"document\" in globalThis && \"window\" in globalThis;\n return Object.freeze({ kind: isBrowser ? \"browser\" : \"node\" });\n}\n","import type { DeferredQueue } from \"../signal/signal.js\";\n\n/**\n * The `EndOfFrame` queue (`docs/architecture/01-lifecycle-and-time.md` §3 step 0,\n * `02-scene-graph.md` §8). A `{ deferred: true }` signal connection and anything else that wants to\n * run \"later, but still inside a phase\" enqueues here; the scheduler drains the queue at the top of\n * the **next** frame.\n *\n * @remarks\n * Draining swaps the pending array for a scratch one before running anything, so work enqueued *by*\n * a deferred callback lands in the following frame rather than extending the current drain into an\n * unbounded loop. Both arrays are reused, so a steady stream of deferred deliveries allocates\n * nothing per frame (coding standards §7).\n *\n * @internal\n */\nexport class EndOfFrameQueue implements DeferredQueue {\n #pending: (() => void)[] = [];\n\n #running: (() => void)[] = [];\n\n readonly #onError: (error: unknown) => void;\n\n /**\n * Creates the queue of one app.\n *\n * @param onError - Where a deferred callback's exception is reported. It must not throw.\n */\n constructor(onError: (error: unknown) => void) {\n this.#onError = onError;\n }\n\n /**\n * How much work is waiting for the next drain.\n *\n * @returns The number of queued callbacks.\n */\n get length(): number {\n return this.#pending.length;\n }\n\n /**\n * Queues a callback for the next frame's `EndOfFrame` step.\n *\n * @param callback - The delivery to run.\n */\n enqueue(callback: () => void): void {\n this.#pending.push(callback);\n }\n\n /**\n * Runs everything queued before this call, in queue order.\n *\n * @returns How many callbacks ran.\n */\n drain(): number {\n const batch = this.#pending;\n const count = batch.length;\n if (count === 0) {\n return 0;\n }\n this.#pending = this.#running;\n this.#running = batch;\n for (let index = 0; index < count; index += 1) {\n const callback = batch[index];\n if (callback === undefined) {\n continue;\n }\n try {\n callback();\n } catch (error) {\n this.#onError(error);\n }\n }\n batch.length = 0;\n return count;\n }\n\n /** Drops every queued callback, for app disposal. */\n clear(): void {\n this.#pending.length = 0;\n this.#running.length = 0;\n }\n}\n","import { componentInternals } from \"../component/internals.js\";\nimport type { Script } from \"../script/script.js\";\n\n/**\n * The `time.paused` filter the scheduler applies to `fixedUpdate`, `update`, and `lateUpdate`\n * (`docs/architecture/01-lifecycle-and-time.md` §2, §7): while the app is paused only scripts whose\n * class sets `static updateWhenPaused = true` keep receiving them.\n *\n * @remarks\n * The flag is resolved once per class, at registration, into `ScriptClassInfo.updateWhenPaused`;\n * this reads it back through the component's engine state, which is a symbol property access and no\n * lookup at all (coding standards §7).\n *\n * @param script - The script about to receive a callback.\n * @returns `true` when the script keeps updating while the app is paused.\n *\n * @internal\n */\nexport function updatesWhilePaused(script: Script): boolean {\n return componentInternals(script).info?.script?.updateWhenPaused ?? false;\n}\n","import { PHASES, Phase } from \"../app/types.js\";\nimport { ScriptCallbackKind } from \"../lifecycle/callbacks.js\";\nimport { updatesWhilePaused } from \"../lifecycle/pause-filter.js\";\nimport type { EndOfFrameQueue } from \"./deferred-queue.js\";\nimport type { RegisterSystemOptions, System, SystemContext, Time } from \"../app/types.js\";\nimport type { CoroutineHostImpl } from \"../coroutine/coroutine-host.js\";\nimport type { Diagnostics } from \"../diagnostics/diagnostics.js\";\nimport type { FrameStateController } from \"../lifecycle/frame-state.js\";\nimport type { Script } from \"../script/script.js\";\nimport type { Clock } from \"../time/clock.js\";\nimport type { TimeImpl } from \"../time/time.js\";\nimport type { WorldInternals } from \"../world/world-internals.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * The frame function (`docs/architecture/01-lifecycle-and-time.md` §3). One instance per app drives\n * the whole of steps 0–10, in order, whether the frame was started by Babylon Lite's render loop or\n * by `app.step(dt)`.\n *\n * Rules this file exists to keep:\n *\n * - **Nothing allocates per frame** (coding standards §7). The system context is one long-lived\n * mutable object, the three script visitors are bound once in the field initialisers, and every\n * loop is an indexed `for`.\n * - **Script callbacks go through the world's one guarded call site.** The scheduler decides *who*\n * and *when*; `WorldInternals.invokeCallback` decides what happens when game code throws\n * (`03-scripting-and-components.md` §6, `01-lifecycle-and-time.md` §5).\n * - **Systems never see a phase they did not register for**, and within a phase they run in\n * ascending `order` with registration order breaking ties.\n *\n * Decisions the documents leave open:\n *\n * - **`lateUpdate` is billed to `PostUpdate` in the per-phase CPU timings.** §3 gives `lateUpdate`\n * its own step but `Phase` has no ordinal for it, and `FrameSample.cpuMs` is indexed by phase\n * ordinal; `PostUpdate` is the phase it sits inside.\n * - **The fixed loop does not run at all while the app is paused.** §2's table says the phases\n * `FixedUpdate`…`LateUpdate` \"skip scripts\", but §7 is explicit that \"fixed steps and physics do\n * not run\" while paused, and a physics system that kept stepping with no `fixedUpdate` in front\n * of it would be worse than either reading alone. Systems of every other phase keep running:\n * rendering, audio, and UI must still work on a pause screen.\n * - **`FrameSample.destroyed` counts entities.** The destroy flush reports no total, and the only\n * world-level signal for a release is `onEntityDestroyed`; a component destroyed on a surviving\n * entity is therefore not counted yet.\n */\n\n/** How many phases the scheduler keeps system lists for. */\nconst PHASE_COUNT = PHASES.length;\n\n/** Milliseconds in one second. */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * How close the accumulator has to be to a multiple of the fixed step before it is snapped onto it\n * (§3 notes). Without this, `600` frames of exactly `1 / 60` would drift into a frame with two\n * steps and a frame with none.\n */\nconst SNAP_TOLERANCE = 1e-6;\n\n/** One registered system, with the keys that order it inside its phase. */\nclass SystemEntry {\n /** The system. */\n readonly system: System;\n\n /** Ascending order within the phase. */\n readonly order: number;\n\n /** Registration serial, the tie-breaker. */\n readonly serial: number;\n\n /**\n * Creates an entry.\n *\n * @param system - The system.\n * @param order - Its order within the phase.\n * @param serial - Its registration serial.\n */\n constructor(system: System, order: number, serial: number) {\n this.system = system;\n this.order = order;\n this.serial = serial;\n }\n}\n\n/**\n * The one {@link SystemContext} every system in an app is handed. Its fields are mutable so that\n * running a phase allocates nothing; the public interface declares them `readonly`, which is what\n * systems see.\n */\nclass SystemContextImpl implements SystemContext {\n /** The world the system operates on. */\n world: World;\n\n /** The app clock. */\n readonly time: Time;\n\n /** The phase currently running. */\n phase: Phase = Phase.EndOfFrame;\n\n /** Seconds elapsed. */\n dt = 0;\n\n /**\n * Creates the shared context.\n *\n * @param world - The world.\n * @param time - The clock.\n */\n constructor(world: World, time: Time) {\n this.world = world;\n this.time = time;\n }\n}\n\n/**\n * What the scheduler needs from the app.\n *\n * @internal\n */\nexport interface SchedulerOptions {\n /** The app clock the frame advances. */\n readonly time: TimeImpl;\n /** The per-frame counters the loop publishes. */\n readonly diagnostics: Diagnostics;\n /** The frame state, so `inFixedStep` is visible to the scene graph. */\n readonly frameState: FrameStateController;\n /** The coroutine scheduler, resumed at the two documented points. */\n readonly coroutines: CoroutineHostImpl;\n /** The `EndOfFrame` queue drained at step 0. */\n readonly deferred: EndOfFrameQueue;\n /** The wall clock used for the development-only per-phase timings. */\n readonly clock: Clock;\n /** Whether per-phase CPU timings are recorded. */\n readonly development: boolean;\n /**\n * Reports a system failure.\n *\n * @param error - Whatever the system threw.\n * @param system - The system that threw.\n * @param phase - The phase it was running in.\n */\n report(error: unknown, system: System, phase: Phase): void;\n}\n\n/**\n * The frame function of one app.\n *\n * @internal\n */\nexport class Scheduler {\n readonly #time: TimeImpl;\n\n readonly #diagnostics: Diagnostics;\n\n readonly #frameState: FrameStateController;\n\n readonly #coroutines: CoroutineHostImpl;\n\n readonly #deferred: EndOfFrameQueue;\n\n readonly #clock: Clock;\n\n readonly #development: boolean;\n\n readonly #report: (error: unknown, system: System, phase: Phase) => void;\n\n /** One system list per phase, kept sorted by `(order, registration serial)`. */\n readonly #systems: SystemEntry[][] = [];\n\n /** How many entries of each phase's list have a negative `order`. */\n readonly #negativeCounts: number[] = [];\n\n #context: SystemContextImpl | null = null;\n\n #internals: WorldInternals | null = null;\n\n #world: World | null = null;\n\n #serial = 0;\n\n #accumulator = 0;\n\n #phase: Phase | null = null;\n\n #stepDt = 0;\n\n #frameDt = 0;\n\n /**\n * Dispatches `fixedUpdate` to one script. Bound once so the fixed loop allocates nothing.\n *\n * @param script - The script to call.\n */\n readonly #visitFixedUpdate = (script: Script): void => {\n this.#internals?.invokeCallback(script, ScriptCallbackKind.fixedUpdate, this.#stepDt);\n };\n\n /**\n * Dispatches `update` to one script, honouring `time.paused`.\n *\n * @param script - The script to call.\n */\n readonly #visitUpdate = (script: Script): void => {\n if (this.#time.paused && !updatesWhilePaused(script)) {\n return;\n }\n this.#diagnostics.frame.scriptsUpdated += 1;\n this.#internals?.invokeCallback(script, ScriptCallbackKind.update, this.#frameDt);\n };\n\n /**\n * Dispatches `lateUpdate` to one script, honouring `time.paused`.\n *\n * @param script - The script to call.\n */\n readonly #visitLateUpdate = (script: Script): void => {\n if (this.#time.paused && !updatesWhilePaused(script)) {\n return;\n }\n this.#internals?.invokeCallback(script, ScriptCallbackKind.lateUpdate, this.#frameDt);\n };\n\n /** Counts an entity release into this frame's diagnostics. */\n readonly #countDestroyed = (): void => {\n this.#diagnostics.frame.destroyed += 1;\n };\n\n /**\n * Creates the frame function of one app.\n *\n * @param options - The clock, diagnostics, coroutine scheduler, and deferred queue it drives.\n */\n constructor(options: SchedulerOptions) {\n this.#time = options.time;\n this.#diagnostics = options.diagnostics;\n this.#frameState = options.frameState;\n this.#coroutines = options.coroutines;\n this.#deferred = options.deferred;\n this.#clock = options.clock;\n this.#development = options.development;\n // Bound rather than assigned: `options.report` is declared as a method, so handing the raw\n // reference around would detach its `this` (coding standards §5.4).\n this.#report = (error: unknown, system: System, phase: Phase): void => {\n options.report(error, system, phase);\n };\n for (let index = 0; index < PHASE_COUNT; index += 1) {\n this.#systems.push([]);\n this.#negativeCounts.push(0);\n }\n }\n\n /**\n * The phase currently running, for error reports raised outside the world's guarded call site.\n *\n * @returns The phase, or `null` between phases.\n */\n get currentPhase(): Phase | null {\n return this.#phase;\n }\n\n /**\n * What is left in the fixed-step accumulator, in seconds.\n *\n * @returns The residue the interpolation alpha is derived from.\n */\n get accumulator(): number {\n return this.#accumulator;\n }\n\n /**\n * Registers a system in a phase (`docs/architecture/03-scripting-and-components.md` §6).\n *\n * @param system - The system.\n * @param options - The phase and the ascending order within it; `order` defaults to `0`.\n */\n registerSystem(system: System, options: RegisterSystemOptions): void {\n const phase = options.phase;\n const list = this.#systems[phase];\n if (list === undefined) {\n return;\n }\n this.#serial += 1;\n const entry = new SystemEntry(system, options.order ?? 0, this.#serial);\n // Sorted insertion, not a per-frame sort: both keys are fixed for the system's whole life.\n let index = list.length;\n while (index > 0) {\n const previous = list[index - 1];\n if (previous === undefined || previous.order <= entry.order) {\n break;\n }\n list[index] = previous;\n index -= 1;\n }\n list[index] = entry;\n let negatives = 0;\n for (let at = 0; at < list.length; at += 1) {\n if ((list[at]?.order ?? 0) < 0) {\n negatives += 1;\n }\n }\n this.#negativeCounts[phase] = negatives;\n const world = this.#world;\n if (world !== null) {\n system.onWorldCreated?.(world);\n }\n }\n\n /**\n * Binds the world the frame function drives and tells every registered system about it.\n *\n * @param world - The world `createApp` built.\n */\n attachWorld(world: World): void {\n this.#world = world;\n this.#internals = world.lifecycle;\n this.#context = new SystemContextImpl(world, this.#time);\n world.onEntityDestroyed.connect(this.#countDestroyed);\n for (let phase = 0; phase < PHASE_COUNT; phase += 1) {\n const list = this.#systems[phase] ?? [];\n for (let index = 0; index < list.length; index += 1) {\n list[index]?.system.onWorldCreated?.(world);\n }\n }\n }\n\n /**\n * Runs one frame: `docs/architecture/01-lifecycle-and-time.md` §3, top to bottom.\n *\n * @param rawDeltaSeconds - The delta the driver supplied, before the maximum-delta clamp.\n */\n runFrame(rawDeltaSeconds: number): void {\n const time = this.#time;\n const diagnostics = this.#diagnostics;\n const internals = this.#internals;\n\n // Step 0 — EndOfFrame work carried over from the previous frame. It runs before the clock\n // advances, so a deferred handler still sees the delta of the frame that queued it.\n const endOfFrameStart = this.#now();\n this.#deferred.drain();\n this.#runSystems(Phase.EndOfFrame, 0, -1, time.deltaTime);\n const endOfFrameMs = this.#now() - endOfFrameStart;\n\n // Step 1 — the clock.\n time.beginFrame(rawDeltaSeconds);\n diagnostics.beginFrame(rawDeltaSeconds * MILLISECONDS_PER_SECOND);\n diagnostics.frame.droppedMs = time.droppedSeconds * MILLISECONDS_PER_SECOND;\n this.#writePhaseTime(Phase.EndOfFrame, endOfFrameMs);\n this.#frameDt = time.deltaTime;\n\n // Step 2 — PreUpdate.\n this.#runPhase(Phase.PreUpdate, 0, -1, time.deltaTime);\n\n // Step 3 — lifecycle flush A: awake, then onEnable.\n internals?.flushAwakeAndEnable();\n\n // Step 4 — the fixed loop.\n this.#runFixedLoop();\n\n // Step 5 — lifecycle flush B: start.\n internals?.flushStart();\n\n // Step 6 — Update.\n this.#runUpdate();\n\n // Step 7 and 8 — PostUpdate, then lateUpdate.\n const postUpdateStart = this.#now();\n this.#runSystems(Phase.PostUpdate, 0, -1, time.deltaTime);\n this.#dispatch(ScriptCallbackKind.lateUpdate, this.#visitLateUpdate, Phase.PostUpdate);\n this.#writePhaseTime(Phase.PostUpdate, this.#now() - postUpdateStart);\n\n // Step 9 — the destroy flush, before anything renders.\n internals?.flushDestroy();\n\n // Step 10 — PreRender.\n this.#runPhase(Phase.PreRender, 0, -1, time.deltaTime);\n\n time.endFrame();\n diagnostics.endFrame();\n }\n\n /** Releases every system and clears the phase lists. */\n dispose(): void {\n const world = this.#world;\n for (let phase = 0; phase < PHASE_COUNT; phase += 1) {\n const list = this.#systems[phase] ?? [];\n for (let index = list.length - 1; index >= 0; index -= 1) {\n const system = list[index]?.system;\n if (system === undefined) {\n continue;\n }\n if (world !== null) {\n system.onWorldDisposed?.(world);\n }\n system.dispose?.();\n }\n list.length = 0;\n this.#negativeCounts[phase] = 0;\n }\n this.#world = null;\n this.#internals = null;\n this.#context = null;\n }\n\n /**\n * Step 4: the fixed-timestep loop, with the accumulator snapping rule of §3.\n *\n * @remarks\n * The loop is bounded by `maximumDeltaTime`, which is what the clamp in step 1 is for: with the\n * defaults a frame runs at most six fixed steps no matter how long the tab was in the background.\n */\n #runFixedLoop(): void {\n const time = this.#time;\n const start = this.#now();\n this.#phase = Phase.FixedUpdate;\n this.#internals?.setPhase(Phase.FixedUpdate);\n if (!time.paused) {\n this.#accumulator = snap(this.#accumulator + time.deltaTime, time.fixedDeltaTime);\n const step = time.fixedDeltaTime;\n this.#stepDt = step;\n const negatives = this.#negativeCounts[Phase.FixedUpdate] ?? 0;\n while (this.#accumulator >= step) {\n time.beginFixedStep();\n this.#frameState.setInsideFixedStep(true);\n this.#runSystems(Phase.FixedUpdate, 0, negatives, step);\n this.#dispatch(ScriptCallbackKind.fixedUpdate, this.#visitFixedUpdate, Phase.FixedUpdate);\n this.#runSystems(Phase.FixedUpdate, negatives, -1, step);\n // Physics contact and trigger dispatch belongs here, between the step and the coroutine\n // resume point (§3). `@ignifx/physics` performs it from its own `FixedUpdate` system, which\n // the line above already ran; the kernel adds no hook of its own.\n this.#diagnostics.frame.coroutinesResumed += this.#coroutines.resumeFixedUpdate();\n this.#accumulator = snap(this.#accumulator - step, step);\n this.#diagnostics.frame.fixedSteps += 1;\n }\n this.#frameState.setInsideFixedStep(false);\n }\n time.endFixedLoop(this.#accumulator);\n this.#internals?.setPhase(null);\n this.#phase = null;\n this.#writePhaseTime(Phase.FixedUpdate, this.#now() - start);\n }\n\n /** Step 6: `Systems(Update, order < 0)`, `update`, coroutines, `Systems(Update, order >= 0)`. */\n #runUpdate(): void {\n const start = this.#now();\n const time = this.#time;\n const negatives = this.#negativeCounts[Phase.Update] ?? 0;\n this.#runSystems(Phase.Update, 0, negatives, time.deltaTime);\n this.#dispatch(ScriptCallbackKind.update, this.#visitUpdate, Phase.Update);\n this.#phase = Phase.Update;\n this.#diagnostics.frame.coroutinesResumed += this.#coroutines.resumeUpdate(time.deltaTime, time.unscaledDeltaTime);\n this.#phase = null;\n this.#runSystems(Phase.Update, negatives, -1, time.deltaTime);\n this.#writePhaseTime(Phase.Update, this.#now() - start);\n }\n\n /**\n * Runs a whole phase's systems and records its CPU time.\n *\n * @param phase - The phase.\n * @param from - The first entry to run.\n * @param to - One past the last entry, or `-1` for \"to the end\".\n * @param dt - The delta handed to the systems.\n */\n #runPhase(phase: Phase, from: number, to: number, dt: number): void {\n const start = this.#now();\n this.#runSystems(phase, from, to, dt);\n this.#writePhaseTime(phase, this.#now() - start);\n }\n\n /**\n * Runs a slice of one phase's system list, guarded: a system that throws is reported and the rest\n * of the phase still runs (coding standards §5.5).\n *\n * @param phase - The phase.\n * @param from - The first entry to run.\n * @param to - One past the last entry, or `-1` for \"to the end\".\n * @param dt - The delta handed to the systems.\n */\n #runSystems(phase: Phase, from: number, to: number, dt: number): void {\n const list = this.#systems[phase];\n const context = this.#context;\n if (list === undefined || context === null) {\n return;\n }\n const end = to < 0 ? list.length : to;\n if (from >= end) {\n return;\n }\n context.phase = phase;\n context.dt = dt;\n const previousPhase = this.#phase;\n this.#phase = phase;\n this.#internals?.setPhase(phase);\n for (let index = from; index < end; index += 1) {\n const system = list[index]?.system;\n if (system === undefined) {\n continue;\n }\n try {\n system.update?.(context);\n } catch (error) {\n this.#report(error, system, phase);\n }\n }\n this.#internals?.setPhase(previousPhase);\n this.#phase = previousPhase;\n }\n\n /**\n * Walks one callback's sorted dispatch list.\n *\n * @param kind - Which callback.\n * @param visitor - The bound visitor for that callback; never allocated here.\n * @param phase - The phase to record in error reports.\n */\n #dispatch(kind: ScriptCallbackKind, visitor: (script: Script) => void, phase: Phase): void {\n const internals = this.#internals;\n if (internals === null) {\n return;\n }\n const previousPhase = this.#phase;\n this.#phase = phase;\n internals.setPhase(phase);\n // `forEachScript` is what makes the walk safe when a callback disables, destroys, or enables a\n // script; the visitor is a bound field, so this allocates nothing (coding standards §7).\n internals.forEachScript(kind, visitor);\n internals.setPhase(previousPhase);\n this.#phase = previousPhase;\n }\n\n /**\n * Reads the timing clock, or returns `0` outside development builds so the timings cost nothing.\n *\n * @returns Milliseconds, or `0` when timings are off.\n */\n #now(): number {\n return this.#development ? this.#clock.nowMs() : 0;\n }\n\n /**\n * Records one phase's CPU time.\n *\n * @param phase - The phase.\n * @param milliseconds - How long it took.\n */\n #writePhaseTime(phase: Phase, milliseconds: number): void {\n if (this.#development) {\n this.#diagnostics.frame.cpuMs[phase] = milliseconds;\n }\n }\n}\n\n/**\n * Snaps an accumulator onto the nearest multiple of the fixed step when it is within\n * `1e-6 × fixedDeltaTime` of one (`docs/architecture/01-lifecycle-and-time.md` §3 notes).\n *\n * @remarks\n * This is what makes `app.step(1 / 60)` run exactly one fixed step per call for as long as the test\n * runs: without it, the accumulated rounding error of the repeated `+= 1/60` and `-= 1/60` would\n * eventually leave a residue just below the step and produce a frame with no fixed step, followed\n * by one with two.\n *\n * @param accumulator - The current residue, in seconds.\n * @param step - The fixed step, in seconds.\n * @returns The snapped residue.\n */\nfunction snap(accumulator: number, step: number): number {\n const multiples = Math.round(accumulator / step);\n const nearest = multiples * step;\n if (Math.abs(accumulator - nearest) <= SNAP_TOLERANCE * step) {\n return nearest;\n }\n return accumulator;\n}\n","import { assertNever } from \"../errors/ignifx-error.js\";\nimport { COLOR_CHANNELS, VECTOR_COMPONENTS, childPath, indexPath, isArray, isPlainObject } from \"./internal.js\";\nimport { SchemaIssueCode, issue } from \"./issues.js\";\nimport type { SchemaIssue } from \"./issues.js\";\nimport type { FieldDefinition, FieldOptions, Schema } from \"./types.js\";\n\n/**\n * The inclusive bounds of a signed 32-bit integer.\n *\n * @internal\n */\nconst I32_RANGE = [-2147483648, 2147483647] as const;\n/**\n * The inclusive bounds of an unsigned 32-bit integer.\n *\n * @internal\n */\nconst U32_RANGE = [0, 4294967295] as const;\n\n/**\n * Checks a numeric value against its kind's integer rules and the field's `min`/`max` options.\n *\n * @param kind - The numeric field kind.\n * @param options - The field's options.\n * @param value - The value to check.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n *\n * @internal\n */\nfunction validateNumber(\n kind: \"f32\" | \"f64\" | \"i32\" | \"u32\",\n options: FieldOptions,\n value: unknown,\n path: string,\n issues: SchemaIssue[],\n): void {\n if (typeof value !== \"number\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a ${kind} number, received ${typeof value}.`));\n return;\n }\n if (!Number.isFinite(value)) {\n issues.push(issue(SchemaIssueCode.nonFiniteNumber, path, `${String(value)} cannot be written to JSON.`));\n return;\n }\n if (kind === \"i32\" || kind === \"u32\") {\n if (Number.isInteger(value)) {\n const [low, high] = kind === \"u32\" ? U32_RANGE : I32_RANGE;\n if (value < low || value > high) {\n issues.push(issue(SchemaIssueCode.outOfRange, path, `${value} is outside the ${kind} range.`));\n }\n } else {\n issues.push(issue(SchemaIssueCode.outOfRange, path, `${kind} requires a whole number, received ${value}.`));\n }\n }\n const { min, max } = options;\n if (min !== undefined && value < min) {\n issues.push(issue(SchemaIssueCode.outOfRange, path, `${value} is below the declared minimum ${min}.`));\n }\n if (max !== undefined && value > max) {\n issues.push(issue(SchemaIssueCode.outOfRange, path, `${value} is above the declared maximum ${max}.`));\n }\n}\n\n/**\n * Checks that every named channel of an object value is a finite number, optionally within bounds.\n *\n * @param names - The channel names to require.\n * @param bounds - Inclusive `[low, high]` bounds each channel must fall in, or `null` for none.\n * @param label - How the value is named in messages.\n * @param value - The value to check.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n *\n * @internal\n */\nfunction validateChannels(\n names: readonly string[],\n bounds: readonly [number, number] | null,\n label: string,\n value: unknown,\n path: string,\n issues: SchemaIssue[],\n): void {\n if (!isPlainObject(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a ${label} object, received ${typeof value}.`));\n return;\n }\n for (const name of names) {\n const channel = value[name];\n const channelAt = childPath(path, name);\n if (typeof channel !== \"number\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, channelAt, `expected a number, received ${typeof channel}.`));\n continue;\n }\n if (!Number.isFinite(channel)) {\n issues.push(issue(SchemaIssueCode.nonFiniteNumber, channelAt, `${String(channel)} cannot be written to JSON.`));\n continue;\n }\n if (bounds !== null && (channel < bounds[0] || channel > bounds[1])) {\n issues.push(\n issue(SchemaIssueCode.outOfRange, channelAt, `${channel} is outside the ${bounds[0]}–${bounds[1]} range.`),\n );\n }\n }\n}\n\n/**\n * Checks one value against one field definition, appending to a collector.\n *\n * @param field - The field to check against.\n * @param value - The value to check.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n *\n * @internal\n */\nfunction validateInto(field: FieldDefinition<unknown>, value: unknown, path: string, issues: SchemaIssue[]): void {\n const { spec } = field;\n switch (spec.kind) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\": {\n validateNumber(spec.kind, field.options, value, path, issues);\n return;\n }\n case \"bool\": {\n if (typeof value !== \"boolean\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a boolean, received ${typeof value}.`));\n }\n return;\n }\n case \"str\": {\n if (typeof value !== \"string\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a string, received ${typeof value}.`));\n }\n return;\n }\n case \"vec2\":\n case \"vec3\":\n case \"vec4\":\n case \"quat\": {\n validateChannels(VECTOR_COMPONENTS.slice(0, spec.components), null, spec.kind, value, path, issues);\n return;\n }\n case \"color\": {\n validateChannels(COLOR_CHANNELS, [0, 1], \"color\", value, path, issues);\n return;\n }\n case \"enum\": {\n if (typeof value !== \"string\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a string, received ${typeof value}.`));\n } else if (!spec.values.includes(value)) {\n issues.push(issue(SchemaIssueCode.outOfRange, path, `\"${value}\" is not one of [${spec.values.join(\", \")}].`));\n }\n return;\n }\n case \"entityRef\":\n case \"componentRef\": {\n if (value !== null && typeof value !== \"object\") {\n issues.push(\n issue(\n SchemaIssueCode.typeMismatch,\n path,\n `expected a ${spec.kind} target or null, received ${typeof value}.`,\n ),\n );\n }\n return;\n }\n case \"asset\": {\n if (value === null) {\n return;\n }\n // Structural on purpose: the runtime value is an `AssetHandle`, which the schema layer must\n // not import (coding standards §4), and a tool that reads a file without an app holds the\n // plain `{ address, type? }` form instead. Both carry a string `address`, which is the only\n // thing this layer can check.\n if (!isPlainObject(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a loaded asset handle or null.`));\n return;\n }\n if (typeof value[\"address\"] !== \"string\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, childPath(path, \"address\"), `expected a string address.`));\n }\n return;\n }\n case \"array\": {\n if (!isArray(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected an array, received ${typeof value}.`));\n return;\n }\n for (let index = 0; index < value.length; index += 1) {\n validateInto(spec.item, value[index], indexPath(path, index), issues);\n }\n return;\n }\n case \"record\": {\n if (!isPlainObject(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected an object, received ${typeof value}.`));\n return;\n }\n collectPropsIssues(spec.fields, value, path, issues);\n return;\n }\n case \"map\": {\n if (!isPlainObject(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected an object, received ${typeof value}.`));\n return;\n }\n for (const [key, entry] of Object.entries(value)) {\n validateInto(spec.value, entry, indexPath(path, key), issues);\n }\n return;\n }\n case \"optional\": {\n if (value !== null) {\n validateInto(spec.inner, value, path, issues);\n }\n return;\n }\n case \"layerMask\": {\n if (!isArray(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected an array of layer names.`));\n return;\n }\n for (let index = 0; index < value.length; index += 1) {\n if (typeof value[index] !== \"string\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, indexPath(path, index), `expected a layer name string.`));\n }\n }\n return;\n }\n case \"curve\": {\n if (!isPlainObject(value)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected a curve object.`));\n return;\n }\n const keys = value[\"keys\"];\n if (!isArray(keys)) {\n issues.push(issue(SchemaIssueCode.typeMismatch, childPath(path, \"keys\"), `expected an array of curve keys.`));\n return;\n }\n for (let index = 0; index < keys.length; index += 1) {\n validateCurveKey(keys[index], indexPath(childPath(path, \"keys\"), index), issues);\n }\n return;\n }\n case \"custom\": {\n // A custom field's shape is the codec's business; the schema layer cannot second-guess it.\n return;\n }\n default: {\n assertNever(spec, \"schema field kind\");\n }\n }\n}\n\n/**\n * Checks one animation curve key.\n *\n * @param key - The candidate key.\n * @param path - The property path for reported issues.\n * @param issues - The collector to append to.\n *\n * @internal\n */\nfunction validateCurveKey(key: unknown, path: string, issues: SchemaIssue[]): void {\n if (!isArray(key) || key.length !== 4) {\n issues.push(issue(SchemaIssueCode.typeMismatch, path, `expected [time, value, inTangent, outTangent].`));\n return;\n }\n for (let index = 0; index < 4; index += 1) {\n const component = key[index];\n if (typeof component !== \"number\") {\n issues.push(issue(SchemaIssueCode.typeMismatch, indexPath(path, index), `expected a number.`));\n } else if (!Number.isFinite(component)) {\n issues.push(\n issue(\n SchemaIssueCode.nonFiniteNumber,\n indexPath(path, index),\n `${String(component)} cannot be written to JSON.`,\n ),\n );\n }\n }\n}\n\n/**\n * Checks a bag of property values against a schema, appending to a collector.\n *\n * @param schema - The schema that says which names are legal and how they are typed.\n * @param props - The values to check.\n * @param path - The property path prefix for reported issues.\n * @param issues - The collector to append to.\n *\n * @internal\n */\nfunction collectPropsIssues(\n schema: Schema,\n props: Readonly<Record<string, unknown>>,\n path: string,\n issues: SchemaIssue[],\n): void {\n for (const name of Object.keys(props)) {\n if (!Object.hasOwn(schema, name)) {\n issues.push(\n issue(SchemaIssueCode.unknownField, childPath(path, name), `the schema declares no field \"${name}\".`),\n );\n }\n }\n for (const [name, field] of Object.entries(schema)) {\n const value = props[name];\n if (value !== undefined) {\n validateInto(field, value, childPath(path, name), issues);\n }\n }\n}\n\n/**\n * Checks one value against one field definition. Nothing is thrown: the result is data, and the\n * caller decides whether a problem is a development-time error or a logged diagnostic\n * (`CONSTITUTION.md` §3.9).\n *\n * Checks performed are the value's type, finiteness for numbers, whole-number and 32-bit range for\n * `i32`/`u32`, `min`/`max` from the field options, enum membership, sRGB 0–1 range for colors, and\n * recursion into `array`, `record`, `map`, and `optional`.\n *\n * @param field - The field to check against.\n * @param value - The value to check.\n * @param path - A property path prefix used when reporting issues; defaults to the empty path.\n * @returns Every problem found, in discovery order; empty when the value is valid.\n *\n * @example\n * ```ts\n * validateValue(f32(0, { min: 0 }), -1);\n * // [{ path: \"\", code: \"IGX-0606\", message: \"-1 is below the declared minimum 0.\" }]\n * ```\n *\n * @public\n */\nexport function validateValue(\n field: FieldDefinition<unknown>,\n value: unknown,\n path: string = \"\",\n): readonly SchemaIssue[] {\n const issues: SchemaIssue[] = [];\n validateInto(field, value, path, issues);\n return issues;\n}\n\n/**\n * Checks a bag of property values against a schema. Names the schema does not declare are reported\n * as `IGX-0607`; names the caller omits are legal, because omitted props take schema defaults\n * (`docs/architecture/06-serialization-and-scene-format.md` §2).\n *\n * @param schema - The schema to check against.\n * @param props - The values to check, keyed by field name.\n * @param path - A property path prefix used when reporting issues; defaults to the empty path.\n * @returns Every problem found, in discovery order; empty when the props are valid.\n *\n * @public\n */\nexport function validateProps(\n schema: Schema,\n props: Readonly<Record<string, unknown>>,\n path: string = \"\",\n): readonly SchemaIssue[] {\n const issues: SchemaIssue[] = [];\n collectPropsIssues(schema, props, path, issues);\n return issues;\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { createDefaults } from \"../schema/schema.js\";\nimport { validateProps } from \"../schema/validate.js\";\nimport type { SettingsInput } from \"./settings-input.js\";\nimport type { AppSettings, LayersSettings, SortingLayersSettings, TimeSettings } from \"../app/types.js\";\nimport type { ErrorFormatMode } from \"../errors/ignifx-error.js\";\nimport type { Logger } from \"../log/logger.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * Project settings (`docs/architecture/04-extensions.md` §5). Each section is owned by the\n * extension that registered it, validated against that extension's schema, and frozen once every\n * extension has registered.\n *\n * Decisions the documents leave open:\n *\n * - **Single-field shorthand.** §5's example writes `layers: [\"Default\", \"Ground\"]`, an array,\n * while `AppSettings.layers` is `{ layers: readonly string[] }` and `Schema` describes an object\n * with named fields. The two are reconciled by one documented rule: when a section's schema\n * declares exactly one field and the project supplies something that is not a plain object, the\n * value is taken as that field's value. So `layers: [...]` and `layers: { layers: [...] }` both\n * work, and `time: { fixedDeltaTime: 1 / 60 }` — two fields — keeps its object form.\n * - **A provided section is merged over the defaults, not replaced by them.** §5 calls the\n * registered values \"defaults\", and omitted props already take schema defaults elsewhere\n * (`06-serialization-and-scene-format.md` §2), so a project that sets only `fixedDeltaTime`\n * keeps the default `maximumDeltaTime`.\n */\n\n/** One registered section. */\ninterface Section {\n /** The schema the section is validated against. */\n readonly schema: Schema;\n /** The extension that registered it. */\n readonly owner: string;\n /** The resolved, frozen value. */\n value: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Reports whether a value is a plain object rather than an array, a primitive, or `null`.\n *\n * @param value - The candidate.\n * @returns `true` when the value can be read as a bag of named props.\n */\nfunction isPropertyBag(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The per-app settings table.\n *\n * @internal\n */\nexport class SettingsStore implements AppSettings {\n readonly #sections = new Map<string, Section>();\n\n readonly #input: SettingsInput;\n\n readonly #mode: ErrorFormatMode;\n\n readonly #log: Logger;\n\n #isFrozen = false;\n\n /**\n * Creates the settings table of one app.\n *\n * @param input - What the project supplied, keyed by section name.\n * @param mode - `\"development\"` throws on an invalid or unknown section; `\"production\"` logs and\n * falls back to the registered defaults (§5).\n * @param log - Where the production-mode complaints go.\n */\n constructor(input: SettingsInput, mode: ErrorFormatMode, log: Logger) {\n this.#input = input;\n this.#mode = mode;\n this.#log = log;\n }\n\n /**\n * The core `layers` section.\n *\n * @returns The project's layer names.\n */\n get layers(): LayersSettings {\n return this.section<LayersSettings>(\"layers\");\n }\n\n /**\n * The core `sortingLayers` section.\n *\n * @returns The project's sorting-layer names.\n */\n get sortingLayers(): SortingLayersSettings {\n return this.section<SortingLayersSettings>(\"sortingLayers\");\n }\n\n /**\n * The core `time` section.\n *\n * @returns The initial clock settings.\n */\n get time(): TimeSettings {\n return this.section<TimeSettings>(\"time\");\n }\n\n /**\n * Reads a resolved section.\n *\n * @typeParam S - The section's resolved shape, as its owner declared it.\n * @param name - The section name.\n * @returns The frozen resolved section.\n * @throws IgnifxError with code `IGX-0407` when the section was never registered.\n */\n // The type parameter is the caller's declaration of what the section holds; there is no value to\n // infer it from. Same escape hatch as `AppSettings.section`.\n // oxlint-disable-next-line typescript/no-unnecessary-type-parameters\n section<S>(name: string): S {\n const section = this.#sections.get(name);\n if (section === undefined) {\n throw new IgnifxError(CoreErrorCode.unknownSettingsSection, `${name} is not a registered settings section.`, {\n context: { section: name },\n hint: \"A section exists once the extension that owns it has run its register() hook.\",\n });\n }\n // Boundary assertion (coding standards §5.2): the invariant is that the resolved value was\n // built from the owner's own schema and defaults, so it has exactly the shape the owner\n // declared. Nothing in the type system connects a section name to a shape.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return section.value as S;\n }\n\n /**\n * Registers and immediately resolves a section, so `ctx.settings(name)` works inside the same\n * `register` call that declared it (`04-extensions.md` §1).\n *\n * @param name - The section name as it appears in `ignifx.config.ts`.\n * @param schema - The schema the project's values are validated against.\n * @param defaults - The values used for everything the project omits, as a bag of named props.\n * @param owner - The extension registering the section, named in diagnostics.\n * @throws IgnifxError with code `IGX-0408` in development when the project's values do not\n * validate.\n */\n register(name: string, schema: Schema, defaults: unknown, owner: string): void {\n const base = isPropertyBag(defaults) ? defaults : createDefaults(schema);\n const value = this.#resolve(name, schema, base);\n this.#sections.set(name, { schema, owner, value: Object.freeze(value) });\n }\n\n /**\n * Reports whether a section has been registered.\n *\n * @param name - The section name.\n * @returns `true` when an extension owns the section.\n */\n has(name: string): boolean {\n return this.#sections.has(name);\n }\n\n /**\n * Checks that every section the project supplied is owned by some extension (§5) and closes the\n * table to further registration.\n *\n * @throws IgnifxError with code `IGX-0407` in development when the project declares a section no\n * extension registered.\n */\n freeze(): void {\n for (const name of Object.keys(this.#input)) {\n if (this.#sections.has(name)) {\n continue;\n }\n if (this.#mode === \"development\") {\n throw new IgnifxError(CoreErrorCode.unknownSettingsSection, `${name} is not a registered settings section.`, {\n context: { section: name },\n hint: \"Register the extension that owns the section, or remove it from the project settings.\",\n });\n }\n this.#log.warn(\"Ignoring the unknown settings section {section}.\", name);\n }\n this.#isFrozen = true;\n }\n\n /**\n * Whether {@link SettingsStore.freeze} has run.\n *\n * @returns `true` once the table is closed.\n */\n get isFrozen(): boolean {\n return this.#isFrozen;\n }\n\n /**\n * Merges the project's values for one section over its defaults, validating them first.\n *\n * @param name - The section name.\n * @param schema - The owner's schema.\n * @param defaults - The owner's defaults.\n * @returns The resolved section.\n * @throws IgnifxError with code `IGX-0408` in development when validation fails.\n */\n #resolve(name: string, schema: Schema, defaults: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const provided = this.#input[name];\n const resolved: Record<string, unknown> = { ...defaults };\n if (provided === undefined) {\n return resolved;\n }\n const props = this.#toPropertyBag(schema, provided);\n if (props === null) {\n return this.#reject(name, `${name} settings must be an object.`, resolved);\n }\n const issues = validateProps(schema, props, name);\n if (issues.length > 0) {\n const detail = issues.map((entry) => `${entry.path}: ${entry.message}`).join(\"; \");\n return this.#reject(name, detail, resolved);\n }\n return Object.assign(resolved, props);\n }\n\n /**\n * Applies the single-field shorthand: a section whose schema declares exactly one field may be\n * written as that field's value.\n *\n * @param schema - The owner's schema.\n * @param provided - What the project supplied.\n * @returns A bag of named props, or `null` when the value cannot be read as one.\n */\n #toPropertyBag(schema: Schema, provided: unknown): Record<string, unknown> | null {\n if (isPropertyBag(provided)) {\n return provided;\n }\n const names = Object.keys(schema);\n const only = names[0];\n if (names.length !== 1 || only === undefined) {\n return null;\n }\n return { [only]: provided };\n }\n\n /**\n * Handles an invalid section: a throw in development, a log line and the defaults in production\n * (§5).\n *\n * @param name - The section name.\n * @param detail - What was wrong.\n * @param defaults - The values to fall back to.\n * @returns The defaults, in production.\n * @throws IgnifxError with code `IGX-0408` in development.\n */\n #reject(name: string, detail: string, defaults: Record<string, unknown>): Record<string, unknown> {\n if (this.#mode === \"development\") {\n throw new IgnifxError(CoreErrorCode.invalidSettings, `The ${name} settings section is invalid: ${detail}`, {\n context: { section: name, issues: detail },\n hint: \"Check the section against the schema the owning extension registered.\",\n });\n }\n this.#log.warn(\n \"The {section} settings section is invalid and was replaced by its defaults: {issues}\",\n name,\n detail,\n );\n return defaults;\n }\n}\n","/**\n * The wall clock the runtime reads (`docs/architecture/01-lifecycle-and-time.md` §2, §8). It is a\n * one-method interface so headless runs and tests can inject a clock they control: \"tests must not\n * depend on wall-clock time\" (§8, coding standards §10).\n */\n\n/**\n * A source of monotonically non-decreasing milliseconds.\n *\n * @remarks\n * Only `Time.realtimeSinceStartup` and the development-only phase timings read it; frame deltas are\n * supplied by Babylon Lite's render loop or by `app.step(dt)`, never measured from this clock, so\n * swapping the clock never changes simulation results (`CONSTITUTION.md` §2.1).\n *\n * @example\n * ```ts\n * const clock = createManualClock();\n * const app = await createApp({ headless: true, clock });\n * clock.advance(1000); // app.time.realtimeSinceStartup === 1\n * ```\n *\n * @public\n */\nexport interface Clock {\n /**\n * Reads the clock.\n *\n * @returns Milliseconds since an unspecified epoch; only differences are meaningful.\n */\n nowMs(): number;\n}\n\n/**\n * A clock that only moves when a test moves it.\n *\n * @public\n */\nexport interface ManualClock extends Clock {\n /**\n * Moves the clock forward.\n *\n * @param milliseconds - How far to advance. Negative values are rejected so the clock stays\n * monotonic.\n */\n advance(milliseconds: number): void;\n /**\n * Sets the clock to an absolute reading.\n *\n * @param milliseconds - The new reading.\n */\n set(milliseconds: number): void;\n}\n\n/**\n * Creates the default clock: `performance.now()` where the host has it, `Date.now()` otherwise.\n *\n * @returns A clock reading the host's monotonic timer.\n *\n * @public\n */\nexport function createPerformanceClock(): Clock {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return { nowMs: () => performance.now() };\n }\n return { nowMs: () => Date.now() };\n}\n\n/**\n * Creates a clock a test drives by hand. Headless apps take one so that `realtimeSinceStartup` and\n * `waitSecondsRealtime` are as deterministic as the rest of the frame\n * (`docs/architecture/01-lifecycle-and-time.md` §8).\n *\n * @param startMs - The initial reading. Defaults to `0`.\n * @returns The clock, with `advance` and `set`.\n *\n * @example\n * ```ts\n * const clock = createManualClock(1000);\n * clock.advance(1000 / 60);\n * clock.nowMs(); // 1016.666…\n * ```\n *\n * @public\n */\nexport function createManualClock(startMs: number = 0): ManualClock {\n let now = startMs;\n return {\n nowMs: (): number => now,\n advance: (milliseconds: number): void => {\n if (milliseconds > 0) {\n now += milliseconds;\n }\n },\n set: (milliseconds: number): void => {\n now = milliseconds;\n },\n };\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { Clock } from \"./clock.js\";\nimport type { Time } from \"../app/types.js\";\n\n/**\n * The implementation of {@link Time} (`docs/architecture/01-lifecycle-and-time.md` §2). The\n * scheduler owns one per app and drives it through {@link TimeImpl.beginFrame},\n * {@link TimeImpl.beginFixedStep}, and {@link TimeImpl.endFixedLoop}; everything else reads it.\n */\n\n/** The default fixed step, in seconds (`01-lifecycle-and-time.md` §2). */\nexport const DEFAULT_FIXED_DELTA_TIME: number = 1 / 60;\n\n/** The default upper clamp on one frame's delta, in seconds. */\nexport const DEFAULT_MAXIMUM_DELTA_TIME = 0.1;\n\n/** Milliseconds in one second. */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * Rejects a value that is outside a `Time` property's documented domain.\n *\n * @param property - The property being written, for the message.\n * @param value - The offending value.\n * @param domain - A prose description of the domain, for example `\"a positive finite number\"`.\n * @throws IgnifxError with code `IGX-0108` always.\n */\nfunction rejectTimeValue(property: string, value: number, domain: string): never {\n throw new IgnifxError(CoreErrorCode.invalidTimeValue, `time.${property} must be ${domain}; got ${String(value)}.`, {\n context: { property, value, domain },\n hint: \"Time values are seconds; a zero or negative fixed step would make the fixed loop unbounded.\",\n });\n}\n\n/**\n * The app clock.\n *\n * @remarks\n * **When a `fixedDeltaTime` write takes effect.** §2 allows the write \"between frames only (a set\n * during a frame takes effect at the next frame start)\". A write made while a frame is running is\n * therefore buffered and applied by the next {@link TimeImpl.beginFrame}, and the getter keeps\n * reporting the step the frame is actually running at — which is what makes §4's guarantee that\n * `fixedUpdate` receives `dt === time.fixedDeltaTime` hold even when a script changes the step from\n * inside a callback. A write made between frames applies immediately, because there is no frame for\n * it to disagree with.\n *\n * @internal\n */\nexport class TimeImpl implements Time {\n readonly #clock: Clock;\n\n readonly #startMs: number;\n\n #deltaTime = 0;\n\n #unscaledDeltaTime = 0;\n\n #fixedDeltaTime: number = DEFAULT_FIXED_DELTA_TIME;\n\n #pendingFixedDeltaTime: number | null = null;\n\n #timeScale = 1;\n\n #maximumDeltaTime: number = DEFAULT_MAXIMUM_DELTA_TIME;\n\n #time = 0;\n\n #unscaledTime = 0;\n\n #fixedTime = 0;\n\n #frameCount = 0;\n\n #inFixedStep = false;\n\n #fixedStepAlpha = 0;\n\n #isInsideFrame = false;\n\n /** Seconds of the raw delta the {@link Time.maximumDeltaTime} clamp discarded this frame. */\n droppedSeconds = 0;\n\n /** Whether `app.pause()` is in effect. */\n paused = false;\n\n /**\n * Creates the clock of one app.\n *\n * @param clock - The wall clock behind {@link Time.realtimeSinceStartup}.\n */\n constructor(clock: Clock) {\n this.#clock = clock;\n this.#startMs = clock.nowMs();\n }\n\n /**\n * Scaled seconds since the previous frame.\n *\n * @returns The scaled delta.\n */\n get deltaTime(): number {\n return this.#deltaTime;\n }\n\n /**\n * Wall-clock frame delta after the {@link Time.maximumDeltaTime} clamp.\n *\n * @returns The unscaled delta.\n */\n get unscaledDeltaTime(): number {\n return this.#unscaledDeltaTime;\n }\n\n /**\n * The size of one fixed step, in seconds.\n *\n * @returns The step the current frame is running at.\n */\n get fixedDeltaTime(): number {\n return this.#fixedDeltaTime;\n }\n\n /**\n * Changes the fixed step. A write made while a frame is running takes effect at the next frame\n * start (§2).\n *\n * @param value - The new step in seconds; must be positive and finite.\n * @throws IgnifxError with code `IGX-0108` when the value is not a positive finite number.\n */\n set fixedDeltaTime(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n rejectTimeValue(\"fixedDeltaTime\", value, \"a positive finite number of seconds\");\n }\n if (this.#isInsideFrame) {\n this.#pendingFixedDeltaTime = value;\n return;\n }\n this.#fixedDeltaTime = value;\n this.#pendingFixedDeltaTime = null;\n }\n\n /**\n * The multiplier applied to {@link Time.unscaledDeltaTime}.\n *\n * @returns The current scale.\n */\n get timeScale(): number {\n return this.#timeScale;\n }\n\n /**\n * Changes the time scale. `0` freezes scaled time and, with it, the fixed loop.\n *\n * @param value - The new scale; must be a finite number that is not negative.\n * @throws IgnifxError with code `IGX-0108` when the value is negative or not finite.\n */\n set timeScale(value: number) {\n if (!Number.isFinite(value) || value < 0) {\n rejectTimeValue(\"timeScale\", value, \"a finite number that is not negative\");\n }\n this.#timeScale = value;\n }\n\n /**\n * The upper clamp on one frame's delta, in seconds.\n *\n * @returns The clamp.\n */\n get maximumDeltaTime(): number {\n return this.#maximumDeltaTime;\n }\n\n /**\n * Changes the frame-delta clamp, which is also what bounds the number of fixed steps per frame.\n *\n * @param value - The new clamp in seconds; must be positive and finite.\n * @throws IgnifxError with code `IGX-0108` when the value is not a positive finite number.\n */\n set maximumDeltaTime(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n rejectTimeValue(\"maximumDeltaTime\", value, \"a positive finite number of seconds\");\n }\n this.#maximumDeltaTime = value;\n }\n\n /**\n * Scaled seconds since the app started running frames.\n *\n * @returns The scaled elapsed time.\n */\n get time(): number {\n return this.#time;\n }\n\n /**\n * Unscaled seconds since the app started running frames.\n *\n * @returns The unscaled elapsed time.\n */\n get unscaledTime(): number {\n return this.#unscaledTime;\n }\n\n /**\n * Scaled seconds advanced by fixed steps so far.\n *\n * @returns The fixed-step clock.\n */\n get fixedTime(): number {\n return this.#fixedTime;\n }\n\n /**\n * Wall-clock seconds since the app was created, unaffected by pause or time scale.\n *\n * @returns The reading of the injected clock, relative to app creation.\n */\n get realtimeSinceStartup(): number {\n return (this.#clock.nowMs() - this.#startMs) / MILLISECONDS_PER_SECOND;\n }\n\n /**\n * How many frames have started.\n *\n * @returns The frame counter, starting at `0`.\n */\n get frameCount(): number {\n return this.#frameCount;\n }\n\n /**\n * Whether the fixed loop is running.\n *\n * @returns `true` between {@link TimeImpl.beginFixedStep} and {@link TimeImpl.endFixedLoop}.\n */\n get inFixedStep(): boolean {\n return this.#inFixedStep;\n }\n\n /**\n * The interpolation alpha left over from the fixed loop.\n *\n * @returns `accumulator / fixedDeltaTime`, in `[0, 1)`.\n */\n get fixedStepAlpha(): number {\n return this.#fixedStepAlpha;\n }\n\n /**\n * Step 1 of the frame (`01-lifecycle-and-time.md` §3): applies a buffered `fixedDeltaTime`\n * change, clamps the raw delta, scales it, and advances the counters.\n *\n * @param rawDeltaSeconds - The delta the driver supplied, before clamping. Non-finite and\n * negative values are treated as zero rather than corrupting the clock: they come from a render\n * loop, not from game code, so a diagnostic is the right response, not a throw.\n */\n beginFrame(rawDeltaSeconds: number): void {\n const pending = this.#pendingFixedDeltaTime;\n if (pending !== null) {\n this.#fixedDeltaTime = pending;\n this.#pendingFixedDeltaTime = null;\n }\n this.#isInsideFrame = true;\n const raw = Number.isFinite(rawDeltaSeconds) && rawDeltaSeconds > 0 ? rawDeltaSeconds : 0;\n const clamped = raw > this.#maximumDeltaTime ? this.#maximumDeltaTime : raw;\n this.droppedSeconds = raw - clamped;\n this.#unscaledDeltaTime = clamped;\n this.#deltaTime = clamped * this.#timeScale;\n this.#time += this.#deltaTime;\n this.#unscaledTime += this.#unscaledDeltaTime;\n this.#frameCount += 1;\n }\n\n /** Marks the end of the frame, so a `fixedDeltaTime` write applies immediately again. */\n endFrame(): void {\n this.#isInsideFrame = false;\n }\n\n /** Enters one fixed step: raises `inFixedStep` and advances `fixedTime`. */\n beginFixedStep(): void {\n this.#inFixedStep = true;\n this.#fixedTime += this.#fixedDeltaTime;\n }\n\n /**\n * Leaves the fixed loop and publishes the interpolation alpha.\n *\n * @param accumulator - What is left in the fixed-step accumulator, in seconds.\n */\n endFixedLoop(accumulator: number): void {\n this.#inFixedStep = false;\n const alpha = accumulator / this.#fixedDeltaTime;\n if (alpha <= 0) {\n this.#fixedStepAlpha = 0;\n return;\n }\n // The documented domain is `[0, 1)`; a residue that rounds up to one would break interpolation\n // consumers that assume the exclusive upper bound.\n this.#fixedStepAlpha = alpha >= 1 ? 1 - Number.EPSILON : alpha;\n }\n\n /**\n * Applies the resolved `time` settings section at app creation\n * (`docs/architecture/04-extensions.md` §5).\n *\n * @param fixedDeltaTime - The initial fixed step, when the section declares one.\n * @param maximumDeltaTime - The initial delta clamp, when the section declares one.\n * @param timeScale - The initial time scale, when the section declares one.\n */\n applySettings(fixedDeltaTime?: number, maximumDeltaTime?: number, timeScale?: number): void {\n if (fixedDeltaTime !== undefined) {\n this.fixedDeltaTime = fixedDeltaTime;\n }\n if (maximumDeltaTime !== undefined) {\n this.maximumDeltaTime = maximumDeltaTime;\n }\n if (timeScale !== undefined) {\n this.timeScale = timeScale;\n }\n }\n}\n","import { componentInternals } from \"./internals.js\";\nimport type { ComponentClassInfo } from \"./component-registry.js\";\nimport type { ComponentType } from \"./component-type.js\";\nimport type { Component } from \"./component.js\";\n\n/**\n * The world's live per-type component registry — what `world.components(Type)` returns and what\n * every system iterates (`docs/architecture/02-scene-graph.md` §9).\n *\n * @remarks\n * A component is filed under **every** class in its ancestor chain, so a query for `Script` really\n * does return every script and a query for `Component` returns everything, with no prototype walk\n * and no filtering per frame. Each bucket records where the component sits, so removal is a\n * swap-remove rather than a scan: `add` and `remove` are both O(ancestors), which is a small\n * constant.\n *\n * The array a query returns is the bucket itself: obtaining it costs nothing, its identity is\n * stable for the lifetime of the world, and it is live — a component added later shows up in it.\n * Swap-remove means the order is *not* creation order and changes when a component is destroyed;\n * systems that need deterministic ordering iterate `world.scriptsWith(kind)` instead.\n */\n\n/** Shared empty bucket for a type nothing has ever been filed under. */\nconst EMPTY_BUCKET: readonly Component[] = Object.freeze([]);\n\n/**\n * The per-type component index of one world.\n *\n * @internal\n */\nexport class ComponentStore {\n readonly #buckets = new Map<ComponentType, Component[]>();\n\n /**\n * Files a component under its class and every class it derives from.\n *\n * @param component - The component to file.\n * @param info - Its class info, whose `ancestors` list drives the filing.\n */\n add(component: Component, info: ComponentClassInfo): void {\n const internals = componentInternals(component);\n const ancestors = info.ancestors;\n const slots = internals.storeSlots;\n slots.length = ancestors.length;\n for (let index = 0; index < ancestors.length; index += 1) {\n const type = ancestors[index];\n if (type === undefined) {\n continue;\n }\n const bucket = this.#bucketFor(type);\n slots[index] = bucket.length;\n bucket.push(component);\n }\n }\n\n /**\n * Removes a component from every bucket it was filed under, by swapping the last entry into its\n * slot.\n *\n * @param component - The component to remove.\n * @param info - Its class info, whose `ancestors` list matches the recorded slots.\n */\n remove(component: Component, info: ComponentClassInfo): void {\n const internals = componentInternals(component);\n const ancestors = info.ancestors;\n const slots = internals.storeSlots;\n for (let index = 0; index < ancestors.length; index += 1) {\n const type = ancestors[index];\n const slot = slots[index];\n if (type === undefined || slot === undefined || slot < 0) {\n continue;\n }\n const bucket = this.#buckets.get(type);\n if (bucket === undefined) {\n continue;\n }\n const last = bucket.length - 1;\n const moved = bucket[last];\n if (slot !== last && moved !== undefined) {\n bucket[slot] = moved;\n const movedSlots = componentInternals(moved).storeSlots;\n const movedIndex = indexOfAncestor(moved, type);\n if (movedIndex >= 0) {\n movedSlots[movedIndex] = slot;\n }\n }\n bucket.pop();\n slots[index] = -1;\n }\n slots.length = 0;\n }\n\n /**\n * The live bucket for a type.\n *\n * @typeParam T - The component instance type.\n * @param type - The component class, abstract or concrete.\n * @returns The live array of matching components. Never allocates once the bucket exists.\n */\n components<T extends Component>(type: ComponentType<T>): readonly T[] {\n const bucket = this.#buckets.get(type);\n if (bucket === undefined) {\n // Nothing of this type has ever existed. Returning the shared frozen empty array keeps the\n // query allocation-free; the bucket is created the moment something is filed under it.\n // Boundary assertion (coding standards §5.2): an empty array of `Component` is an empty array\n // of any subtype.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return EMPTY_BUCKET as unknown as readonly T[];\n }\n // Boundary assertion (coding standards §5.2): the invariant is that a component is only ever\n // filed under classes in its own ancestor chain, so every member of the bucket for `type` is a\n // `T`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return bucket as unknown as readonly T[];\n }\n\n /** Empties every bucket, for world disposal. */\n clear(): void {\n for (const bucket of this.#buckets.values()) {\n bucket.length = 0;\n }\n this.#buckets.clear();\n }\n\n /**\n * The bucket for a type, created on demand so that `components(Type)` returns a stable identity\n * from the first component onwards.\n *\n * @param type - The component class.\n * @returns The live bucket.\n */\n #bucketFor(type: ComponentType): Component[] {\n let bucket = this.#buckets.get(type);\n if (bucket === undefined) {\n bucket = [];\n this.#buckets.set(type, bucket);\n }\n return bucket;\n }\n}\n\n/**\n * Where a class sits in a component's ancestor chain, so a swap-remove can fix up the moved\n * component's recorded slot.\n *\n * @param component - The component that was moved into another slot.\n * @param type - The bucket's class.\n * @returns The index in the component's ancestor list, or `-1`.\n */\nfunction indexOfAncestor(component: Component, type: ComponentType): number {\n const info = componentInternals(component).info;\n if (info === null) {\n return -1;\n }\n const ancestors = info.ancestors;\n for (let index = 0; index < ancestors.length; index += 1) {\n if (ancestors[index] === type) {\n return index;\n }\n }\n return -1;\n}\n","import { componentInternals } from \"./internals.js\";\nimport type { Component } from \"./component.js\";\n\n/**\n * Tracked references (`docs/architecture/02-scene-graph.md` §4): a field declared with `entityRef`\n * or `componentRef` is set to `null` when its target is destroyed, in the same destroy flush,\n * before any `onDestroy` of the holder runs. Plain class fields holding entities or components are\n * not* tracked; game code checks `isDestroyed` before using those.\n *\n * @remarks\n * **How it is implemented, and why not with accessors.** The obvious design intercepts every write\n * to a tracked field with a generated accessor, so the tracker can index holders by target. Coding\n * standards §5.3 bans `Object.defineProperty` tricks and prototype mutation, which is what\n * generating those accessors requires, so the tracker takes the other route: it keeps the small set\n * of components whose class declares at least one tracked field, and the destroy flush makes one\n * pass over that set, nulling any tracked field whose current value is being destroyed. Tracked\n * fields stay ordinary data properties — `this.target = other` is a plain assignment with no hidden\n * cost — and the pass is O(holders x tracked fields) once per flush that destroys anything, not per\n * frame and not per entity.\n */\n\n/**\n * The set of components with tracked reference fields, and the flush-time nulling pass.\n *\n * @internal\n */\nexport class ReferenceTracker {\n /** Every attached component whose class declares at least one tracked field. */\n readonly #holders: Component[] = [];\n\n /** Where each holder sits in `#holders`, so removal is a swap-remove. */\n readonly #slots = new Map<Component, number>();\n\n /**\n * How many components are being watched. Exposed for tests and diagnostics.\n *\n * @returns The holder count.\n */\n get size(): number {\n return this.#holders.length;\n }\n\n /**\n * Starts watching a component, if its class declares tracked fields.\n *\n * @param component - The freshly attached component.\n */\n watch(component: Component): void {\n const info = componentInternals(component).info;\n if (info === null || info.trackedFields.length === 0 || this.#slots.has(component)) {\n return;\n }\n this.#slots.set(component, this.#holders.length);\n this.#holders.push(component);\n }\n\n /**\n * Stops watching a component.\n *\n * @param component - The component being released.\n */\n unwatch(component: Component): void {\n const slot = this.#slots.get(component);\n if (slot === undefined) {\n return;\n }\n this.#slots.delete(component);\n const last = this.#holders.length - 1;\n const moved = this.#holders[last];\n if (slot !== last && moved !== undefined) {\n this.#holders[slot] = moved;\n this.#slots.set(moved, slot);\n }\n this.#holders.pop();\n }\n\n /**\n * Nulls every tracked field pointing at anything in `doomed`. Run once at the top of the destroy\n * flush, before any `onDisable` or `onDestroy`, so a holder's own `onDestroy` already sees `null`\n * (`docs/architecture/02-scene-graph.md` §4).\n *\n * @param doomed - The entities and components about to be released. `null` is never a member, so\n * a field that is already `null` is left alone.\n */\n nullReferencesTo(doomed: ReadonlySet<unknown>): void {\n if (doomed.size === 0 || this.#holders.length === 0) {\n return;\n }\n const holders = this.#holders;\n for (let index = 0; index < holders.length; index += 1) {\n const holder = holders[index];\n if (holder === undefined) {\n continue;\n }\n const info = componentInternals(holder).info;\n if (info === null) {\n continue;\n }\n const fields = info.trackedFields;\n // Boundary assertion (coding standards §5.2): a tracked field is an ordinary data property\n // whose name came from the component's own schema, so reading and clearing it by name is\n // exactly what the serializer does with the same names.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const bag = holder as unknown as Record<string, unknown>;\n for (let field = 0; field < fields.length; field += 1) {\n const name = fields[field];\n if (name === undefined) {\n continue;\n }\n if (doomed.has(bag[name])) {\n bag[name] = null;\n }\n }\n }\n }\n\n /** Forgets every holder, for world disposal. */\n clear(): void {\n this.#holders.length = 0;\n this.#slots.clear();\n }\n}\n","/**\n * Free-form grouping labels on an entity (`docs/architecture/02-scene-graph.md` §7). Tags are for\n * grouping and lookup — `world.findByTag` keeps an index over them — never for behaviour dispatch,\n * which is the string-messaging anti-pattern the standard rejects\n * (`docs/architecture/03-scripting-and-components.md` §9).\n */\n\n/**\n * What a {@link TagSet} tells its owner when it changes, so the world can keep its `findByTag`\n * index current.\n *\n * @internal\n */\nexport type TagSetObserver = (tag: string, added: boolean) => void;\n\n/**\n * The mutable set of tags on one entity.\n *\n * @example\n * ```ts\n * entity.tags.add(\"enemy\");\n * entity.tags.has(\"enemy\"); // true\n * for (const tag of entity.tags) {\n * console.log(tag);\n * }\n * ```\n *\n * @public\n */\nexport class TagSet {\n readonly #tags = new Set<string>();\n\n readonly #observer: TagSetObserver | null;\n\n /**\n * Creates a tag set.\n *\n * @param observer - Called after every effective add or delete, so the world can maintain its tag\n * index. Entities always pass one; a standalone set can omit it.\n *\n * @internal\n */\n constructor(observer?: TagSetObserver) {\n this.#observer = observer ?? null;\n }\n\n /**\n * How many tags the entity carries.\n *\n * @returns The tag count.\n */\n get size(): number {\n return this.#tags.size;\n }\n\n /**\n * Adds a tag. Adding a tag the entity already carries is a no-op.\n *\n * @param tag - The tag.\n * @returns This set, so calls chain.\n */\n add(tag: string): this {\n if (this.#tags.has(tag)) {\n return this;\n }\n this.#tags.add(tag);\n this.#observer?.(tag, true);\n return this;\n }\n\n /**\n * Reports whether the entity carries a tag.\n *\n * @param tag - The tag.\n * @returns `true` when the tag is present.\n */\n has(tag: string): boolean {\n return this.#tags.has(tag);\n }\n\n /**\n * Removes a tag.\n *\n * @param tag - The tag.\n * @returns `true` when the tag was present and has been removed.\n */\n delete(tag: string): boolean {\n if (!this.#tags.delete(tag)) {\n return false;\n }\n this.#observer?.(tag, false);\n return true;\n }\n\n /**\n * Every tag, in insertion order.\n *\n * @returns An iterator over the tags.\n */\n values(): IterableIterator<string> {\n return this.#tags.values();\n }\n\n /**\n * Every tag, in insertion order, so a tag set can be spread or used in `for…of`.\n *\n * @returns An iterator over the tags.\n */\n [Symbol.iterator](): IterableIterator<string> {\n return this.#tags.values();\n }\n\n /**\n * Removes every tag, notifying the observer once per tag so indices stay correct.\n *\n * @internal\n */\n clear(): void {\n if (this.#tags.size === 0) {\n return;\n }\n // Snapshot: the observer runs while the set is being drained, and must not see a half-mutated\n // iterator.\n const tags = [...this.#tags];\n this.#tags.clear();\n const observer = this.#observer;\n if (observer !== null) {\n for (let index = 0; index < tags.length; index += 1) {\n const tag = tags[index];\n if (tag !== undefined) {\n observer(tag, false);\n }\n }\n }\n }\n}\n","import { entityInternals } from \"./internals.js\";\nimport type { Entity } from \"./entity.js\";\n\n/**\n * The `entity.find(\"Body/Arm.L\")` path grammar (`docs/architecture/02-scene-graph.md` §4).\n *\n * @remarks\n * Deliberately fragile — the Godot `get_node` lesson — and therefore allowed only in tests,\n * examples, and tools, where a hard-coded path is the point; `ignifx/no-entity-find-in-src` flags\n * it anywhere else. Serialized `entityRef`/`componentRef` fields and `requireComponent` are the\n * supported way to link objects.\n *\n * The grammar is exactly:\n *\n * - segments are separated by `/`;\n * - a leading `/` resolves from the roots of the entity's **own scene instance**, not the world, so\n * an additive HUD scene cannot accidentally reach into the gameplay scene (§10 says cross-scene\n * links go through tags, uids, or a service);\n * - `..` is the parent and `.` is the entity itself, but **only as whole segments** — a name may\n * contain dots, which is why `Arm.L` resolves as a name and not as a path;\n * - empty segments are skipped, so `\"a//b\"` and `\"a/b/\"` mean `\"a/b\"`;\n * - anything that does not resolve yields `null`, because a lookup that finds nothing is an\n * expected absence, not an error (coding standards §5.5).\n */\n\n/**\n * Resolves a path relative to an entity.\n *\n * @param from - The entity the path is relative to.\n * @param path - The path.\n * @returns The entity the path names, or `null`.\n *\n * @internal\n */\nexport function resolvePath(from: Entity, path: string): Entity | null {\n if (path === \"\") {\n return null;\n }\n let current: Entity | null = from;\n let rest = path;\n if (path.startsWith(\"/\")) {\n rest = path.slice(1);\n if (rest === \"\") {\n return null;\n }\n const segments = rest.split(\"/\");\n const first = nextSegment(segments, 0);\n if (first === null) {\n return null;\n }\n current = findRoot(from, first.value);\n return current === null ? null : walk(current, segments, first.index + 1);\n }\n const segments = rest.split(\"/\");\n return walk(current, segments, 0);\n}\n\n/**\n * Walks the remaining segments from an entity.\n *\n * @param start - Where to walk from.\n * @param segments - Every segment of the path.\n * @param offset - The first segment to consume.\n * @returns The entity the walk lands on, or `null`.\n */\nfunction walk(start: Entity, segments: readonly string[], offset: number): Entity | null {\n let current: Entity | null = start;\n for (let index = offset; index < segments.length; index += 1) {\n const segment = segments[index];\n if (segment === undefined || segment === \"\" || segment === \".\") {\n continue;\n }\n if (current === null) {\n return null;\n }\n if (segment === \"..\") {\n current = current.parent;\n continue;\n }\n current = findChildNamed(current, segment);\n }\n return current;\n}\n\n/**\n * The first non-empty segment at or after an index.\n *\n * @param segments - Every segment of the path.\n * @param offset - Where to start looking.\n * @returns The segment and the index it was found at, or `null` when there is none.\n */\nfunction nextSegment(segments: readonly string[], offset: number): { value: string; index: number } | null {\n for (let index = offset; index < segments.length; index += 1) {\n const segment = segments[index];\n if (segment !== undefined && segment !== \"\") {\n return { value: segment, index };\n }\n }\n return null;\n}\n\n/**\n * Finds a named root of the entity's scene instance.\n *\n * @param from - The entity whose scene is searched.\n * @param name - The root's name.\n * @returns The first root with that name, or `null`.\n */\nfunction findRoot(from: Entity, name: string): Entity | null {\n const roots = entityInternals(from).scene.roots;\n for (let index = 0; index < roots.length; index += 1) {\n const root = roots[index];\n if (root !== undefined && root.name === name) {\n return root;\n }\n }\n return null;\n}\n\n/**\n * Finds a named direct child.\n *\n * @param parent - The entity to search.\n * @param name - The child's name.\n * @returns The first child with that name, or `null`.\n */\nfunction findChildNamed(parent: Entity, name: string): Entity | null {\n const children = parent.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined && child.name === name) {\n return child;\n }\n }\n return null;\n}\n","import { componentInternals } from \"../component/internals.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { isValidLayer, MAX_LAYERS } from \"../layers/layer-table.js\";\nimport { readCallback } from \"../lifecycle/callbacks.js\";\nimport { linkParent, reparentKeepingWorld, setNodeName, setNodeSelfVisible, tagNode } from \"../lite/node.js\";\nimport { validateProps } from \"../schema/validate.js\";\nimport { Signal } from \"../signal/signal.js\";\nimport { TagSet } from \"../tags/tag-set.js\";\nimport { attachTransform, transformIsNotRemovable } from \"../transform/transform-internals.js\";\nimport { Transform } from \"../transform/transform.js\";\nimport { resolvePath } from \"./entity-path.js\";\nimport { ENTITY_INTERNALS, entityInternals } from \"./internals.js\";\nimport type { EntityInternals } from \"./internals.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { ComponentInit, ComponentType, ConcreteComponentType } from \"../component/component-type.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { EntityHandle } from \"../handles/handle.js\";\nimport type { LiteSceneNode } from \"../lite/node.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\nimport type { Schema } from \"../schema/types.js\";\nimport type { SceneAsset } from \"../serialization/scene-asset.js\";\nimport type { TagSetObserver } from \"../tags/tag-set.js\";\nimport type { WorldHost } from \"../world/world-host.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * A node of the scene tree (`docs/architecture/02-scene-graph.md` §4). Every entity has a stable\n * id, a name, tags, a layer, an active flag, an ordered list of components, and exactly one\n * `Transform` wrapping its Babylon Lite node.\n *\n * @remarks\n * Entities are created by the world, never with `new`: `world.createEntity()` allocates the Lite\n * node, the handle, and the transform together. Destroying one queues its whole subtree for the\n * current frame's destroy flush; it reports `isDestroyed === true` immediately and throws\n * `IGX-0101` on any further structural change (`addComponent`, `removeComponent`, `setParent`,\n * `active`, `layer`, `name`, `isStatic`, `tags.add`/`delete`). Transform writes are deliberately\n * not* guarded: they are the hottest path in the engine and a write to a doomed node is harmless.\n *\n * @example\n * ```ts\n * const player = world.createEntity(\"Player\", { position: { x: 0, y: 1, z: 0 } });\n * player.layer = world.layers.indexOf(\"Player\");\n * player.tags.add(\"player\");\n * const mover = player.addComponent(Mover, { speed: 8 });\n * const gun = world.createEntity(\"Gun\", { parent: player });\n * ```\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- the merged interface below declares one engine-owned property that the constructor always assigns.\nexport class Entity {\n /**\n * Creates an entity. The world calls this; game code calls `world.createEntity`.\n *\n * @param host - The owning world.\n * @param handle - The dense runtime handle already allocated for this entity.\n * @param uid - The stable identifier.\n * @param node - The Lite node the transform will view.\n * @param name - The display name.\n * @param scene - The scene instance that owns the entity.\n *\n * @internal\n */\n constructor(\n host: WorldHost,\n handle: EntityHandle,\n uid: string,\n node: LiteSceneNode,\n name: string,\n scene: SceneInstance,\n ) {\n const observer: TagSetObserver = (tag, added) => {\n host.notifyTagChanged(this, tag, added);\n };\n this[ENTITY_INTERNALS] = {\n host,\n node,\n handle,\n uid,\n serial: host.nextSerial(),\n tags: new TagSet(observer),\n transform: null,\n name,\n scene,\n origin: null,\n parent: null,\n children: [],\n components: [],\n active: true,\n activeInHierarchy: true,\n layer: 0,\n isStatic: false,\n hasAwoken: false,\n isDestroyed: false,\n isReleased: false,\n isDestroyQueued: false,\n onChildAdded: null,\n onChildRemoved: null,\n onParentChanged: null,\n onActiveChanged: null,\n onComponentAdded: null,\n onComponentRemoved: null,\n onDestroyed: null,\n };\n tagNode(node, { entity: handle });\n const transform = new Transform();\n attachTransform(transform, node);\n this[ENTITY_INTERNALS].transform = transform;\n this.#attach(transform);\n }\n\n /**\n * The stable ULID; the key files use to reference this entity.\n *\n * @returns The identifier.\n */\n get uid(): string {\n return entityInternals(this).uid;\n }\n\n /**\n * The dense runtime handle; `world.getEntityByHandle` stops resolving it after destruction.\n *\n * @returns The handle.\n */\n get handle(): EntityHandle {\n return entityInternals(this).handle;\n }\n\n /**\n * The display name. Not unique, and never used for lookup by the engine\n * (`docs/architecture/02-scene-graph.md` §4).\n *\n * @returns The name.\n */\n get name(): string {\n return entityInternals(this).name;\n }\n\n set name(value: string) {\n const internals = this.#mutable(\"name\");\n internals.name = value;\n setNodeName(internals.node, value);\n }\n\n /**\n * The world that owns the entity.\n *\n * @returns The world.\n */\n get world(): World {\n return entityInternals(this).host.world;\n }\n\n /**\n * The scene instance the entity belongs to.\n *\n * @returns The owning scene instance.\n */\n get scene(): SceneInstance {\n return entityInternals(this).scene;\n }\n\n /**\n * The entity's transform. Every entity has one; it can be neither removed nor disabled.\n *\n * @returns The transform.\n */\n get transform(): Transform {\n const transform = entityInternals(this).transform;\n if (transform === null) {\n throw new IgnifxError(CoreErrorCode.componentNotAttached, \"This entity has no transform yet.\", {\n context: { entity: entityInternals(this).uid },\n });\n }\n return transform;\n }\n\n /**\n * The parent entity, or `null` when the entity is a root of its scene.\n *\n * @returns The parent, or `null`.\n */\n get parent(): Entity | null {\n return entityInternals(this).parent;\n }\n\n /**\n * The children, in creation order. The array is live; treat it as read-only.\n *\n * @returns The live child list.\n */\n get children(): readonly Entity[] {\n return entityInternals(this).children;\n }\n\n /**\n * The components, in attach order. The transform is always first.\n *\n * @returns The live component list.\n */\n get components(): readonly Component[] {\n return entityInternals(this).components;\n }\n\n /**\n * The free-form tags the world indexes for `world.findByTag`.\n *\n * @returns The tag set.\n */\n get tags(): TagSet {\n return entityInternals(this).tags;\n }\n\n /**\n * The entity's own active flag. Setting it to `false` disables every component in the subtree\n * (`onDisable`), hides the Lite subtree, and pauses their coroutines; setting it back reverses\n * that with `onEnable`, and `start` still runs only once ever\n * (`docs/architecture/01-lifecycle-and-time.md` §6).\n *\n * @returns The own flag.\n */\n get active(): boolean {\n return entityInternals(this).active;\n }\n\n set active(value: boolean) {\n const internals = this.#mutable(\"active\");\n if (internals.active === value) {\n return;\n }\n internals.active = value;\n internals.host.lifecycle.refreshActivation(this);\n internals.onActiveChanged?.emit(value);\n }\n\n /**\n * `active` and every ancestor's `active`. Materialised on change, never walked per read.\n *\n * @returns `true` when the entity and every ancestor are active.\n */\n get activeInHierarchy(): boolean {\n return entityInternals(this).activeInHierarchy;\n }\n\n /**\n * The layer slot, `0..31` (`docs/architecture/02-scene-graph.md` §7). Layers drive physics\n * collision matrices and raycast masks. Files store the layer *name*, so reordering the project\n * list is safe.\n *\n * @returns The slot index.\n */\n get layer(): number {\n return entityInternals(this).layer;\n }\n\n set layer(value: number) {\n if (!isValidLayer(value)) {\n throw new IgnifxError(CoreErrorCode.unknownLayer, `${String(value)} is not a layer slot.`, {\n context: { layer: value, limit: MAX_LAYERS },\n hint: \"Layers are integers 0 to 31; resolve a name with world.layers.indexOf(name).\",\n });\n }\n this.#mutable(\"layer\").layer = value;\n }\n\n /**\n * The immovability hint: `true` promises that the transform will not change after `awake`, which\n * lets the 2D batcher, physics, and navmesh treat the entity as static.\n *\n * @returns `true` when the entity is marked static.\n */\n get isStatic(): boolean {\n return entityInternals(this).isStatic;\n }\n\n set isStatic(value: boolean) {\n const internals = this.#mutable(\"isStatic\");\n if (internals.hasAwoken) {\n throw new IgnifxError(\n CoreErrorCode.mutationAfterDestroy,\n \"isStatic is set in files or before awake, and cannot change afterwards.\",\n { context: { entity: internals.uid, operation: \"isStatic\" } },\n );\n }\n internals.isStatic = value;\n }\n\n /**\n * The prefab link for an entity a scene file's `instance` entry produced\n * (`docs/architecture/02-scene-graph.md` §6). It is set on the instance root and on every entity\n * the instanced scene contributed, so tooling can show where an object came from.\n *\n * @remarks\n * The engine keeps no live link back to the prefab after load: editing the instanced scene does\n * not update loaded instances, and \"apply changes to prefab\" is editor work, post-1.0. The link\n * exists so that saving re-emits the subtree as an `instance` entry with recomputed overrides\n * (`06-serialization-and-scene-format.md` §5) rather than as plain entities.\n *\n * @returns The link, or `null` for an entity the scene declared itself or code created.\n *\n * @example\n * ```ts\n * const link = enemy.prefab;\n * if (link !== null && link.instanceRoot === enemy) {\n * app.log.info(`${enemy.name} is the root of an instance of ${link.address}`);\n * }\n * ```\n */\n get prefab(): EntityPrefabLink | null {\n const origin = entityInternals(this).origin;\n if (origin === null) {\n return null;\n }\n const own = origin.instanced;\n if (own !== null) {\n return { asset: own.asset, address: own.address, instanceRoot: this };\n }\n const root = origin.instanceRoot;\n const link = root === null ? null : (entityInternals(root).origin?.instanced ?? null);\n return link === null || root === null ? null : { asset: link.asset, address: link.address, instanceRoot: root };\n }\n\n /**\n * `true` from the moment `destroy()` is called, long before the destroy flush runs.\n *\n * @returns `true` once the entity has been queued for destruction.\n */\n get isDestroyed(): boolean {\n return entityInternals(this).isDestroyed;\n }\n\n /**\n * Emitted after a child is added, whether by creation or by reparenting.\n *\n * @returns The signal, created on first access.\n */\n get onChildAdded(): Signal<Entity> {\n const internals = entityInternals(this);\n internals.onChildAdded ??= internals.host.createSignal<Entity>();\n return internals.onChildAdded;\n }\n\n /**\n * Emitted after a child is removed.\n *\n * @returns The signal, created on first access.\n */\n get onChildRemoved(): Signal<Entity> {\n const internals = entityInternals(this);\n internals.onChildRemoved ??= internals.host.createSignal<Entity>();\n return internals.onChildRemoved;\n }\n\n /**\n * Emitted with the new parent after this entity is reparented.\n *\n * @returns The signal, created on first access.\n */\n get onParentChanged(): Signal<Entity | null> {\n const internals = entityInternals(this);\n internals.onParentChanged ??= internals.host.createSignal<Entity | null>();\n return internals.onParentChanged;\n }\n\n /**\n * Emitted with the new value when the entity's **own** active flag changes. An ancestor's change\n * does not emit it; read `activeInHierarchy` for the effective state.\n *\n * @returns The signal, created on first access.\n */\n get onActiveChanged(): Signal<boolean> {\n const internals = entityInternals(this);\n internals.onActiveChanged ??= internals.host.createSignal<boolean>();\n return internals.onActiveChanged;\n }\n\n /**\n * Emitted with each component attached to this entity, synchronously at the end of\n * `addComponent`, after the component's `onAttach` has run\n * (`docs/architecture/02-scene-graph.md` §8). Extensions that key work off an entity's component\n * set — the physics extension recomputing `Rigidbody.collisionEvents`, say — listen here rather\n * than polling `entity.components`. Costs nothing until something connects.\n *\n * @returns The signal, created on first access.\n */\n get onComponentAdded(): Signal<Component> {\n const internals = entityInternals(this);\n internals.onComponentAdded ??= internals.host.createSignal<Component>();\n return internals.onComponentAdded;\n }\n\n /**\n * Emitted with each component the destroy flush removes from this entity, after it has left\n * `entity.components` and before its `onDetach` runs. Removal is deferred, so this fires in the\n * destroy flush rather than inside `removeComponent`.\n *\n * @returns The signal, created on first access.\n */\n get onComponentRemoved(): Signal<Component> {\n const internals = entityInternals(this);\n internals.onComponentRemoved ??= internals.host.createSignal<Component>();\n return internals.onComponentRemoved;\n }\n\n /**\n * Emitted in the destroy flush, after the entity's components have run `onDestroy`. `Signal`'s\n * `{ owner }` option uses it to detach handlers automatically.\n *\n * @returns The signal, created on first access.\n */\n get onDestroyed(): Signal<Entity> {\n const internals = entityInternals(this);\n internals.onDestroyed ??= new Signal<Entity>();\n return internals.onDestroyed;\n }\n\n /**\n * Moves the entity under a new parent, or to the root of its scene.\n *\n * @param parent - The new parent, or `null` to detach to the scene root.\n * @param options - How the entity's transform is treated across the move:\n * `worldPositionStays` is `true` by default and keeps the world transform, while `false` keeps\n * the local values.\n * @throws IgnifxError with code `IGX-0306` when the new parent is inside this entity's own\n * subtree, and `IGX-0101` when either entity has been destroyed.\n *\n * @example\n * ```ts\n * gun.setParent(hand); // snaps to the hand, keeping world pose\n * gun.setParent(hand, { worldPositionStays: false }); // keeps its local offset instead\n * ```\n */\n setParent(parent: Entity | null, options?: SetParentOptions): void {\n const internals = this.#mutable(\"setParent\");\n if (parent === internals.parent) {\n return;\n }\n if (parent !== null) {\n if (parent.isDestroyed) {\n throw destroyedError(entityInternals(parent).uid, \"setParent\");\n }\n if (parent === this || parent.isDescendantOf(this)) {\n throw new IgnifxError(\n CoreErrorCode.parentingCycle,\n `${internals.name} cannot be parented to ${parent.name}, which is inside its own subtree.`,\n { context: { entity: internals.uid, parent: entityInternals(parent).uid } },\n );\n }\n }\n const previous = internals.parent;\n if (previous === null) {\n internals.scene.removeRoot(this);\n } else {\n const siblings = entityInternals(previous).children;\n const index = siblings.indexOf(this);\n if (index >= 0) {\n siblings.splice(index, 1);\n }\n }\n internals.parent = parent;\n if (parent === null) {\n internals.scene.addRoot(this);\n } else {\n entityInternals(parent).children.push(this);\n }\n const keepWorld = options?.worldPositionStays ?? true;\n const parentNode = parent === null ? null : entityInternals(parent).node;\n if (keepWorld) {\n reparentKeepingWorld(internals.node, parentNode);\n } else {\n linkParent(internals.node, parentNode);\n }\n if (parent !== null && entityInternals(parent).scene !== internals.scene) {\n internals.host.moveToScene(this, entityInternals(parent).scene);\n }\n internals.host.lifecycle.refreshActivation(this);\n if (previous !== null) {\n entityInternals(previous).onChildRemoved?.emit(this);\n }\n if (parent !== null) {\n entityInternals(parent).onChildAdded?.emit(this);\n }\n internals.onParentChanged?.emit(parent);\n }\n\n /**\n * Resolves a path relative to this entity — `\"Body/Arm.L\"`, `\"../Sibling\"`, `\"/Root/Child\"`.\n *\n * @remarks\n * Deliberately fragile, and allowed only in tests, examples, and tools: the\n * `ignifx/no-entity-find-in-src` rule flags it anywhere else. Use `entityRef`/`componentRef`\n * fields or `requireComponent` to link objects (`docs/architecture/02-scene-graph.md` §4).\n *\n * @param path - The path. A leading `/` resolves from the roots of this entity's scene instance;\n * `..` is the parent and `.` is this entity, as whole segments only, so a name may contain dots.\n * @returns The entity, or `null` when the path resolves to nothing.\n */\n find(path: string): Entity | null {\n return resolvePath(this, path);\n }\n\n /**\n * Finds a descendant satisfying a predicate.\n *\n * @param predicate - Called with each candidate; the first `true` wins.\n * @param deep - `true` (the default) searches the whole subtree depth-first; `false` searches\n * direct children only.\n * @returns The first match, or `null`.\n */\n findChild(predicate: (entity: Entity) => boolean, deep: boolean = true): Entity | null {\n const children = entityInternals(this).children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child === undefined) {\n continue;\n }\n if (predicate(child)) {\n return child;\n }\n if (deep) {\n const found = child.findChild(predicate, true);\n if (found !== null) {\n return found;\n }\n }\n }\n return null;\n }\n\n /**\n * Reports whether this entity is anywhere below another in the tree.\n *\n * @param other - The candidate ancestor.\n * @returns `true` when `other` is a strict ancestor of this entity.\n */\n isDescendantOf(other: Entity): boolean {\n let current = entityInternals(this).parent;\n while (current !== null) {\n if (current === other) {\n return true;\n }\n current = entityInternals(current).parent;\n }\n return false;\n }\n\n /**\n * The topmost ancestor.\n *\n * @returns The root of this entity's branch, which is this entity when it has no parent.\n */\n root(): Entity {\n return rootOf(this);\n }\n\n /**\n * Attaches a component.\n *\n * @remarks\n * The engine constructs the class with no arguments, assigns its identity, applies schema\n * defaults then `init`, calls `onAttach`, and finally runs the enable transition — so `awake`\n * runs in the next lifecycle flush, or immediately and nested when `addComponent` is called from\n * inside a callback (`docs/architecture/01-lifecycle-and-time.md` §4). Everything a class lists in\n * `static requires` is added first if it is missing.\n *\n * @typeParam T - The component type.\n * @param type - The component class.\n * @param init - Initial values for the class's schema fields.\n * @returns The attached component.\n * @throws IgnifxError with code `IGX-0202` when the class does not allow multiple instances and\n * the entity already has one, `IGX-0605`/`IGX-0606`/`IGX-0607` when `init` does not match the\n * schema, and `IGX-0101` when the entity has been destroyed.\n */\n addComponent<T extends Component>(type: ConcreteComponentType<T>, init?: ComponentInit<T>): T {\n const internals = this.#mutable(\"addComponent\");\n const host = internals.host;\n const info = host.registry.describe(type);\n if (!info.allowMultiple && this.getComponent(type) !== null) {\n throw new IgnifxError(\n CoreErrorCode.multipleComponentsNotAllowed,\n `${type.prototype.constructor.name} does not allow multiple instances on one entity.`,\n { context: { component: type.prototype.constructor.name, entity: internals.uid } },\n );\n }\n for (let index = 0; index < info.requires.length; index += 1) {\n const required = info.requires[index];\n if (required !== undefined && this.getComponent(required) === null) {\n // Boundary assertion (coding standards §5.2): `requires` names classes the engine has to be\n // able to construct; a class listed there without a no-argument constructor is a\n // declaration bug that surfaces here as a construction failure.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n this.addComponent(required as ConcreteComponentType);\n }\n }\n const component = new type();\n const schema = info.schema;\n if (schema !== null && init !== undefined) {\n applyComponentInit(component, schema, init, type.prototype.constructor.name);\n }\n this.#attach(component);\n host.lifecycle.refreshEnabled(component);\n return component;\n }\n\n /**\n * The first component matching a class, by identity **or** inheritance — `getComponent(Script)`\n * returns the first script.\n *\n * @typeParam T - The component type.\n * @param type - The component class, abstract or concrete.\n * @returns The first match in attach order, or `null`. Cost is linear in the entity's component\n * count, so cache the result in `awake`.\n */\n getComponent<T extends Component>(type: ComponentType<T>): T | null {\n const components = entityInternals(this).components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined && matches(component, type)) {\n return component;\n }\n }\n return null;\n }\n\n /**\n * The first component matching a class, requiring it to be there — the supported way to link\n * components (`docs/architecture/03-scripting-and-components.md` §8).\n *\n * @typeParam T - The component type.\n * @param type - The component class.\n * @returns The first match in attach order.\n * @throws IgnifxError with code `IGX-0201` when the entity has no such component.\n */\n requireComponent<T extends Component>(type: ComponentType<T>): T {\n const found = this.getComponent(type);\n if (found === null) {\n const internals = entityInternals(this);\n throw new IgnifxError(\n CoreErrorCode.requiredComponentMissing,\n `${internals.name} has no ${type.prototype.constructor.name}.`,\n {\n context: { component: type.prototype.constructor.name, entity: internals.uid },\n hint: \"Add it with entity.addComponent, or declare it in the requiring class's `static requires`.\",\n },\n );\n }\n return found;\n }\n\n /**\n * Every component matching a class, by identity or inheritance.\n *\n * @typeParam T - The component type.\n * @param type - The component class.\n * @returns A freshly allocated array in attach order; empty when there is no match.\n */\n getComponents<T extends Component>(type: ComponentType<T>): T[] {\n const found: T[] = [];\n const components = entityInternals(this).components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined && matches(component, type)) {\n found.push(component);\n }\n }\n return found;\n }\n\n /**\n * The first matching component on this entity or anywhere below it, depth-first.\n *\n * @typeParam T - The component type.\n * @param type - The component class.\n * @param includeInactive - `false` (the default) skips entities that are inactive in the\n * hierarchy.\n * @returns The first match, or `null`.\n */\n getComponentInChildren<T extends Component>(type: ComponentType<T>, includeInactive: boolean = false): T | null {\n if (includeInactive || this.activeInHierarchy) {\n const own = this.getComponent(type);\n if (own !== null) {\n return own;\n }\n }\n const children = entityInternals(this).children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child === undefined) {\n continue;\n }\n const found = child.getComponentInChildren(type, includeInactive);\n if (found !== null) {\n return found;\n }\n }\n return null;\n }\n\n /**\n * Every matching component on this entity and everything below it, depth-first.\n *\n * @typeParam T - The component type.\n * @param type - The component class.\n * @param includeInactive - `false` (the default) skips entities that are inactive in the\n * hierarchy.\n * @returns A freshly allocated array.\n */\n getComponentsInChildren<T extends Component>(type: ComponentType<T>, includeInactive: boolean = false): T[] {\n const found: T[] = [];\n collectInChildren(this, type, includeInactive, found);\n return found;\n }\n\n /**\n * The first matching component on this entity or any ancestor.\n *\n * @typeParam T - The component type.\n * @param type - The component class.\n * @returns The first match walking up from this entity, or `null`.\n */\n getComponentInParent<T extends Component>(type: ComponentType<T>): T | null {\n return findInParents(this, type);\n }\n\n /**\n * Reports whether the entity carries a component of a class.\n *\n * @param type - The component class.\n * @returns `true` when at least one matches.\n */\n hasComponent(type: ComponentType): boolean {\n return this.getComponent(type) !== null;\n }\n\n /**\n * Queues one component for destruction. It stays usable until the destroy flush.\n *\n * @param component - The component to remove; it must be attached to this entity.\n * @throws IgnifxError with code `IGX-0205` when the component is the entity's transform.\n */\n removeComponent(component: Component): void {\n const internals = entityInternals(this);\n if (component === internals.transform) {\n throw transformIsNotRemovable();\n }\n if (componentInternals(component).entity !== this) {\n return;\n }\n internals.host.lifecycle.queueDestroyComponent(component);\n }\n\n /**\n * Queues this entity and its whole subtree for the current frame's destroy flush. `isDestroyed`\n * becomes `true` immediately; `onDisable` and `onDestroy` run in the flush, children before\n * parents (`docs/architecture/01-lifecycle-and-time.md` §6). Calling it twice is a no-op.\n */\n destroy(): void {\n const internals = entityInternals(this);\n if (internals.isReleased) {\n return;\n }\n internals.host.lifecycle.queueDestroyEntity(this);\n }\n\n /**\n * Runs the destroy flush for this entity right now, rather than at the end of the frame. It\n * exists for tooling and tests.\n *\n * @throws IgnifxError with code `IGX-0102` when called from inside a lifecycle callback, where\n * destroying an object the engine is still iterating would be unsound; use `destroy()` there.\n */\n destroyImmediate(): void {\n entityInternals(this).host.lifecycle.destroyImmediate(this);\n }\n\n /**\n * Finishes attaching a component: identity, filing, tracked references, and the `onAttach` hook.\n *\n * @param component - The freshly constructed component.\n */\n #attach(component: Component): void {\n const internals = entityInternals(this);\n const host = internals.host;\n const state = componentInternals(component);\n state.entity = this;\n state.uid = host.nextUid();\n state.handle = host.allocateComponentHandle(component);\n state.serial = host.nextSerial();\n // A component instance's `constructor` is its own component class, and `describe` is cached and\n // idempotent, so looking the info up here rather than threading it through costs one map read.\n const info = host.registry.describe(component.constructor);\n state.info = info;\n internals.components.push(component);\n host.store.add(component, info);\n host.references.watch(component);\n readCallback(component, \"onAttach\")?.call(component);\n internals.onComponentAdded?.emit(component);\n }\n\n /**\n * The internals, with the \"not destroyed\" precondition checked.\n *\n * @param operation - What was attempted, for the error's context.\n * @returns The internals.\n */\n #mutable(operation: string): EntityInternals {\n const internals = entityInternals(this);\n if (internals.isDestroyed) {\n throw destroyedError(internals.uid, operation);\n }\n return internals;\n }\n}\n\n/**\n * The engine-owned state of an entity, declared through interface merging for the same reason as\n * a component's: `isolatedDeclarations` (coding standards §3) rejects a symbol-keyed class field.\n *\n * @public\n */\n// Merging is deliberate and safe here: the class constructor assigns the one property the\n// interface declares. See the note on `Component`.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- see the note above\nexport interface Entity {\n /**\n * The engine-owned state.\n *\n * @internal\n */\n [ENTITY_INTERNALS]: EntityInternals;\n}\n\n/**\n * The prefab link `Entity.prefab` returns for an entity a scene file's `instance` entry produced\n * (`docs/architecture/02-scene-graph.md` §6).\n *\n * @public\n */\nexport interface EntityPrefabLink {\n /** The handle the instanced scene was loaded through, or `null` when no asset service resolved one. */\n readonly asset: AssetHandle<SceneAsset> | null;\n /** The address of the instanced scene. */\n readonly address: string;\n /** The entity the `instance` entry sat on — the root of this instance. */\n readonly instanceRoot: Entity;\n}\n\n/**\n * Options accepted by `Entity.setParent`. Written as code rather than as a documentation link\n * because `Entity` is a class and an interface at once: an unqualified reference is ambiguous to\n * API Extractor, and the qualified form it asks for is unresolvable to TypeDoc.\n *\n * @public\n */\nexport interface SetParentOptions {\n /**\n * `true` (the default) preserves the entity's world transform by rewriting its local values;\n * `false` keeps the local values, so the entity moves with the new parent\n * (`docs/architecture/02-scene-graph.md` §5.1).\n */\n readonly worldPositionStays?: boolean;\n}\n\n/**\n * The topmost ancestor of an entity.\n *\n * @param entity - Where to start.\n * @returns The root of that entity's branch.\n */\nfunction rootOf(entity: Entity): Entity {\n let current = entity;\n let parent = entityInternals(current).parent;\n while (parent !== null) {\n current = parent;\n parent = entityInternals(current).parent;\n }\n return current;\n}\n\n/**\n * Walks up from an entity looking for a component.\n *\n * @typeParam T - The component type.\n * @param entity - Where to start.\n * @param type - The query class.\n * @returns The first match, or `null`.\n */\nfunction findInParents<T extends Component>(entity: Entity, type: ComponentType<T>): T | null {\n let current: Entity | null = entity;\n while (current !== null) {\n const found = current.getComponent(type);\n if (found !== null) {\n return found;\n }\n current = entityInternals(current).parent;\n }\n return null;\n}\n\n/**\n * Reports whether a component matches a query class, by identity or inheritance, from the ancestor\n * chain the registry precomputed.\n *\n * @typeParam T - The component type.\n * @param component - The candidate.\n * @param type - The query class.\n * @returns `true` when the component is an instance of the class.\n */\nfunction matches<T extends Component>(component: Component, type: ComponentType<T>): component is T {\n const info = componentInternals(component).info;\n if (info === null) {\n return false;\n }\n const ancestors = info.ancestors;\n for (let index = 0; index < ancestors.length; index += 1) {\n if (ancestors[index] === type) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Depth-first collection for `Entity.getComponentsInChildren`.\n *\n * @typeParam T - The component type.\n * @param entity - The subtree root.\n * @param type - The query class.\n * @param includeInactive - Whether inactive entities are visited.\n * @param out - Where matches are appended.\n */\nfunction collectInChildren<T extends Component>(\n entity: Entity,\n type: ComponentType<T>,\n includeInactive: boolean,\n out: T[],\n): void {\n if (includeInactive || entity.activeInHierarchy) {\n const components = entityInternals(entity).components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined && matches(component, type)) {\n out.push(component);\n }\n }\n }\n const children = entityInternals(entity).children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectInChildren(child, type, includeInactive, out);\n }\n }\n}\n\n/**\n * Validates an `init` object against a schema and copies it onto the component.\n *\n * @param component - The component being initialised.\n * @param schema - Its declared fields.\n * @param init - The caller's values.\n * @param typeName - The class name, for the error message.\n */\nfunction applyComponentInit(component: Component, schema: Schema, init: object, typeName: string): void {\n // Boundary assertion (coding standards §5.2): the invariant is that `ComponentInit<T>` only ever\n // names schema fields, so reading it as a string-keyed bag is exactly what the validator and the\n // deserializer do with the same names.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const values = init as Record<string, unknown>;\n const issues = validateProps(schema, values);\n const first = issues[0];\n if (first !== undefined) {\n throw new IgnifxError(first.code, `${typeName}.${first.path === \"\" ? \"<value>\" : first.path}: ${first.message}`, {\n context: { component: typeName, field: first.path, issues: issues.length },\n });\n }\n // Boundary assertion (coding standards §5.2): the component's own schema declares these property\n // names, and the values have just been validated against it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const target = component as unknown as Record<string, unknown>;\n for (const name of Object.keys(schema)) {\n const value = values[name];\n if (value !== undefined) {\n target[name] = value;\n }\n }\n}\n\n/**\n * Builds the \"used after destroy\" error.\n *\n * @param uid - The destroyed entity's identifier.\n * @param operation - What was attempted.\n * @returns The error to throw.\n */\nfunction destroyedError(uid: string, operation: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.mutationAfterDestroy, \"This entity has been destroyed.\", {\n context: { target: \"entity\", entity: uid, operation },\n hint: \"Check isDestroyed before mutating an object you kept a reference to.\",\n });\n}\n\n/**\n * Applies an entity's effective activation to its Lite subtree.\n *\n * @param entity - The entity whose visibility changed.\n * @param visible - The new effective activation.\n *\n * @internal\n */\nexport function applyEntityVisibility(entity: Entity, visible: boolean): void {\n setNodeSelfVisible(entityInternals(entity).node, visible);\n}\n","/**\n * Generation-checked handle allocation (`docs/architecture/00-overview.md` §5). A handle packs a\n * dense slot index with the generation the slot was on when the handle was issued, so a handle kept\n * across a destroy resolves to `null` instead of to whatever object recycled the slot — the bug\n * that dense-index-only schemes are famous for.\n */\n\n/** How many low bits of a handle carry the slot index: 2^20 = 1,048,576 live objects. */\nconst INDEX_BITS = 20;\n\n/** The mask that extracts the slot index. */\nconst INDEX_MASK = (1 << INDEX_BITS) - 1;\n\n/** How many generations a slot cycles through before wrapping: 2^11 = 2048. */\nconst GENERATION_LIMIT = 1 << 11;\n\n/** The highest slot index the packing supports. */\nconst MAX_SLOTS = INDEX_MASK;\n\n/**\n * A dense table of live objects addressed by generation-checked handles.\n *\n * @typeParam T - The object type stored in the table.\n *\n * @remarks\n * Slot zero is never handed out, so the handle `0` (`INVALID_HANDLE`) can mean \"no handle\". Freed slots\n * are pushed on a free list and reused in last-freed-first order; each reuse bumps the slot's\n * generation, which is what invalidates the old handle. Generations wrap after 2048 reuses of the\n * same* slot, at which point a handle that old could alias again — the same trade-off Unity and\n * Bevy make, documented here rather than papered over.\n *\n * @example\n * ```ts\n * const allocator = new HandleAllocator<Entity>();\n * const handle = allocator.allocate(entity);\n * allocator.get(handle); // entity\n * allocator.release(handle);\n * allocator.get(handle); // null\n * ```\n *\n * @internal\n */\nexport class HandleAllocator<T> {\n /** Value per slot; `null` while a slot is reserved but not yet bound. Index 0 is never used. */\n readonly #values: (T | null)[] = [null];\n\n /** Whether each slot is currently handed out. Index 0 is permanently free. */\n readonly #live: boolean[] = [false];\n\n /** Current generation per slot. Index 0 is permanently unused. */\n readonly #generations: number[] = [0];\n\n /** Indices of freed slots, reused last-freed-first. */\n readonly #free: number[] = [];\n\n /** How many slots currently hold a value. */\n #size = 0;\n\n /**\n * How many handles are currently live.\n *\n * @returns The number of occupied slots.\n */\n get size(): number {\n return this.#size;\n }\n\n /**\n * How many slots the table has ever grown to, live or free. Exposed for tests that assert slot\n * reuse rather than growth.\n *\n * @returns The slot count, including the permanently unused slot zero.\n */\n get capacity(): number {\n return this.#values.length;\n }\n\n /**\n * Stores a value and issues a handle for it.\n *\n * @param value - The object to store.\n * @returns The packed handle. Brand it with `toEntityHandle`/`toComponentHandle`.\n * @throws RangeError when the table is full (2^20 - 1 live objects).\n */\n allocate(value: T): number {\n const handle = this.reserve();\n this.bind(handle, value);\n return handle;\n }\n\n /**\n * Takes a slot without a value yet, for an object whose constructor needs its own handle.\n *\n * @returns The packed handle. Until {@link HandleAllocator.bind} runs, resolving it yields\n * `null`, exactly as a stale handle does.\n * @throws RangeError when the table is full (2^20 - 1 live objects).\n */\n reserve(): number {\n const recycled = this.#free.pop();\n if (recycled !== undefined) {\n const next = ((this.#generations[recycled] ?? 0) + 1) % GENERATION_LIMIT;\n // Generation zero would collide with the \"never allocated\" state, so wrapping skips it.\n const generation = next === 0 ? 1 : next;\n this.#generations[recycled] = generation;\n this.#values[recycled] = null;\n this.#live[recycled] = true;\n this.#size += 1;\n return (generation << INDEX_BITS) | recycled;\n }\n const index = this.#values.length;\n if (index > MAX_SLOTS) {\n throw new RangeError(`The handle table is full at ${String(MAX_SLOTS)} live objects.`);\n }\n this.#values.push(null);\n this.#generations.push(1);\n this.#live.push(true);\n this.#size += 1;\n return (1 << INDEX_BITS) | index;\n }\n\n /**\n * Stores the value of a reserved slot.\n *\n * @param handle - The handle {@link HandleAllocator.reserve} returned.\n * @param value - The object to store.\n */\n bind(handle: number, value: T): void {\n if (!this.isLive(handle)) {\n return;\n }\n this.#values[slotOf(handle)] = value;\n }\n\n /**\n * Resolves a handle.\n *\n * @param handle - A handle from {@link HandleAllocator.allocate}.\n * @returns The stored value, or `null` when the handle is stale, was never issued, or is zero.\n */\n get(handle: number): T | null {\n if (!this.isLive(handle)) {\n return null;\n }\n return this.#values[slotOf(handle)] ?? null;\n }\n\n /**\n * Reports whether a handle still resolves.\n *\n * @param handle - The handle to test.\n * @returns `true` when {@link HandleAllocator.get} would return a value.\n */\n isLive(handle: number): boolean {\n const slot = slotOf(handle);\n if (slot === 0 || slot >= this.#values.length) {\n return false;\n }\n return this.#generations[slot] === handle >>> INDEX_BITS && this.#live[slot] === true;\n }\n\n /**\n * Frees the slot a handle points at, invalidating that handle and every older one for the slot.\n *\n * @param handle - The handle to release.\n * @returns `true` when a live slot was freed, `false` when the handle was already stale.\n */\n release(handle: number): boolean {\n if (!this.isLive(handle)) {\n return false;\n }\n const slot = slotOf(handle);\n this.#values[slot] = null;\n this.#live[slot] = false;\n this.#free.push(slot);\n this.#size -= 1;\n return true;\n }\n\n /** Frees every slot and forgets every generation, as if the allocator were new. */\n clear(): void {\n this.#values.length = 1;\n this.#generations.length = 1;\n this.#live.length = 1;\n this.#free.length = 0;\n this.#size = 0;\n }\n}\n\n/**\n * The slot a handle points at.\n *\n * @param handle - The packed handle.\n * @returns The dense slot index.\n */\nfunction slotOf(handle: number): number {\n return handle & INDEX_MASK;\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\n\n/**\n * Where {@link generateUlid} gets its randomness. Injecting it is what lets a test replay a scene\n * with the same uids every run (`CONSTITUTION.md` §2.1) without ignifx depending on a random\n * library (coding standards §13).\n *\n * @public\n */\nexport interface RandomSource {\n /**\n * Fills every byte of the buffer with new random values.\n *\n * @remarks\n * Named `fillBytes` rather than `fill` so that call sites are not mistaken for `Array.prototype.fill`\n * by the linter's reference-value rule.\n *\n * @param bytes - The buffer to overwrite in place. The buffer is a plain `ArrayBuffer` view;\n * `crypto.getRandomValues` refuses shared memory, so the type says so.\n */\n fillBytes(bytes: Uint8Array<ArrayBuffer>): void;\n}\n\n/**\n * Creates the production random source, backed by Web Crypto.\n *\n * @returns A source that fills buffers with `crypto.getRandomValues`.\n * @throws IgnifxError with code `IGX-1420` when the host exposes no Web Crypto implementation.\n *\n * @example\n * ```ts\n * const nextUid = createUlidFactory({ random: createCryptoRandom() });\n * ```\n *\n * @public\n */\nexport function createCryptoRandom(): RandomSource {\n // The DOM lib declares `globalThis.crypto` as always present. Node before 19 and locked-down\n // embedders do not have it, so the assertion models the absence the types deny (standards §5.2).\n const webCrypto = globalThis.crypto as Crypto | undefined;\n if (webCrypto === undefined || typeof webCrypto.getRandomValues !== \"function\") {\n throw new IgnifxError(CoreErrorCode.cryptoUnavailable, \"This host does not expose Web Crypto.\", {\n hint: \"Pass a RandomSource explicitly, or use createSeededRandom() in environments without crypto.\",\n });\n }\n return {\n fillBytes(bytes: Uint8Array<ArrayBuffer>): void {\n webCrypto.getRandomValues(bytes);\n },\n };\n}\n\n/** The `splitmix32` multiplier used to expand a single 32-bit seed into the four state words. */\nconst SEED_MULTIPLIER = 0x6d2b79f5;\n\n/**\n * Creates a deterministic random source: the same seed always produces the same byte stream.\n *\n * @remarks\n * The generator is Marsaglia's four-word `xorshift128`, seeded through a `splitmix32`-style\n * scrambler so that neighbouring seeds do not produce correlated streams. It is for tests, replays,\n * and procedural generation — never for anything security-sensitive.\n *\n * @param seed - Any integer; only the low 32 bits are used.\n * @returns A source that fills buffers deterministically.\n *\n * @example\n * ```ts\n * const nextUid = createUlidFactory({ random: createSeededRandom(1), now: () => 0 });\n * nextUid() === createUlidFactory({ random: createSeededRandom(1), now: () => 0 })(); // true\n * ```\n *\n * @public\n */\nexport function createSeededRandom(seed: number): RandomSource {\n let scrambler = Math.trunc(seed) >>> 0;\n /**\n * Produces the next scrambled 32-bit word used to initialise the generator state.\n *\n * @returns An unsigned 32-bit integer.\n */\n const nextSeedWord = (): number => {\n scrambler = (scrambler + SEED_MULTIPLIER) >>> 0;\n let word = scrambler;\n word = Math.imul(word ^ (word >>> 15), word | 1) >>> 0;\n word = (word ^ (word + Math.imul(word ^ (word >>> 7), word | 61))) >>> 0;\n return (word ^ (word >>> 14)) >>> 0;\n };\n\n // An all-zero state is a fixed point of xorshift, so the low bit of the first word is forced on:\n // one guaranteed set bit costs nothing and removes the failure mode without a runtime check.\n let stateA = nextSeedWord() | 1;\n let stateB = nextSeedWord();\n let stateC = nextSeedWord();\n let stateD = nextSeedWord();\n\n /**\n * Advances the generator.\n *\n * @returns The next unsigned 32-bit word.\n */\n const nextWord = (): number => {\n const t = stateD ^ (stateD << 11);\n stateD = stateC;\n stateC = stateB;\n stateB = stateA;\n stateA = (stateA ^ (stateA >>> 19) ^ (t ^ (t >>> 8))) >>> 0;\n return stateA;\n };\n\n return {\n fillBytes(bytes: Uint8Array<ArrayBuffer>): void {\n let word = 0;\n for (let index = 0; index < bytes.length; index += 1) {\n if (index % 4 === 0) {\n word = nextWord();\n }\n bytes[index] = (word >>> ((index % 4) * 8)) & 0xff;\n }\n },\n };\n}\n","import { createCryptoRandom, type RandomSource } from \"./random-source.js\";\n\n/**\n * ULID generation (`docs/architecture/02-scene-graph.md` §10, `00-overview.md` §5): a 26-character,\n * lexicographically sortable, Crockford base32 identifier built from a 48-bit millisecond timestamp\n * and 80 bits of randomness. Entities and components carry one as their `uid`, and scene files use\n * it as the reference key.\n */\n\n/** Crockford's base32 alphabet: no `I`, `L`, `O`, or `U`, so ids cannot be misread. */\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/** How many characters a ULID has. */\nconst ULID_LENGTH = 26;\n\n/** How many of those characters encode the timestamp. */\nconst TIME_LENGTH = 10;\n\n/** How many bytes of randomness a ULID carries (80 bits). */\nconst RANDOM_BYTES = 10;\n\n/** How many characters one 40-bit half of the randomness encodes to. */\nconst HALF_LENGTH = 8;\n\n/** The base of the encoding. */\nconst BASE = 32;\n\n/** The largest timestamp a 48-bit ULID can express: 10889-08-02T05:31:50.655Z. */\nconst MAX_TIME_MS = 281_474_976_710_655;\n\n/** A byte mask, used by the monotonic carry. */\nconst BYTE_MAX = 0xff;\n\n/**\n * Encodes an unsigned integer as a fixed number of Crockford base32 characters, most significant\n * first.\n *\n * @param value - The value to encode; must be below `32 ** length`.\n * @param length - How many characters to produce.\n * @returns The encoded characters.\n */\nfunction encode(value: number, length: number): string {\n let remaining = value;\n let out = \"\";\n for (let index = 0; index < length; index += 1) {\n out = CROCKFORD.charAt(remaining % BASE) + out;\n remaining = Math.floor(remaining / BASE);\n }\n return out;\n}\n\n/**\n * Reads five bytes as one 40-bit big-endian integer. A `DataView` rather than indexing, because it\n * returns a plain `number` under `noUncheckedIndexedAccess`, and multiplication rather than shifting,\n * because JavaScript's bitwise operators truncate to 32 bits.\n *\n * @param view - A view over the randomness buffer.\n * @param offset - The index of the most significant byte.\n * @returns The 40-bit value.\n */\nfunction readHalf(view: DataView, offset: number): number {\n return view.getUint32(offset) * 256 + view.getUint8(offset + 4);\n}\n\n/**\n * Formats a timestamp and a randomness buffer as a ULID.\n *\n * @param timeMs - The timestamp in milliseconds, already clamped to 48 bits.\n * @param view - A view over exactly {@link RANDOM_BYTES} bytes of randomness.\n * @returns The 26-character identifier.\n */\nfunction formatUlid(timeMs: number, view: DataView): string {\n return encode(timeMs, TIME_LENGTH) + encode(readHalf(view, 0), HALF_LENGTH) + encode(readHalf(view, 5), HALF_LENGTH);\n}\n\n/**\n * Adds one to the 80-bit randomness, big-endian, which is how the ULID specification keeps ids\n * generated in the same millisecond strictly increasing.\n *\n * @param view - A view over the randomness buffer, modified in place.\n * @returns `false` when every byte overflowed, meaning the caller must draw fresh randomness.\n */\nfunction incrementRandom(view: DataView): boolean {\n for (let index = RANDOM_BYTES - 1; index >= 0; index -= 1) {\n const next = (view.getUint8(index) + 1) & BYTE_MAX;\n view.setUint8(index, next);\n if (next !== 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Clamps a clock reading into the 48 bits a ULID timestamp has.\n *\n * @param timeMs - The raw clock reading.\n * @returns A whole number between 0 and {@link MAX_TIME_MS}.\n */\nfunction clampTime(timeMs: number): number {\n if (!Number.isFinite(timeMs) || timeMs < 0) {\n return 0;\n }\n return Math.min(Math.floor(timeMs), MAX_TIME_MS);\n}\n\n/**\n * Options for {@link createUlidFactory}.\n *\n * @public\n */\nexport interface UlidFactoryOptions {\n /** Where randomness comes from. Defaults to {@link createCryptoRandom}. */\n readonly random?: RandomSource;\n /** The clock, in milliseconds since the Unix epoch. Defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\n/**\n * Creates the monotonic ULID generator an app owns.\n *\n * @remarks\n * The returned function holds the monotonic state — the last timestamp and its randomness — so that\n * ids created inside one millisecond still sort in creation order, exactly like the ULID\n * specification's monotonic mode. The state lives in the closure, never at module scope, so two apps\n * in one process generate independently (`CONSTITUTION.md` §3.5, §3.6). A clock that jumps backwards\n * is pinned to the last timestamp, so ids never go backwards either.\n *\n * @param options - The random source and the clock.\n * @returns A function producing the next ULID.\n *\n * @example\n * ```ts\n * const nextUid = createUlidFactory();\n * const a = nextUid();\n * const b = nextUid();\n * a < b; // true, even inside one millisecond\n * ```\n *\n * @public\n */\nexport function createUlidFactory(options?: UlidFactoryOptions): () => string {\n const random = options?.random ?? createCryptoRandom();\n const now = options?.now ?? Date.now;\n const bytes = new Uint8Array(RANDOM_BYTES);\n const view = new DataView(bytes.buffer);\n let lastTimeMs = -1;\n\n return function nextUlid(): string {\n const timeMs = Math.max(clampTime(now()), lastTimeMs);\n if (timeMs === lastTimeMs) {\n if (!incrementRandom(view)) {\n // Unreachable in practice: it takes 2^80 ids inside one millisecond to exhaust the space.\n random.fillBytes(bytes);\n }\n } else {\n lastTimeMs = timeMs;\n random.fillBytes(bytes);\n }\n return formatUlid(timeMs, view);\n };\n}\n\n/**\n * Generates one ULID with fresh randomness.\n *\n * @remarks\n * This is the stateless form: every call draws 80 new random bits, so two ids created in the same\n * millisecond are unordered relative to each other. Monotonic ordering needs state, and state at\n * module scope is forbidden (`CONSTITUTION.md` §3.5, §3.6) — use {@link createUlidFactory} when\n * ordering inside a millisecond matters, which is what an app does for entity uids.\n *\n * @param random - Where the 80 random bits come from. Defaults to {@link createCryptoRandom}.\n * @param now - The clock, in milliseconds since the Unix epoch. Defaults to `Date.now`.\n * @returns A 26-character ULID.\n *\n * @example\n * ```ts\n * const uid = generateUlid();\n * isUlid(uid); // true\n * ```\n *\n * @public\n */\nexport function generateUlid(random?: RandomSource, now?: () => number): string {\n const source = random ?? createCryptoRandom();\n const bytes = new Uint8Array(RANDOM_BYTES);\n source.fillBytes(bytes);\n return formatUlid(clampTime(now === undefined ? Date.now() : now()), new DataView(bytes.buffer));\n}\n\n/**\n * Reports whether a string is a canonical ULID: 26 uppercase Crockford base32 characters whose\n * first character is `7` or lower, because a 48-bit timestamp cannot set the top two bits.\n *\n * @param value - The candidate identifier.\n * @returns `true` when the string is a well-formed ULID.\n *\n * @example\n * ```ts\n * isUlid(\"01ARZ3NDEKTSV4RRFFQ69G5FAV\"); // true\n * isUlid(\"01arz3ndektsv4rrffq69g5fav\"); // false — ULIDs are canonically uppercase\n * ```\n *\n * @public\n */\nexport function isUlid(value: string): boolean {\n if (value.length !== ULID_LENGTH) {\n return false;\n }\n for (let index = 0; index < ULID_LENGTH; index += 1) {\n if (!CROCKFORD.includes(value.charAt(index))) {\n return false;\n }\n }\n // 26 characters carry 130 bits but a ULID is 128, so the leading character encodes at most 7.\n return CROCKFORD.indexOf(value.charAt(0)) < 8;\n}\n\n/**\n * The largest timestamp a ULID can encode, in milliseconds since the Unix epoch. Readings beyond it\n * are clamped rather than producing a malformed identifier.\n *\n * @public\n */\nexport const MAX_ULID_TIME_MS: number = MAX_TIME_MS;\n","import { componentInternals } from \"../component/internals.js\";\nimport type { ScriptClassInfo } from \"../component/component-registry.js\";\nimport type { Script } from \"../script/script.js\";\n\n/**\n * One callback's dispatch list: every effectively-enabled script that implements it, kept sorted by\n * `(executionOrder ascending, creation serial ascending)`\n * (`docs/architecture/01-lifecycle-and-time.md` §3).\n *\n * @remarks\n * The order is maintained incrementally by sorted insertion — never by re-sorting per frame — which\n * is possible because both keys are fixed for a script's whole life: `executionOrder` is a static\n * of its class and the serial is assigned once at attachment.\n *\n * Mutation during a walk is the interesting case, and it is handled without allocating: while a\n * walk is in flight, insertions and removals are recorded and applied when it ends, and the walk\n * itself skips any script that is no longer effectively enabled. So a script disabled or destroyed\n * by another script's callback does not receive the callback this frame, and one enabled during the\n * walk first receives it on the next frame — the same rule that defers a newly created component's\n * `start` to the next flush B (§4).\n *\n * @internal\n */\nexport class ScriptList {\n readonly #items: Script[] = [];\n\n readonly #added: Script[] = [];\n\n readonly #removed: Script[] = [];\n\n #depth = 0;\n\n /**\n * The sorted list.\n *\n * @returns The live array. Outside a walk it holds exactly the effectively-enabled scripts that\n * implement this callback.\n */\n get items(): readonly Script[] {\n return this.#items;\n }\n\n /**\n * Adds a script in sort order. Adding one that is already present is a no-op.\n *\n * @param script - The script that just became effectively enabled.\n * @param info - Its class's ordering data.\n */\n insert(script: Script, info: ScriptClassInfo): void {\n if (this.#depth > 0) {\n this.#added.push(script);\n return;\n }\n const order = info.executionOrder;\n const serial = componentInternals(script).serial;\n const items = this.#items;\n let low = 0;\n let high = items.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n const other = items[middle];\n if (other !== undefined && compare(other, order, serial) < 0) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n if (items[low] === script) {\n return;\n }\n items.splice(low, 0, script);\n }\n\n /**\n * Removes a script. Removing one that is not present is a no-op.\n *\n * @param script - The script that stopped being effectively enabled.\n */\n remove(script: Script): void {\n if (this.#depth > 0) {\n this.#removed.push(script);\n return;\n }\n const index = this.#items.indexOf(script);\n if (index >= 0) {\n this.#items.splice(index, 1);\n }\n }\n\n /**\n * Walks the list in order, skipping scripts that stopped being effectively enabled.\n *\n * @param visitor - Called with each script.\n */\n forEach(visitor: (script: Script) => void): void {\n this.#depth += 1;\n try {\n const items = this.#items;\n const count = items.length;\n for (let index = 0; index < count; index += 1) {\n const script = items[index];\n if (script === undefined) {\n continue;\n }\n const state = componentInternals(script);\n if (state.isEnabledNow && !state.isDestroyed) {\n visitor(script);\n }\n }\n } finally {\n this.#depth -= 1;\n if (this.#depth === 0) {\n this.#drain();\n }\n }\n }\n\n /** Empties the list, for world disposal. */\n clear(): void {\n this.#items.length = 0;\n this.#added.length = 0;\n this.#removed.length = 0;\n this.#depth = 0;\n }\n\n /** Applies the mutations recorded while a walk was in flight, removals first. */\n #drain(): void {\n for (let index = 0; index < this.#removed.length; index += 1) {\n const script = this.#removed[index];\n if (script !== undefined) {\n const at = this.#items.indexOf(script);\n if (at >= 0) {\n this.#items.splice(at, 1);\n }\n }\n }\n this.#removed.length = 0;\n for (let index = 0; index < this.#added.length; index += 1) {\n const script = this.#added[index];\n const info = script === undefined ? null : componentInternals(script).info;\n if (script !== undefined && info !== null && info.script !== null) {\n this.insert(script, info.script);\n }\n }\n this.#added.length = 0;\n }\n}\n\n/**\n * Compares a list member against a sort key.\n *\n * @param item - The script already in the list.\n * @param order - The execution order being placed.\n * @param serial - The creation serial being placed.\n * @returns A negative number when `item` sorts first, a positive one when it sorts after.\n */\nfunction compare(item: Script, order: number, serial: number): number {\n const state = componentInternals(item);\n const info = state.info;\n const itemOrder = info?.script?.executionOrder ?? 0;\n if (itemOrder !== order) {\n return itemOrder - order;\n }\n return state.serial - serial;\n}\n","import { implementsCallback } from \"../component/component-registry.js\";\nimport { componentInternals } from \"../component/internals.js\";\nimport { Entity, applyEntityVisibility } from \"../entity/entity.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { disposeNode } from \"../lite/node.js\";\nimport { Script } from \"../script/script.js\";\nimport {\n FIRST_DISPATCHED_CALLBACK,\n SCRIPT_CALLBACK_COUNT,\n SCRIPT_CALLBACK_NAMES,\n ScriptCallbackKind,\n readCallback,\n} from \"./callbacks.js\";\nimport { ScriptList } from \"./script-list.js\";\nimport type { Phase } from \"../app/types.js\";\nimport type { ScriptClassInfo } from \"../component/component-registry.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { ComponentInternals } from \"../component/internals.js\";\nimport type { WorldHost } from \"../world/world-host.js\";\nimport type { WorldInternals } from \"../world/world-internals.js\";\n\n/**\n * The lifecycle queues and the three flushes the frame function calls\n * (`docs/architecture/01-lifecycle-and-time.md` §3 steps 3, 5, and 9; §4 and §6 define the\n * semantics). Every callback the engine invokes goes through {@link LifecycleQueue.invokeCallback},\n * the one guarded call site: it brackets the call with the frame state, catches whatever the\n * callback throws, reports it to `app.onError`, and carries on with the next script (§5).\n *\n * Decisions this class makes where the documents leave a choice, each with the sentence it follows:\n *\n * - **`awake` waits for the first time a component is effectively enabled.** §4's table says\n * `awake` runs \"right after the component is attached to an entity that is active in the\n * hierarchy\", but the guarantee immediately below it says \"a callback never runs ... on a\n * component whose `enabled` is `false`, except `onDisable`/`onDestroy`\". The guarantee wins: a\n * component added with `enabled = false` gets no `awake` until it is enabled.\n * - **`onDisable` is synchronous, `onEnable` is queued.** §3 step 3 lists `onEnable` in flush A, so\n * it waits for the flush; §4 says `onDisable` runs \"when the component stops being effectively\n * enabled\", with no flush named, so it runs at the transition. Inside a callback both run\n * immediately and nested, which is what §4's \"entities or components created from inside a\n * callback ... run nested and synchronously\" requires of `awake`.\n * - **Within one entity, components are released in attach order.** §3 step 9 fixes only \"children\n * before parents\". Attach order is the same order `awake` used, so one mental model covers both\n * ends of a component's life.\n */\n\n/** How many callbacks get a sorted dispatch list. */\nconst DISPATCH_LIST_COUNT = SCRIPT_CALLBACK_COUNT - FIRST_DISPATCHED_CALLBACK;\n\n/**\n * The lifecycle state machine of one world.\n *\n * @internal\n */\nexport class LifecycleQueue implements WorldInternals {\n readonly #host: WorldHost;\n\n readonly #lists: ScriptList[] = [];\n\n /** Components waiting for `awake`/`onEnable` in flush A. */\n #pendingEnable: Component[] = [];\n\n /** Components waiting for `start` in flush B. */\n #pendingStart: Component[] = [];\n\n /** Entities whose subtrees are waiting for the destroy flush. */\n #doomedEntities: Entity[] = [];\n\n /** Components waiting for the destroy flush on their own. */\n #doomedComponents: Component[] = [];\n\n /** The phase the scheduler says is running, recorded in error reports. */\n #phase: Phase | null = null;\n\n /**\n * Creates the queue.\n *\n * @param host - The world that owns it.\n */\n constructor(host: WorldHost) {\n this.#host = host;\n for (let index = 0; index < DISPATCH_LIST_COUNT; index += 1) {\n this.#lists.push(new ScriptList());\n }\n }\n\n /**\n * Tells the queue which phase is running, so a failure reported through `app.onError` names it.\n *\n * @param phase - The phase, or `null` between phases.\n */\n setPhase(phase: Phase | null): void {\n this.#phase = phase;\n }\n\n /** Lifecycle flush A. */\n flushAwakeAndEnable(): void {\n while (this.#pendingEnable.length > 0) {\n const batch = this.#pendingEnable;\n this.#pendingEnable = [];\n for (let index = 0; index < batch.length; index += 1) {\n const component = batch[index];\n if (component === undefined) {\n continue;\n }\n const state = componentInternals(component);\n if (!state.isEnableQueued) {\n continue;\n }\n state.isEnableQueued = false;\n if (state.isDestroyed || state.isReleased) {\n continue;\n }\n this.#enable(component, state);\n }\n }\n }\n\n /** Lifecycle flush B. */\n flushStart(): void {\n const batch = this.#pendingStart;\n if (batch.length === 0) {\n return;\n }\n // The list is swapped before the walk so that a component created inside a `start` queues into\n // the *next* flush B, which is what §4 promises.\n this.#pendingStart = [];\n batch.sort(byExecutionOrderThenSerial);\n for (let index = 0; index < batch.length; index += 1) {\n const component = batch[index];\n if (component === undefined) {\n continue;\n }\n const state = componentInternals(component);\n if (state.hasStarted || state.isReleased || state.isDestroyed) {\n state.isStartQueued = false;\n continue;\n }\n if (!state.isEnabledNow) {\n // Not effectively enabled at this flush: keep the reservation so `start` still runs exactly\n // once, on the first flush B at which the component is enabled.\n this.#pendingStart.push(component);\n continue;\n }\n state.hasStarted = true;\n state.isStartQueued = false;\n this.invokeCallback(component, ScriptCallbackKind.start);\n }\n }\n\n /** The destroy flush. */\n flushDestroy(): void {\n while (this.#doomedEntities.length > 0 || this.#doomedComponents.length > 0) {\n const entities = this.#doomedEntities;\n const components = this.#doomedComponents;\n this.#doomedEntities = [];\n this.#doomedComponents = [];\n const doomed = new Set<unknown>();\n for (let index = 0; index < entities.length; index += 1) {\n const entity = entities[index];\n if (entity !== undefined) {\n collectSubtree(entity, doomed);\n }\n }\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined) {\n doomed.add(component);\n }\n }\n // Tracked references are nulled before any callback runs, so a holder's own `onDestroy`\n // already sees `null` (`docs/architecture/02-scene-graph.md` §4).\n this.#host.references.nullReferencesTo(doomed);\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined) {\n this.#releaseComponent(component);\n }\n }\n for (let index = 0; index < entities.length; index += 1) {\n const entity = entities[index];\n if (entity !== undefined) {\n this.#releaseEntity(entity);\n }\n }\n }\n }\n\n /**\n * Walks one callback's dispatch list.\n *\n * @param kind - Which callback.\n * @param visitor - Called with each script.\n */\n forEachScript(kind: ScriptCallbackKind, visitor: (script: Script) => void): void {\n this.#lists[kind - FIRST_DISPATCHED_CALLBACK]?.forEach(visitor);\n }\n\n /**\n * One callback's dispatch list.\n *\n * @param kind - Which callback.\n * @returns The sorted, live list.\n */\n scriptsWith(kind: ScriptCallbackKind): readonly Script[] {\n return this.#lists[kind - FIRST_DISPATCHED_CALLBACK]?.items ?? EMPTY_SCRIPTS;\n }\n\n /**\n * Delivers one callback to every effectively-enabled script on one entity, in component order.\n *\n * @param entity - The entity to deliver to.\n * @param kind - Which callback.\n * @param argument - The callback's single argument.\n */\n dispatchToEntity(entity: Entity, kind: ScriptCallbackKind, argument: unknown): void {\n const internals = entityInternals(entity);\n if (internals.isDestroyed || !internals.activeInHierarchy) {\n return;\n }\n const components = internals.components;\n // Measured once: a script attached by a handler joins the entity only after this dispatch, the\n // same rule `forEachScript` applies to the sorted lists.\n const count = components.length;\n for (let index = 0; index < count; index += 1) {\n const component = components[index];\n if (component !== undefined && canReceiveDispatch(component, kind)) {\n this.invokeCallback(component, kind, argument);\n }\n }\n }\n\n /**\n * Whether any script on an entity implements a callback, whatever its `enabled` state.\n *\n * @param entity - The entity to inspect.\n * @param kind - Which callback.\n * @returns `true` when at least one of the entity's live scripts implements it.\n */\n entityImplements(entity: Entity, kind: ScriptCallbackKind): boolean {\n const components = entityInternals(entity).components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined && declaresCallback(component, kind)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes one callback on one component, guarded. This is the only place in the engine that calls\n * game code for a lifecycle or frame callback.\n *\n * @param component - The component to call.\n * @param kind - Which callback.\n * @param argument - The callback's single argument, when it takes one.\n */\n invokeCallback(component: Component, kind: ScriptCallbackKind, argument?: unknown): void {\n const state = componentInternals(component);\n const info = state.info;\n if (info === null || !implementsCallback(info.script, kind)) {\n return;\n }\n const name = SCRIPT_CALLBACK_NAMES[kind];\n if (name === undefined) {\n return;\n }\n const callback = readCallback(component, name);\n if (callback === null) {\n return;\n }\n const frameState = this.#host.frameState;\n frameState.beginCallback();\n try {\n callback.call(component, argument);\n } catch (error) {\n this.#host.reportError({\n error,\n source: \"lifecycle\",\n phase: this.#phase,\n entity: state.entity,\n component,\n });\n } finally {\n frameState.endCallback();\n }\n }\n\n /**\n * Recomputes and applies a component's effective enabled state.\n *\n * @param component - The component.\n */\n refreshEnabled(component: Component): void {\n const state = componentInternals(component);\n if (state.isReleased) {\n return;\n }\n const entity = state.entity;\n const target =\n state.enabled && !state.isDestroyed && entity !== null && !entity.isDestroyed && entity.activeInHierarchy;\n const current = state.isEnabledNow || state.isEnableQueued;\n if (target === current) {\n return;\n }\n if (target) {\n if (this.#host.frameState.state.isInsideCallback) {\n this.#enable(component, state);\n return;\n }\n state.isEnableQueued = true;\n this.#pendingEnable.push(component);\n return;\n }\n state.isEnableQueued = false;\n if (state.isEnabledNow) {\n this.#disable(component, state);\n }\n }\n\n /**\n * Materialises `activeInHierarchy` over a subtree and applies the transitions it implies.\n *\n * @param entity - The subtree root.\n */\n refreshActivation(entity: Entity): void {\n const parent = entityInternals(entity).parent;\n this.#applyActivation(entity, parent === null || parent.activeInHierarchy);\n }\n\n /**\n * Queues an entity and its subtree for destruction.\n *\n * @param entity - The entity to destroy.\n */\n queueDestroyEntity(entity: Entity): void {\n const internals = entityInternals(entity);\n if (internals.isReleased || internals.isDestroyQueued) {\n return;\n }\n internals.isDestroyQueued = true;\n markSubtreeDestroyed(entity);\n this.#doomedEntities.push(entity);\n }\n\n /**\n * Queues one component for destruction.\n *\n * @param component - The component to destroy.\n */\n queueDestroyComponent(component: Component): void {\n const state = componentInternals(component);\n if (state.isReleased || state.isDestroyQueued) {\n state.isDestroyed = true;\n return;\n }\n state.isDestroyed = true;\n state.isDestroyQueued = true;\n this.#doomedComponents.push(component);\n }\n\n /**\n * Destroys an object right now.\n *\n * @param target - The entity or component.\n * @throws IgnifxError with code `IGX-0102` inside a lifecycle callback.\n */\n destroyImmediate(target: Entity | Component): void {\n if (this.#host.frameState.state.isInsideCallback) {\n throw new IgnifxError(\n CoreErrorCode.destroyImmediateInCallback,\n \"destroyImmediate() cannot run inside a lifecycle callback; use destroy() instead.\",\n {\n context: { phase: \"callback\" },\n hint: \"destroy() queues the object for this frame's destroy flush, which is always safe.\",\n },\n );\n }\n if (target instanceof Entity) {\n this.queueDestroyEntity(target);\n } else {\n this.queueDestroyComponent(target);\n }\n this.flushDestroy();\n }\n\n /** Destroys every entity in the world and releases every list. */\n disposeWorld(): void {\n const scenes = this.#host.world.scenes;\n for (let index = 0; index < scenes.length; index += 1) {\n const scene = scenes[index];\n if (scene === undefined) {\n continue;\n }\n const roots = scene.roots;\n // A copy: releasing a root removes it from the live list.\n const snapshot = roots.slice();\n for (let root = 0; root < snapshot.length; root += 1) {\n const entity = snapshot[root];\n if (entity !== undefined) {\n this.queueDestroyEntity(entity);\n }\n }\n }\n this.flushDestroy();\n for (let index = 0; index < this.#lists.length; index += 1) {\n this.#lists[index]?.clear();\n }\n this.#pendingEnable.length = 0;\n this.#pendingStart.length = 0;\n this.#host.store.clear();\n this.#host.references.clear();\n }\n\n /**\n * Runs the enable transition: `awake` once, then `onEnable`, then coroutine resumption, then the\n * `start` reservation.\n *\n * @param component - The component.\n * @param state - Its engine state.\n */\n #enable(component: Component, state: ComponentInternals): void {\n if (state.isEnabledNow || isGone(state)) {\n return;\n }\n state.isEnableQueued = false;\n if (!state.hasAwoken) {\n state.hasAwoken = true;\n const entity = state.entity;\n if (entity !== null) {\n entityInternals(entity).hasAwoken = true;\n }\n this.invokeCallback(component, ScriptCallbackKind.awake);\n // `awake` is game code: it may have destroyed the very component it was called on. The read\n // goes through a helper so the narrowing from the guard above does not hide the fresh value.\n if (isGone(state)) {\n return;\n }\n }\n state.isEnabledNow = true;\n const scriptInfo = state.info?.script ?? null;\n if (component instanceof Script) {\n this.#addToDispatch(component, scriptInfo);\n }\n this.invokeCallback(component, ScriptCallbackKind.onEnable);\n if (component instanceof Script) {\n this.#host.app.coroutines.setPaused(component, false);\n }\n if (!state.hasStarted && !state.isStartQueued && implementsCallback(scriptInfo, ScriptCallbackKind.start)) {\n state.isStartQueued = true;\n this.#pendingStart.push(component);\n }\n }\n\n /**\n * Runs the disable transition: leave the dispatch lists, `onDisable`, then coroutine pausing.\n *\n * @param component - The component.\n * @param state - Its engine state.\n */\n #disable(component: Component, state: ComponentInternals): void {\n if (!state.isEnabledNow) {\n return;\n }\n state.isEnabledNow = false;\n if (component instanceof Script) {\n this.#removeFromDispatch(component, state.info?.script ?? null);\n }\n this.invokeCallback(component, ScriptCallbackKind.onDisable);\n if (component instanceof Script) {\n this.#host.app.coroutines.setPaused(component, true);\n }\n }\n\n /**\n * Files a script in the dispatch list of every callback its class implements.\n *\n * @param script - The script that just became effectively enabled.\n * @param info - Its class's callback mask and ordering, or `null` when it has none.\n */\n #addToDispatch(script: Script, info: ScriptClassInfo | null): void {\n if (info === null) {\n return;\n }\n for (let kind = FIRST_DISPATCHED_CALLBACK; kind < SCRIPT_CALLBACK_COUNT; kind += 1) {\n if ((info.callbacks & (1 << kind)) !== 0) {\n this.#lists[kind - FIRST_DISPATCHED_CALLBACK]?.insert(script, info);\n }\n }\n }\n\n /**\n * Removes a script from every dispatch list it was filed in.\n *\n * @param script - The script that stopped being effectively enabled.\n * @param info - Its class's callback mask, or `null` when it has none.\n */\n #removeFromDispatch(script: Script, info: ScriptClassInfo | null): void {\n if (info === null) {\n return;\n }\n for (let kind = FIRST_DISPATCHED_CALLBACK; kind < SCRIPT_CALLBACK_COUNT; kind += 1) {\n if ((info.callbacks & (1 << kind)) !== 0) {\n this.#lists[kind - FIRST_DISPATCHED_CALLBACK]?.remove(script);\n }\n }\n }\n\n /**\n * Applies an effective activation to an entity and recurses into its children.\n *\n * @param entity - The entity.\n * @param parentActive - Whether every ancestor is active.\n */\n #applyActivation(entity: Entity, parentActive: boolean): void {\n const internals = entityInternals(entity);\n const next = parentActive && internals.active && !internals.isDestroyed;\n internals.activeInHierarchy = next;\n // Written unconditionally rather than only on a change: Lite materialises visibility at write\n // time, so a node linked under a hidden parent does not inherit the state and has to be told\n // (ADR-0003 Validation).\n applyEntityVisibility(entity, next);\n const components = internals.components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined) {\n this.refreshEnabled(component);\n }\n }\n const children = internals.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n this.#applyActivation(child, next);\n }\n }\n }\n\n /**\n * Releases one entity's subtree, children before parents.\n *\n * @param entity - The subtree root.\n */\n #releaseEntity(entity: Entity): void {\n const internals = entityInternals(entity);\n if (internals.isReleased) {\n return;\n }\n const children = internals.children.slice();\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n this.#releaseEntity(child);\n }\n }\n const components = internals.components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined) {\n const state = componentInternals(component);\n if (state.isEnabledNow) {\n this.#disable(component, state);\n }\n }\n }\n // A copy: releasing a component splices it out of the live list.\n const snapshot = components.slice();\n for (let index = 0; index < snapshot.length; index += 1) {\n const component = snapshot[index];\n if (component !== undefined) {\n this.#releaseComponent(component);\n }\n }\n internals.isDestroyed = true;\n internals.isReleased = true;\n const parent = internals.parent;\n if (parent !== null && !entityInternals(parent).isReleased) {\n const siblings = entityInternals(parent).children;\n const at = siblings.indexOf(entity);\n if (at >= 0) {\n siblings.splice(at, 1);\n }\n }\n internals.children.length = 0;\n disposeNode(internals.node);\n this.#host.releaseEntity(entity);\n internals.onDestroyed?.emit(entity);\n this.#host.notifyEntityDestroyed(entity);\n }\n\n /**\n * Releases one component: `onDisable` if it is still enabled, `onDestroy`, coroutine\n * cancellation, `onDetach`, then every index that referred to it.\n *\n * @param component - The component.\n */\n #releaseComponent(component: Component): void {\n const state = componentInternals(component);\n if (state.isReleased) {\n return;\n }\n state.isDestroyed = true;\n if (state.isEnabledNow) {\n this.#disable(component, state);\n }\n this.invokeCallback(component, ScriptCallbackKind.onDestroy);\n if (component instanceof Script) {\n this.#host.app.coroutines.cancelAll(component);\n }\n state.isReleased = true;\n const info = state.info;\n if (info !== null) {\n this.#host.store.remove(component, info);\n }\n this.#host.references.unwatch(component);\n this.#host.releaseComponentHandle(state.handle);\n const entity = state.entity;\n if (entity !== null) {\n const entityState = entityInternals(entity);\n const siblings = entityState.components;\n const at = siblings.indexOf(component);\n if (at >= 0) {\n siblings.splice(at, 1);\n }\n entityState.onComponentRemoved?.emit(component);\n }\n try {\n readCallback(component, \"onDetach\")?.call(component);\n } catch (error) {\n this.#host.reportError({ error, source: \"lifecycle\", phase: this.#phase, entity, component });\n }\n state.onDestroyed?.emit(component);\n }\n}\n\n/**\n * Whether a component has been destroyed or already released.\n *\n * @param state - The component's engine state.\n * @returns `true` when the component must not receive further callbacks.\n */\nfunction isGone(state: ComponentInternals): boolean {\n return state.isDestroyed || state.isReleased;\n}\n\n/**\n * Whether a component still on an entity implements a callback and is not on its way out.\n *\n * @param component - The component.\n * @param kind - The callback ordinal.\n * @returns `true` when the component's class implements the callback.\n */\nfunction declaresCallback(component: Component, kind: ScriptCallbackKind): boolean {\n const state = componentInternals(component);\n const info = state.info;\n return info !== null && !isGone(state) && implementsCallback(info.script, kind);\n}\n\n/**\n * Whether a component should receive a per-entity dispatch: effectively enabled, not destroyed, and\n * implementing the callback.\n *\n * @param component - The component.\n * @param kind - The callback ordinal.\n * @returns `true` when the callback must be delivered to it.\n */\nfunction canReceiveDispatch(component: Component, kind: ScriptCallbackKind): boolean {\n return componentInternals(component).isEnabledNow && declaresCallback(component, kind);\n}\n\n/** Shared empty dispatch list for a kind that has none. */\nconst EMPTY_SCRIPTS: readonly Script[] = Object.freeze([]);\n\n/**\n * Marks an entity, its components, and its whole subtree as destroyed, immediately\n * (`docs/architecture/01-lifecycle-and-time.md` §6).\n *\n * @param entity - The subtree root.\n */\nfunction markSubtreeDestroyed(entity: Entity): void {\n const internals = entityInternals(entity);\n internals.isDestroyed = true;\n internals.isDestroyQueued = true;\n const components = internals.components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component !== undefined) {\n componentInternals(component).isDestroyed = true;\n }\n }\n const children = internals.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n markSubtreeDestroyed(child);\n }\n }\n}\n\n/**\n * Collects an entity, its components, and its subtree into the doomed set the reference tracker\n * scans.\n *\n * @param entity - The subtree root.\n * @param out - The set to fill.\n */\nfunction collectSubtree(entity: Entity, out: Set<unknown>): void {\n out.add(entity);\n const internals = entityInternals(entity);\n const components = internals.components;\n for (let index = 0; index < components.length; index += 1) {\n out.add(components[index]);\n }\n const children = internals.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectSubtree(child, out);\n }\n }\n}\n\n/**\n * Orders the flush B queue by `(executionOrder, creation serial)`.\n *\n * @param a - The first component.\n * @param b - The second component.\n * @returns A negative number when `a` starts first.\n */\nfunction byExecutionOrderThenSerial(a: Component, b: Component): number {\n const left = componentInternals(a);\n const right = componentInternals(b);\n const leftOrder = left.info?.script?.executionOrder ?? 0;\n const rightOrder = right.info?.script?.executionOrder ?? 0;\n if (leftOrder !== rightOrder) {\n return leftOrder - rightOrder;\n }\n return left.serial - right.serial;\n}\n","import { createPickRay, raycastScene, raycastSceneWhere, setPickRay } from \"../lite/picking.js\";\nimport { acceptsEntityTag, rendererInternals } from \"./renderer.js\";\nimport type { Ray } from \"./camera.js\";\nimport type { RenderPick, RenderPickOptions } from \"./renderer.js\";\nimport type { NodeTag } from \"../lite/node.js\";\nimport type { PickRay } from \"../lite/picking.js\";\nimport type { LiteScene } from \"../lite/scene.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * `world.raycastRender` (`docs/architecture/07-rendering.md` §3): the synchronous CPU ray test\n * against renderable meshes.\n *\n * It lives here rather than on `World` so that the world module keeps knowing nothing about the\n * renderer beyond two type imports: the conversion into Lite's ray shape, the entity filter, and\n * the mapping from a Lite hit back to an entity are all rendering concerns.\n *\n * ## What it can and cannot see\n *\n * Lite's `pickWithRay` walks `scene.meshes`, skips anything with `pickable === false`, applies the\n * caller's predicate, and tests each candidate's local AABB before its triangles — reading\n * `mesh._cpuPositions`, the CPU copy every mesh factory retains. Two consequences are worth\n * repeating at the call site, because neither is obvious:\n *\n * - **Visibility is ignored.** A hidden mesh still occludes and still returns a hit. Only\n * `pickable` and the predicate filter, which is why `MeshRenderer.pickable` exists.\n * - **A mesh with no CPU positions is skipped.** A CPU pick can therefore miss geometry a GPU pick\n * would hit; `app.renderer.pickAsync` is the exact answer.\n */\n\n/** One reusable ray per module, so a picking loop allocates nothing (coding standards §7). */\nlet scratch: PickRay | null = null;\n\n/**\n * Casts a ray against a world's renderable meshes and resolves the hit back to its entity.\n *\n * @param world - The world being picked in, for the handle tables.\n * @param scene - The Lite render scene.\n * @param ray - The ray to cast.\n * @param options - An entity filter.\n * @returns What was hit, or `null` for a miss.\n *\n * @internal\n */\nexport function raycastRenderScene(\n world: World,\n scene: LiteScene,\n ray: Ray,\n options?: RenderPickOptions,\n): RenderPick | null {\n const renderer = rendererInternals(world.app.renderer);\n const pickRay = (scratch ??= createPickRay());\n setPickRay(\n pickRay,\n ray.origin.x,\n ray.origin.y,\n ray.origin.z,\n ray.direction.x,\n ray.direction.y,\n ray.direction.z,\n ray.length,\n );\n const filter = options?.filter;\n const info =\n filter === undefined\n ? raycastScene(scene, pickRay)\n : raycastSceneWhere(scene, pickRay, (tag: NodeTag | null): boolean => acceptsEntityTag(world, tag, filter));\n return renderer.resolvePick(info);\n}\n","import { Signal } from \"../signal/signal.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { JsonObject } from \"../schema/json.js\";\nimport type { SceneAsset } from \"../serialization/scene-asset.js\";\nimport type { UidRemap } from \"../serialization/uid-remap.js\";\n\n/**\n * One loaded scene file, or the implicit default scene\n * (`docs/architecture/02-scene-graph.md` §3). An entity belongs to exactly one instance: the scene\n * it was loaded from, or the world's active scene when it was created in code.\n *\n * @remarks\n * The implicit `\"default\"` instance every app starts with has no asset and is always loaded.\n * An instance created by `world.loadScene` carries the handle it was built from and reports\n * `isLoaded === false` only while its entities are being constructed — a window no game code can\n * observe, because construction is one synchronous block (`docs/architecture/02-scene-graph.md` §2).\n *\n * @example\n * ```ts\n * world.activeScene.persistent = true; // survives a \"single\" load, like DontDestroyOnLoad\n * ```\n *\n * @public\n */\nexport class SceneInstance {\n /** The instance id, distinct from the address of the asset it was loaded from. */\n readonly uid: string;\n\n /** The instance's name; the file's name, or `\"default\"` for the implicit scene. */\n readonly name: string;\n\n /**\n * Whether the instance survives a `\"single\"` scene load — Unity's `DontDestroyOnLoad`, at scene\n * granularity rather than per object.\n */\n persistent: boolean;\n\n /** The root entities, maintained as entities are created, reparented, and destroyed. */\n readonly #roots: Entity[] = [];\n\n /** Emitted just before the instance is unloaded and its roots destroyed. */\n readonly #onUnloading: Signal;\n\n /** The scene asset the instance was built from, or `null` for the implicit default scene. */\n #asset: AssetHandle<SceneAsset> | null = null;\n\n /** `false` only between the first entity being created and the whole scene being constructed. */\n #isLoaded = true;\n\n /** File-local uid to runtime object, kept for override addressing and cross-references. */\n #remap: UidRemap | null = null;\n\n /** The `settings` block of the file this instance was built from. */\n #settings: JsonObject | null = null;\n\n /**\n * Creates a scene instance. The world creates these; game code reaches them through\n * `world.scenes` and `world.activeScene`.\n *\n * @param uid - The instance id.\n * @param name - The instance name.\n * @param persistent - Whether the instance survives a `\"single\"` load.\n *\n * @internal\n */\n constructor(uid: string, name: string, persistent: boolean) {\n this.uid = uid;\n this.name = name;\n this.persistent = persistent;\n this.#onUnloading = new Signal();\n }\n\n /**\n * The asset this instance was loaded from.\n *\n * @returns The handle `world.loadScene` retained on the instance's behalf, or `null` for the\n * implicit default scene and for instances created in code.\n */\n get asset(): AssetHandle<SceneAsset> | null {\n return this.#asset;\n }\n\n /**\n * Whether every entity of the instance has been constructed and its references resolved.\n *\n * @returns `true` once construction has finished; `false` only during it.\n */\n get isLoaded(): boolean {\n return this.#isLoaded;\n }\n\n /**\n * The file-local uid to runtime object table of this instance\n * (`docs/architecture/02-scene-graph.md` §10). Two instances of one scene have two tables, which\n * is what keeps their `$entity`/`$component` references apart.\n *\n * @returns The table, or `null` for an instance that was not built from a file.\n */\n get remap(): UidRemap | null {\n return this.#remap;\n }\n\n /**\n * Records the asset the instance was built from.\n *\n * @param asset - The retained handle.\n *\n * @internal\n */\n setAsset(asset: AssetHandle<SceneAsset> | null): void {\n this.#asset = asset;\n }\n\n /**\n * Records whether construction has finished.\n *\n * @param isLoaded - `true` once every entity exists and every reference is resolved.\n *\n * @internal\n */\n setLoaded(isLoaded: boolean): void {\n this.#isLoaded = isLoaded;\n }\n\n /**\n * Records the uid table built while the scene was constructed.\n *\n * @param remap - The table.\n *\n * @internal\n */\n setRemap(remap: UidRemap | null): void {\n this.#remap = remap;\n }\n\n /**\n * The scene-level values the file carried — environment, clear colour, 2D mode flags, physics\n * overrides (`docs/architecture/06-serialization-and-scene-format.md` §2). The core keeps them as\n * plain JSON; the systems that understand a key read it from here.\n *\n * @returns The block, or `null` for an instance that was not built from a file.\n */\n get settings(): JsonObject | null {\n return this.#settings;\n }\n\n /**\n * Records the file's `settings` block.\n *\n * @param settings - The block, or `null`.\n *\n * @internal\n */\n setSettings(settings: JsonObject | null): void {\n this.#settings = settings;\n }\n\n /**\n * The instance's root entities — the ones with no parent — in creation order.\n *\n * @returns The live root list. Its identity is stable for the instance's lifetime.\n */\n get roots(): readonly Entity[] {\n return this.#roots;\n }\n\n /**\n * Emitted just before the instance is unloaded, while its entities are still valid.\n *\n * @returns The signal.\n */\n get onUnloading(): Signal {\n return this.#onUnloading;\n }\n\n /**\n * Records an entity as a root of this instance.\n *\n * @param entity - The now-parentless entity.\n *\n * @internal\n */\n addRoot(entity: Entity): void {\n if (!this.#roots.includes(entity)) {\n this.#roots.push(entity);\n }\n }\n\n /**\n * Removes an entity from the root list.\n *\n * @param entity - The entity that gained a parent or was destroyed.\n *\n * @internal\n */\n removeRoot(entity: Entity): void {\n const index = this.#roots.indexOf(entity);\n if (index >= 0) {\n this.#roots.splice(index, 1);\n }\n }\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { asJsonArray, asJsonObject } from \"./json-view.js\";\nimport type { SceneFileComponent, SceneFileEntity, SceneFileOverride, SceneFileTransform } from \"./scene-file.js\";\nimport type { JsonObject, JsonValue } from \"../schema/json.js\";\n\n/**\n * The parsed form of an instance override `path`\n * (`docs/architecture/06-serialization-and-scene-format.md` §2). Every path starts with the uid of\n * an entity **of the instanced file**, so a path survives the per-instance uid remap\n * (`02-scene-graph.md` §10).\n *\n * The grammar, in the order the parser tries it:\n *\n * ```text\n * <uid> → entity (whole entity, \"remove\" only)\n * <uid>/name | active | static | layer | tags → entityField\n * <uid>/transform/position | rotation | scale → transform\n * <uid>/components → componentList (\"add\" only)\n * <uid>/components/<uid> → component (\"remove\" only)\n * <uid>/components/<uid>/enabled → componentField\n * <uid>/components/<uid>/props/<field>[/<key>…] → prop\n * ```\n *\n * @public\n */\nexport type OverridePath =\n | { readonly kind: \"entity\"; readonly entity: string }\n | { readonly kind: \"entityField\"; readonly entity: string; readonly field: EntityOverrideField }\n | { readonly kind: \"transform\"; readonly entity: string; readonly channel: keyof SceneFileTransform }\n | { readonly kind: \"componentList\"; readonly entity: string }\n | { readonly kind: \"component\"; readonly entity: string; readonly component: string }\n | { readonly kind: \"componentField\"; readonly entity: string; readonly component: string }\n | {\n readonly kind: \"prop\";\n readonly entity: string;\n readonly component: string;\n readonly steps: readonly string[];\n };\n\n/**\n * The entity properties an override may patch directly.\n *\n * @public\n */\nexport type EntityOverrideField = \"name\" | \"active\" | \"static\" | \"layer\" | \"tags\";\n\n/** The entity fields the grammar accepts, as an `as const` table so the union derives from it. */\nconst ENTITY_FIELDS: readonly EntityOverrideField[] = Object.freeze([\"name\", \"active\", \"static\", \"layer\", \"tags\"]);\n\n/** The transform channels the grammar accepts. */\nconst TRANSFORM_CHANNELS: readonly (keyof SceneFileTransform)[] = Object.freeze([\"position\", \"rotation\", \"scale\"]);\n\n/**\n * Parses an override path.\n *\n * @param path - The `path` string from the file.\n * @returns The parsed path.\n * @throws IgnifxError with code `IGX-0609` when the path does not match the grammar.\n *\n * @example\n * ```ts\n * parseOverridePath(\"01J…ROOT/components/01J…AI/props/aggression\");\n * // { kind: \"prop\", entity: \"01J…ROOT\", component: \"01J…AI\", steps: [\"aggression\"] }\n * ```\n *\n * @public\n */\nexport function parseOverridePath(path: string): OverridePath {\n const segments = path.split(\"/\");\n const entity = segments[0];\n if (entity === undefined || entity === \"\") {\n throw invalidPath(path, \"an override path starts with the uid of an entity in the instanced file.\");\n }\n if (segments.length === 1) {\n return { kind: \"entity\", entity };\n }\n const second = segments[1] ?? \"\";\n if (segments.length === 2) {\n if (second === \"components\") {\n return { kind: \"componentList\", entity };\n }\n const field = ENTITY_FIELDS.find((candidate) => candidate === second);\n if (field !== undefined) {\n return { kind: \"entityField\", entity, field };\n }\n throw invalidPath(path, `\"${second}\" is not an entity property an override may patch.`);\n }\n if (second === \"transform\") {\n const channel = TRANSFORM_CHANNELS.find((candidate) => candidate === segments[2]);\n if (channel === undefined || segments.length !== 3) {\n throw invalidPath(path, \"a transform override is <uid>/transform/position, /rotation, or /scale.\");\n }\n return { kind: \"transform\", entity, channel };\n }\n if (second !== \"components\") {\n throw invalidPath(path, `\"${second}\" is not \"components\", \"transform\", or an entity property.`);\n }\n const component = segments[2] ?? \"\";\n if (component === \"\") {\n throw invalidPath(path, \"a component override names the component's uid after /components/.\");\n }\n if (segments.length === 3) {\n return { kind: \"component\", entity, component };\n }\n const fourth = segments[3] ?? \"\";\n if (fourth === \"enabled\" && segments.length === 4) {\n return { kind: \"componentField\", entity, component };\n }\n if (fourth !== \"props\" || segments.length < 5) {\n throw invalidPath(path, \"a property override is <uid>/components/<uid>/props/<field>.\");\n }\n return { kind: \"prop\", entity, component, steps: segments.slice(4) };\n}\n\n/**\n * The `op` an override declares, defaulting to `\"replace\"` as the format document's two-key\n * examples imply.\n *\n * @param override - The override entry.\n * @returns The operation.\n *\n * @internal\n */\nexport function overrideOp(override: SceneFileOverride): \"replace\" | \"remove\" | \"add\" {\n return override.op ?? \"replace\";\n}\n\n/**\n * Applies every override to an expanded entity list, in order\n * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 3).\n *\n * @remarks\n * The patches run on the *file* representation, before any entity exists, so `add`, `remove`, and\n * `replace` all reduce to editing plain JSON. Entities are addressed by the uid they carry in the\n * instanced file; `lookup` maps that uid to the entity object in the expanded list.\n *\n * @param overrides - The patches, in file order.\n * @param lookup - Source uid to the mutable entity record it expanded into.\n * @param report - Called for a patch that names something the instanced file does not contain.\n *\n * @internal\n */\nexport function applyOverrides(\n overrides: readonly SceneFileOverride[],\n lookup: ReadonlyMap<string, OverrideTarget>,\n report: (message: string) => void,\n): void {\n for (let index = 0; index < overrides.length; index += 1) {\n const override = overrides[index];\n if (override === undefined) {\n continue;\n }\n const parsed = parseOverridePath(override.path);\n const target = lookup.get(parsed.entity);\n if (target === undefined) {\n report(`the override path \"${override.path}\" names no entity of the instanced scene.`);\n continue;\n }\n applyOne(overrideOp(override), parsed, override, target, report);\n }\n}\n\n/**\n * One entity an override may address: the record to patch, plus the mapping from the component uids\n * the *instanced file* carries — which is what override paths name — to the fresh uids this copy of\n * the prefab got (`docs/architecture/02-scene-graph.md` §10).\n *\n * @internal\n */\nexport interface OverrideTarget {\n /** The entity record to patch. */\n readonly data: MutableSceneEntity;\n /** Instanced-file component uid to this copy's component uid. */\n readonly components: ReadonlyMap<string, string>;\n}\n\n/**\n * A scene-file entity being built by the expander: the same shape as {@link SceneFileEntity} with\n * the read-only markers dropped, because overrides patch it in place.\n *\n * @internal\n */\nexport interface MutableSceneEntity {\n uid: string;\n name: string;\n parent: string | null;\n active?: boolean;\n static?: boolean;\n layer?: string;\n tags?: string[];\n transform: { position: number[]; rotation: number[]; scale: number[] };\n instance?: SceneFileEntity[\"instance\"];\n components: SceneFileComponent[];\n}\n\n/**\n * Applies one parsed override.\n *\n * @param op - The operation.\n * @param parsed - The parsed path.\n * @param override - The raw entry, for its `value`.\n * @param target - The entity the path resolved to, with its component uid mapping.\n * @param report - Called when the patch cannot be applied.\n */\nfunction applyOne(\n op: \"replace\" | \"remove\" | \"add\",\n parsed: OverridePath,\n override: SceneFileOverride,\n target: OverrideTarget,\n report: (message: string) => void,\n): void {\n const entity = target.data;\n switch (parsed.kind) {\n case \"entity\": {\n report(`\"${override.path}\" addresses a whole entity; overrides patch properties and components.`);\n return;\n }\n case \"entityField\": {\n applyEntityField(parsed.field, override.value ?? null, entity);\n return;\n }\n case \"transform\": {\n const numbers = asJsonArray(override.value);\n if (numbers === null) {\n report(`\"${override.path}\" needs an array of numbers.`);\n return;\n }\n entity.transform[parsed.channel] = numberArray(numbers);\n return;\n }\n case \"componentList\": {\n if (op !== \"add\") {\n report(`\"${override.path}\" is only valid with { \"op\": \"add\" }.`);\n return;\n }\n const added = asComponentEntry(override.value);\n if (added === null) {\n report(`\"${override.path}\" needs a component object with a uid and a type.`);\n return;\n }\n entity.components.push(added);\n return;\n }\n case \"component\": {\n if (op !== \"remove\") {\n report(`\"${override.path}\" addresses a whole component; only { \"op\": \"remove\" } may patch it.`);\n return;\n }\n const at = indexOfComponent(entity, resolve(target, parsed.component));\n if (at < 0) {\n report(`\"${override.path}\" names no component of that entity.`);\n return;\n }\n entity.components.splice(at, 1);\n return;\n }\n case \"componentField\": {\n const uid = resolve(target, parsed.component);\n const component = componentOf(entity, uid);\n if (component === null) {\n report(`\"${override.path}\" names no component of that entity.`);\n return;\n }\n replaceComponent(entity, uid, { ...component, enabled: override.value === true });\n return;\n }\n case \"prop\": {\n const uid = resolve(target, parsed.component);\n const component = componentOf(entity, uid);\n if (component === null) {\n report(`\"${override.path}\" names no component of that entity.`);\n return;\n }\n const props = writeStep(\n component.props ?? {},\n parsed.steps,\n 0,\n op,\n override.value ?? null,\n override.path,\n report,\n );\n replaceComponent(entity, uid, { ...component, props });\n return;\n }\n default: {\n return;\n }\n }\n}\n\n/**\n * Patches one plain entity property.\n *\n * @param field - Which property.\n * @param value - The new JSON value.\n * @param entity - The entity to patch.\n */\nfunction applyEntityField(field: EntityOverrideField, value: JsonValue, entity: MutableSceneEntity): void {\n switch (field) {\n case \"name\": {\n entity.name = typeof value === \"string\" ? value : entity.name;\n return;\n }\n case \"active\": {\n entity.active = value === true;\n return;\n }\n case \"static\": {\n entity.static = value === true;\n return;\n }\n case \"layer\": {\n if (typeof value === \"string\") {\n entity.layer = value;\n }\n return;\n }\n case \"tags\": {\n const list = asJsonArray(value);\n if (list !== null) {\n entity.tags = list.filter((tag): tag is string => typeof tag === \"string\");\n }\n return;\n }\n default: {\n return;\n }\n }\n}\n\n/**\n * Writes one step of a `props/<field>[/<key>…]` path, rebuilding the containers on the way so the\n * instanced file's own JSON is never mutated (two instances of one prefab must not share objects).\n *\n * @param container - The object or array being descended into.\n * @param steps - The remaining path segments.\n * @param at - The index of the segment to apply.\n * @param op - The operation.\n * @param value - The new value.\n * @param path - The whole path, for diagnostics.\n * @param report - Called when the step cannot be applied.\n * @returns The rebuilt container.\n */\nfunction writeStep(\n container: JsonObject,\n steps: readonly string[],\n at: number,\n op: \"replace\" | \"remove\" | \"add\",\n value: JsonValue,\n path: string,\n report: (message: string) => void,\n): JsonObject {\n const key = steps[at];\n if (key === undefined) {\n return container;\n }\n const copy: Record<string, JsonValue> = { ...container };\n if (at === steps.length - 1) {\n if (op === \"remove\") {\n // `delete` on a fresh copy: the container was cloned one line above, so nothing shared is\n // mutated and the key order of the surviving keys is preserved.\n const { [key]: _removed, ...rest } = copy;\n return rest;\n }\n copy[key] = value;\n return copy;\n }\n const next = copy[key];\n const nextArray = asJsonArray(next);\n if (nextArray !== null) {\n copy[key] = writeArrayStep(nextArray, steps, at + 1, op, value, path, report);\n return copy;\n }\n const nextObject = asJsonObject(next);\n if (nextObject !== null) {\n copy[key] = writeStep(nextObject, steps, at + 1, op, value, path, report);\n return copy;\n }\n report(`\"${path}\" descends into ${key}, which is not an object or an array.`);\n return container;\n}\n\n/**\n * The array form of {@link writeStep}.\n *\n * @param container - The array being descended into.\n * @param steps - The remaining path segments.\n * @param at - The index of the segment to apply.\n * @param op - The operation.\n * @param value - The new value.\n * @param path - The whole path, for diagnostics.\n * @param report - Called when the step cannot be applied.\n * @returns The rebuilt array.\n */\nfunction writeArrayStep(\n container: readonly JsonValue[],\n steps: readonly string[],\n at: number,\n op: \"replace\" | \"remove\" | \"add\",\n value: JsonValue,\n path: string,\n report: (message: string) => void,\n): readonly JsonValue[] {\n const key = steps[at];\n if (key === undefined) {\n return container;\n }\n const index = Number.parseInt(key, 10);\n if (!Number.isInteger(index) || index < 0) {\n report(`\"${path}\" indexes an array with \"${key}\", which is not a whole number.`);\n return container;\n }\n const copy = [...container];\n if (at === steps.length - 1) {\n if (op === \"remove\") {\n copy.splice(index, 1);\n return copy;\n }\n if (op === \"add\") {\n copy.splice(index, 0, value);\n return copy;\n }\n copy[index] = value;\n return copy;\n }\n const next = copy[index];\n const nextArray = asJsonArray(next);\n if (nextArray !== null) {\n copy[index] = writeArrayStep(nextArray, steps, at + 1, op, value, path, report);\n return copy;\n }\n const nextObject = asJsonObject(next);\n if (nextObject !== null) {\n copy[index] = writeStep(nextObject, steps, at + 1, op, value, path, report);\n return copy;\n }\n report(`\"${path}\" descends into [${key}], which is not an object or an array.`);\n return container;\n}\n\n/**\n * Resolves the uid an override path names — a uid of the instanced file — to the uid this copy of\n * the prefab gave the same component.\n *\n * @param target - The entity the path resolved to.\n * @param sourceUid - The uid the path names.\n * @returns This copy's uid, or the name itself when the mapping does not know it.\n */\nfunction resolve(target: OverrideTarget, sourceUid: string): string {\n return target.components.get(sourceUid) ?? sourceUid;\n}\n\n/**\n * Finds a component of an entity by uid.\n *\n * @param entity - The entity.\n * @param uid - The component uid.\n * @returns Its index, or `-1`.\n */\nfunction indexOfComponent(entity: MutableSceneEntity, uid: string): number {\n for (let index = 0; index < entity.components.length; index += 1) {\n if (entity.components[index]?.uid === uid) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * Reads a component of an entity by uid.\n *\n * @param entity - The entity.\n * @param uid - The component uid.\n * @returns The component, or `null`.\n */\nfunction componentOf(entity: MutableSceneEntity, uid: string): SceneFileComponent | null {\n const at = indexOfComponent(entity, uid);\n return at < 0 ? null : (entity.components[at] ?? null);\n}\n\n/**\n * Replaces a component entry in place, keeping its position in the list.\n *\n * @param entity - The entity.\n * @param uid - The component uid.\n * @param replacement - The new entry.\n */\nfunction replaceComponent(entity: MutableSceneEntity, uid: string, replacement: SceneFileComponent): void {\n const at = indexOfComponent(entity, uid);\n if (at >= 0) {\n entity.components[at] = replacement;\n }\n}\n\n/**\n * Reads a JSON value as a component entry.\n *\n * @param value - The candidate.\n * @returns The entry, or `null` when it carries no string `uid` and `type`.\n */\nfunction asComponentEntry(value: JsonValue | undefined): SceneFileComponent | null {\n const object = asJsonObject(value);\n if (object === null || typeof object[\"uid\"] !== \"string\" || typeof object[\"type\"] !== \"string\") {\n return null;\n }\n const enabled = object[\"enabled\"];\n const version = object[\"schemaVersion\"];\n return {\n uid: object[\"uid\"],\n type: object[\"type\"],\n ...(typeof enabled === \"boolean\" ? { enabled } : {}),\n ...(typeof version === \"number\" ? { schemaVersion: version } : {}),\n ...(asJsonObject(object[\"props\"]) === null ? {} : { props: asJsonObject(object[\"props\"]) ?? {} }),\n };\n}\n\n/**\n * Coerces a JSON array to numbers, dropping anything else.\n *\n * @param value - The JSON array.\n * @returns The numbers it holds.\n */\nfunction numberArray(value: readonly JsonValue[]): number[] {\n const numbers: number[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const entry = value[index];\n if (typeof entry === \"number\" && Number.isFinite(entry)) {\n numbers.push(entry);\n }\n }\n return numbers;\n}\n\n/**\n * Builds the `IGX-0609` error.\n *\n * @param path - The offending path.\n * @param reason - What the grammar expected.\n * @returns The error to throw.\n */\nfunction invalidPath(path: string, reason: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.invalidOverridePath, `${path} is not a valid override path: ${reason}`, {\n context: { path },\n hint: 'Override paths read \"<entityUid>/components/<componentUid>/props/<field>\".',\n });\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { asJsonArray, asJsonObject } from \"./json-view.js\";\nimport { applyOverrides } from \"./overrides.js\";\nimport { findSceneDependency } from \"./scene-asset.js\";\nimport type { MutableSceneEntity, OverrideTarget } from \"./overrides.js\";\nimport type { SceneAsset } from \"./scene-asset.js\";\nimport type { SceneFileComponent, SceneFileEntity } from \"./scene-file.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { JsonObject, JsonValue } from \"../schema/json.js\";\n\n/**\n * One entity of a fully expanded scene: every `instance` entry has been replaced by the entities of\n * the scene it named, with a fresh uid per copy and its overrides already applied\n * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 3).\n *\n * @internal\n */\nexport interface ExpandedEntity {\n /** The entity record, with `uid` and `parent` in expanded (unique) uid space. */\n readonly data: MutableSceneEntity;\n /** The uid the entity carries in the file that declared it, which overrides address. */\n readonly sourceUid: string;\n /** The instance this entity belongs to, or `null` when the scene itself declared it. */\n readonly instanceKey: string | null;\n /** Expanded component uid to the uid that component carries in its own file. */\n readonly componentSourceUids: ReadonlyMap<string, string>;\n}\n\n/**\n * One expanded `instance` entry.\n *\n * @internal\n */\nexport interface ExpandedInstance {\n /** The key {@link ExpandedEntity.instanceKey} refers to. */\n readonly key: string;\n /** The address of the instanced scene. */\n readonly address: string;\n /** The handle the scene asset was resolved through, when one exists. */\n readonly asset: AssetHandle<SceneAsset> | null;\n /** The instanced scene itself, so the serializer can diff current state against it. */\n readonly scene: SceneAsset;\n /** The expanded uid of the entity carrying the entry, or `null` when the builder decides. */\n readonly rootUid: string | null;\n}\n\n/**\n * A whole expanded scene.\n *\n * @internal\n */\nexport interface ExpandedScene {\n /** Every entity, in tree order: parents before children, instanced children before file children. */\n readonly entities: readonly ExpandedEntity[];\n /** Every instance the expansion produced, in expansion order. */\n readonly instances: readonly ExpandedInstance[];\n}\n\n/**\n * How {@link expandScene} mints uids, reports problems, and treats hashes.\n *\n * @internal\n */\nexport interface ExpandOptions {\n /** Mints a fresh uid for an instanced copy. */\n readonly nextUid: () => string;\n /** Receives every recoverable problem; the loader turns these into log records. */\n readonly report: (code: string, message: string) => void;\n /** `true` turns an `IGX-0604` hash mismatch from a diagnostic into a throw. */\n readonly strictInstanceHashes?: boolean;\n /**\n * Treats the whole file as one instance — what `world.instantiate` does. The expansion then mints\n * fresh uids for every entity and every entity carries the resulting instance key.\n */\n readonly asInstance?: boolean;\n}\n\n/**\n * Expands a scene into the flat entity list the builder creates objects from.\n *\n * @param asset - The scene to expand.\n * @param options - Uid minting, diagnostics, and the hash policy.\n * @returns The expanded entities in tree order and the instances they came from.\n * @throws IgnifxError with code `IGX-0302` when a scene instances itself, directly or through\n * another scene, and `IGX-0604` when `strictInstanceHashes` is set and a recorded hash does not\n * match the instanced scene.\n *\n * @internal\n */\nexport function expandScene(asset: SceneAsset, options: ExpandOptions): ExpandedScene {\n const entities: ExpandedEntity[] = [];\n const instances: ExpandedInstance[] = [];\n const state: ExpandState = { entities, instances, options, counter: 0 };\n if (options.asInstance === true) {\n const key = nextInstanceKey(state);\n instances.push({ key, address: asset.address, asset: null, scene: asset, rootUid: null });\n expandFile(asset, null, key, true, [asset.address], state);\n return { entities, instances };\n }\n expandFile(asset, null, null, false, [asset.address], state);\n return { entities, instances };\n}\n\n/** Everything the recursive expansion threads through. */\ninterface ExpandState {\n readonly entities: ExpandedEntity[];\n readonly instances: ExpandedInstance[];\n readonly options: ExpandOptions;\n counter: number;\n}\n\n/**\n * Expands one file's entities into the output list.\n *\n * @param asset - The scene being expanded.\n * @param parentUid - The expanded uid the file's roots attach to, or `null` for real roots.\n * @param instanceKey - The instance the entities belong to, or `null` for the outermost file.\n * @param freshUids - `true` mints a new uid per entity and component; `false` keeps the file's own.\n * @param chain - The addresses of the scenes currently being expanded, for the cycle check.\n * @param state - The accumulating output.\n * @returns The override targets produced, keyed by the uid each entity carries in `asset`'s own\n * file.\n */\nfunction expandFile(\n asset: SceneAsset,\n parentUid: string | null,\n instanceKey: string | null,\n freshUids: boolean,\n chain: readonly string[],\n state: ExpandState,\n): Map<string, OverrideTarget> {\n const source = asset.file.entities;\n const keys = new Map<string, string>();\n if (freshUids) {\n for (let index = 0; index < source.length; index += 1) {\n const entity = source[index];\n if (entity === undefined) {\n continue;\n }\n keys.set(entity.uid, state.options.nextUid());\n const components = entity.components ?? [];\n for (let inner = 0; inner < components.length; inner += 1) {\n const component = components[inner];\n if (component !== undefined) {\n keys.set(component.uid, state.options.nextUid());\n }\n }\n }\n }\n const produced = new Map<string, OverrideTarget>();\n for (let index = 0; index < source.length; index += 1) {\n const entity = source[index];\n if (entity === undefined) {\n continue;\n }\n const uid = keys.get(entity.uid) ?? entity.uid;\n const componentSourceUids = new Map<string, string>();\n const data: MutableSceneEntity = {\n uid,\n name: entity.name,\n parent: entity.parent === null ? parentUid : (keys.get(entity.parent) ?? entity.parent),\n ...(entity.active === undefined ? {} : { active: entity.active }),\n ...(entity.static === undefined ? {} : { static: entity.static }),\n ...(entity.layer === undefined ? {} : { layer: entity.layer }),\n ...(entity.tags === undefined ? {} : { tags: [...entity.tags] }),\n transform: {\n position: [...entity.transform.position],\n rotation: [...entity.transform.rotation],\n scale: [...entity.transform.scale],\n },\n components: cloneComponents(entity, keys, componentSourceUids),\n };\n produced.set(entity.uid, { data, components: reverse(componentSourceUids) });\n state.entities.push({ data, sourceUid: entity.uid, instanceKey, componentSourceUids });\n const nested = entity.instance;\n if (nested !== undefined) {\n expandInstance(asset, nested, uid, chain, state);\n }\n }\n return produced;\n}\n\n/**\n * Expands one `instance` entry under the entity that carries it.\n *\n * @param asset - The scene the entry was declared in, whose dependencies resolve the reference.\n * @param instance - The entry.\n * @param rootUid - The expanded uid of the entity carrying it.\n * @param chain - The addresses currently being expanded.\n * @param state - The accumulating output.\n */\nfunction expandInstance(\n asset: SceneAsset,\n instance: NonNullable<SceneFileEntity[\"instance\"]>,\n rootUid: string,\n chain: readonly string[],\n state: ExpandState,\n): void {\n const address = instance.scene.$asset;\n if (chain.includes(address)) {\n throw new IgnifxError(\n CoreErrorCode.sceneInstanceCycle,\n `Instantiating ${address} would nest the scene inside itself.`,\n {\n context: { scene: address, entity: rootUid, chain: chain.join(\" > \") },\n hint: \"A scene cannot instance itself, directly or through another scene.\",\n },\n );\n }\n const resolved = findSceneDependency(asset, address);\n if (resolved === null) {\n state.options.report(\n CoreErrorCode.sceneNotLoaded,\n `The instanced scene ${address} is not among the dependencies of ${asset.address}.`,\n );\n return;\n }\n const recorded = instance.hash;\n if (recorded !== undefined && recorded !== resolved.value.hash) {\n reportHashMismatch(address, recorded, resolved.value.hash, state.options);\n }\n const key = nextInstanceKey(state);\n state.instances.push({ key, address, asset: resolved.handle, scene: resolved.value, rootUid });\n const produced = expandFile(resolved.value, rootUid, key, true, [...chain, address], state);\n const overrides = instance.overrides;\n if (overrides !== undefined && overrides.length > 0) {\n applyOverrides(overrides, produced, (message) => {\n state.options.report(CoreErrorCode.instanceHashMismatch, `${asset.address}: ${message}`);\n });\n }\n}\n\n/**\n * Reports, or throws, an `IGX-0604` hash mismatch.\n *\n * @param address - The instanced scene.\n * @param recorded - The hash the file recorded.\n * @param actual - The hash the loaded scene has.\n * @param options - The expansion options, for the policy and the reporter.\n */\nfunction reportHashMismatch(address: string, recorded: string, actual: string, options: ExpandOptions): void {\n const message = `The overrides recorded for ${address} were saved against ${recorded}, but the scene now hashes to ${actual}.`;\n if (options.strictInstanceHashes === true) {\n throw new IgnifxError(CoreErrorCode.instanceHashMismatch, message, {\n context: { scene: address, recorded, actual },\n hint: \"Re-save the scene that instances it, or clear strictInstanceHashes to load anyway.\",\n });\n }\n options.report(CoreErrorCode.instanceHashMismatch, message);\n}\n\n/**\n * Mints the next instance key.\n *\n * @param state - The expansion state.\n * @returns A key unique within this expansion.\n */\nfunction nextInstanceKey(state: ExpandState): string {\n state.counter += 1;\n return `i${String(state.counter)}`;\n}\n\n/**\n * Clones an entity's components, remapping uids and the `$entity`/`$component` references inside\n * their props.\n *\n * @param entity - The source entity.\n * @param keys - Source uid to expanded uid; empty when the file's own uids are kept.\n * @param sourceUids - Filled with expanded component uid to source component uid.\n * @returns The cloned component list.\n */\nfunction cloneComponents(\n entity: SceneFileEntity,\n keys: ReadonlyMap<string, string>,\n sourceUids: Map<string, string>,\n): SceneFileComponent[] {\n const source = entity.components ?? [];\n const cloned: SceneFileComponent[] = [];\n for (let index = 0; index < source.length; index += 1) {\n const component = source[index];\n if (component === undefined) {\n continue;\n }\n const uid = keys.get(component.uid) ?? component.uid;\n sourceUids.set(uid, component.uid);\n const props = component.props;\n cloned.push({\n ...component,\n uid,\n ...(props === undefined ? {} : { props: remapReferences(props, keys) }),\n });\n }\n return cloned;\n}\n\n/**\n * Rewrites every `{ \"$entity\": … }` and `{ \"$component\": … }` inside a props object so that a\n * reference declared in a prefab points at *this* copy of it.\n *\n * @param props - The props object.\n * @param keys - Source uid to expanded uid; an empty map returns the object unchanged.\n * @returns The rewritten props, with key order preserved.\n */\nfunction remapReferences(props: JsonObject, keys: ReadonlyMap<string, string>): JsonObject {\n if (keys.size === 0) {\n return props;\n }\n return asJsonObject(remapValue(props, keys)) ?? props;\n}\n\n/**\n * The recursive half of {@link remapReferences}.\n *\n * @param value - The JSON to rewrite.\n * @param keys - Source uid to expanded uid.\n * @returns The rewritten JSON.\n */\nfunction remapValue(value: JsonValue, keys: ReadonlyMap<string, string>): JsonValue {\n const source = asJsonArray(value);\n if (source !== null) {\n const items: JsonValue[] = [];\n for (let index = 0; index < source.length; index += 1) {\n items.push(remapValue(source[index] ?? null, keys));\n }\n return items;\n }\n const object = asJsonObject(value);\n if (object === null) {\n return value;\n }\n const rewritten: Record<string, JsonValue> = {};\n for (const key of Object.keys(object)) {\n const entry = object[key] ?? null;\n if ((key === \"$entity\" || key === \"$component\") && typeof entry === \"string\") {\n rewritten[key] = keys.get(entry) ?? entry;\n continue;\n }\n rewritten[key] = remapValue(entry, keys);\n }\n return rewritten;\n}\n\n/**\n * Inverts the expanded-to-source component uid map, so an override path — which names source\n * uids — can find this copy's component.\n *\n * @param sourceUids - Expanded component uid to source component uid.\n * @returns Source component uid to expanded component uid.\n */\nfunction reverse(sourceUids: ReadonlyMap<string, string>): ReadonlyMap<string, string> {\n const inverted = new Map<string, string>();\n for (const [expanded, source] of sourceUids) {\n inverted.set(source, expanded);\n }\n return inverted;\n}\n","import type { AssetHandle } from \"../assets/types.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { ReferenceDecoder, ReferenceEncoder } from \"../schema/encode.js\";\n\n/**\n * The per-instance mapping from the uids a scene file carries to the runtime objects built from it\n * (`docs/architecture/02-scene-graph.md` §10). Loading the same scene twice produces two remaps, so\n * two instances of one prefab never resolve each other's references.\n *\n * @remarks\n * The \"file uid\" side of the table is the uid an entity carries in the *expanded* file — the same\n * uid for entities declared by the scene itself, and a freshly minted one for each copy an\n * `instance` entry expands, because a prefab instanced twice would otherwise contribute the same\n * uid twice.\n *\n * @public\n */\nexport class UidRemap {\n readonly #entities = new Map<string, Entity>();\n\n readonly #components = new Map<string, Component>();\n\n /**\n * How many entities the remap holds.\n *\n * @returns The entity count.\n */\n get size(): number {\n return this.#entities.size;\n }\n\n /**\n * Records the entity a file uid produced.\n *\n * @param fileUid - The uid the expanded file carries.\n * @param entity - The entity built from it.\n *\n * @internal\n */\n addEntity(fileUid: string, entity: Entity): void {\n this.#entities.set(fileUid, entity);\n }\n\n /**\n * Records the component a file uid produced.\n *\n * @param fileUid - The uid the expanded file carries.\n * @param component - The component built from it.\n *\n * @internal\n */\n addComponent(fileUid: string, component: Component): void {\n this.#components.set(fileUid, component);\n }\n\n /**\n * Resolves a file uid to its entity.\n *\n * @param fileUid - The uid read from the file.\n * @returns The entity, or `null` when the file declares no such entity.\n */\n entity(fileUid: string): Entity | null {\n return this.#entities.get(fileUid) ?? null;\n }\n\n /**\n * Resolves a file uid to its component.\n *\n * @param fileUid - The uid read from the file.\n * @returns The component, or `null` when the file declares no such component.\n */\n component(fileUid: string): Component | null {\n return this.#components.get(fileUid) ?? null;\n }\n\n /**\n * Every entity the remap holds, in the order the file declared them.\n *\n * @returns The live iterator over `[fileUid, entity]` pairs.\n */\n entries(): IterableIterator<readonly [string, Entity]> {\n return this.#entities.entries();\n }\n\n /** Drops every entry; the scene instance calls it on unload. */\n clear(): void {\n this.#entities.clear();\n this.#components.clear();\n }\n}\n\n/**\n * How an `asset()` field's address becomes the handle the component holds\n * (`docs/architecture/05-assets-and-loading.md` §3). The scene loader supplies one over the\n * dependency handles the `SceneAsset` already retains.\n *\n * @param address - The address the file carries.\n * @param type - The asset type the field or the file declared, or `null`.\n * @returns The loaded handle, or `null` when nothing loaded stands at that address.\n *\n * @internal\n */\nexport type AssetResolver = (address: string, type: string | null) => AssetHandle | null;\n\n/**\n * Resolves nothing — the decoder a caller with no asset service passes.\n *\n * @returns `null`, always.\n *\n * @internal\n */\nexport function noAssets(): null {\n return null;\n}\n\n/**\n * The {@link ReferenceDecoder} over a remap: this is what makes `entityRef`/`componentRef` fields\n * resolve to the *instance's own* objects rather than to another instance of the same prefab\n * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 5), and what turns an\n * `asset()` field's address into the handle the scene already loaded.\n *\n * @param remap - The table filled while the scene was being constructed.\n * @param assets - How an asset address becomes a handle; defaults to resolving nothing, which makes\n * every `asset()` field `null` with an `IGX-0602` issue.\n * @returns The decoder to hand `decodeProps`.\n *\n * @internal\n */\nexport function remapDecoder(remap: UidRemap, assets: AssetResolver = noAssets): ReferenceDecoder {\n return {\n entity: (uid: string): unknown => remap.entity(uid),\n component: (uid: string): unknown => remap.component(uid),\n asset: (address: string, type: string | null): unknown => assets(address, type),\n };\n}\n\n/**\n * The {@link ReferenceEncoder} the serializer uses: an entity or component is addressable only when\n * the file being written contains it, which is exactly \"it is in the membership set\"\n * (`docs/architecture/06-serialization-and-scene-format.md` §2 — \"File references never cross scene\n * files\").\n *\n * @param entities - The entities the file will contain.\n * @param components - The components the file will contain.\n * @returns The encoder to hand `encodeProps`.\n *\n * @internal\n */\nexport function membershipEncoder(entities: ReadonlySet<Entity>, components: ReadonlySet<Component>): ReferenceEncoder {\n return {\n entityUid: (value: unknown): string | null => {\n // Boundary check: `entityRef` fields hold entities, and `has` is the membership test that\n // makes the narrowing sound without an assertion.\n return isEntity(value) && entities.has(value) ? value.uid : null;\n },\n componentUid: (value: unknown): string | null => {\n return isComponent(value) && components.has(value) ? value.uid : null;\n },\n };\n}\n\n/**\n * Narrows an unknown reference value to an entity, structurally: the encoder only ever asks about\n * values a `entityRef` field held, and membership in the file's entity set is the real test.\n *\n * @param value - The field value.\n * @returns `true` when the value is an object carrying a string `uid`.\n */\nfunction isEntity(value: unknown): value is Entity {\n return typeof value === \"object\" && value !== null && typeof Reflect.get(value, \"uid\") === \"string\";\n}\n\n/**\n * Narrows an unknown reference value to a component.\n *\n * @param value - The field value.\n * @returns `true` when the value is an object carrying a string `uid`.\n */\nfunction isComponent(value: unknown): value is Component {\n return typeof value === \"object\" && value !== null && typeof Reflect.get(value, \"uid\") === \"string\";\n}\n","import { componentInternals } from \"../component/internals.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { DEFAULT_LAYER } from \"../layers/layer-table.js\";\nimport { decodeProps } from \"../schema/encode.js\";\nimport { expandScene } from \"./expand.js\";\nimport { findSceneDependency } from \"./scene-asset.js\";\nimport { UidRemap, remapDecoder } from \"./uid-remap.js\";\nimport type { ExpandedEntity, ExpandedInstance } from \"./expand.js\";\nimport type { MutableSceneEntity } from \"./overrides.js\";\nimport type { SceneAsset } from \"./scene-asset.js\";\nimport type { AssetResolver } from \"./uid-remap.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { ConcreteComponentType } from \"../component/component-type.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { EntityInstanceLink, EntityOrigin } from \"../entity/internals.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\nimport type { ReferenceDecoder } from \"../schema/encode.js\";\nimport type { JsonObject } from \"../schema/json.js\";\nimport type { Schema } from \"../schema/types.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * One recoverable problem found while a scene was being built. Nothing here stops the load: a file\n * degrades one field, one reference, or one layer rather than failing whole\n * (`docs/architecture/06-serialization-and-scene-format.md` §4).\n *\n * @public\n */\nexport interface SceneLoadIssue {\n /** The diagnostic code, for example `IGX-0602` or `IGX-0303`. */\n readonly code: string;\n /** The actionable sentence. */\n readonly message: string;\n}\n\n/**\n * Options accepted by {@link instantiateScene}.\n *\n * @public\n */\nexport interface InstantiateSceneOptions {\n /** The entity the scene's roots attach to; `null` or omitted makes them roots of `scene`. */\n readonly parent?: Entity | null;\n /** The instance that owns the new entities; defaults to the parent's, else `world.activeScene`. */\n readonly scene?: SceneInstance;\n /**\n * `true` treats the whole file as one instance: every entity gets a fresh uid and an\n * `Entity.prefab` link. This is what `world.instantiate` does; `world.loadScene` leaves it off so\n * that the scene's own entities keep the uids the file gave them\n * (`docs/architecture/02-scene-graph.md` §10).\n */\n readonly asInstance?: boolean;\n /** The handle the scene was loaded through, recorded on `Entity.prefab` when `asInstance`. */\n readonly assetHandle?: AssetHandle<SceneAsset> | null;\n /**\n * The entity that stands for the instance when `asInstance` is set and the file has more or fewer\n * than one root. `world.instantiate` creates it and passes it as both `parent` and `rootEntity`,\n * so that the call still answers with one entity.\n */\n readonly rootEntity?: Entity | null;\n /** `true` turns an `IGX-0604` hash mismatch from a diagnostic into a throw. */\n readonly strictInstanceHashes?: boolean;\n}\n\n/**\n * What {@link instantiateScene} produced.\n *\n * @public\n */\nexport interface SceneBuildResult {\n /** The entities that ended up parentless within the built subtree, in file order. */\n readonly roots: readonly Entity[];\n /** The file-local uid to runtime object table (`docs/architecture/02-scene-graph.md` §10). */\n readonly remap: UidRemap;\n /** Every recoverable problem, in discovery order. */\n readonly issues: readonly SceneLoadIssue[];\n}\n\n/**\n * Builds the entities of a scene asset into a world — steps 3 to 6 of the loading algorithm\n * (`docs/architecture/06-serialization-and-scene-format.md` §4). It is synchronous and does no I/O:\n * every asset the file references is already loaded, which is what a `SceneAsset` guarantees.\n *\n * @remarks\n * The mechanism that keeps `awake` honest is worth stating, because §4 step 6 and\n * `01-lifecycle-and-time.md` §4 state only the outcome. Entities are created with `active: false`,\n * so the enable transition computes \"not effectively enabled\" and queues nothing. Components are\n * attached with their schema defaults, then every component's props are decoded — that is where\n * `entityRef` and `componentRef` resolve, through a table that by then holds the whole scene. Only\n * then does a last pass write each entity's file `active` value in tree order, which is what queues\n * `awake` and `onEnable`, parents before children. Nothing observes the half-built scene, because\n * all of this runs in one synchronous block.\n *\n * @param world - The world to build into.\n * @param asset - The scene to build.\n * @param options - Where to attach the result, and how to treat instance hashes.\n * @returns The roots, the uid table, and every recoverable problem.\n * @throws IgnifxError with code `IGX-0302` on an instance cycle, `IGX-0307` when the file names an\n * unregistered component type, and `IGX-0604` when `strictInstanceHashes` is set and a recorded\n * instance hash does not match.\n *\n * @example\n * ```ts\n * const built = instantiateScene(world, sceneAsset, { scene: world.activeScene });\n * const player = built.remap.entity(\"01J9Z6M7E5S3A0V2Q4R8T1Y6WX\");\n * ```\n *\n * @public\n */\nexport function instantiateScene(world: World, asset: SceneAsset, options?: InstantiateSceneOptions): SceneBuildResult {\n const issues: SceneLoadIssue[] = [];\n const report = (code: string, message: string): void => {\n issues.push({ code, message });\n };\n const asInstance = options?.asInstance === true;\n const expanded = expandScene(asset, {\n nextUid: () => world.nextUid(),\n report,\n ...(options?.strictInstanceHashes === undefined ? {} : { strictInstanceHashes: options.strictInstanceHashes }),\n asInstance,\n });\n const parent = options?.parent ?? null;\n const context: BuildContext = {\n world,\n scene: options?.scene ?? (parent === null ? world.activeScene : parent.scene),\n remap: new UidRemap(),\n report,\n instances: indexInstances(expanded.instances),\n roots: [],\n built: [],\n };\n createEntities(context, expanded.entities, parent);\n attachComponents(context);\n linkInstances(context, options?.assetHandle ?? null, options?.rootEntity ?? null);\n decodeAllProps(context, sceneAssetResolver(world, asset));\n activate(context);\n return { roots: context.roots, remap: context.remap, issues };\n}\n\n/** Everything the build passes share. */\ninterface BuildContext {\n /** The world being built into. */\n readonly world: World;\n /** The instance that owns the new entities. */\n readonly scene: SceneInstance;\n /** The file-local uid table being filled. */\n readonly remap: UidRemap;\n /** Where recoverable problems go. */\n readonly report: (code: string, message: string) => void;\n /** The expansion's instances, by key. */\n readonly instances: ReadonlyMap<string, ExpandedInstance>;\n /** The parentless entities produced, in file order. */\n readonly roots: Entity[];\n /** Every entity produced, in file order, with the record that produced it. */\n readonly built: BuiltEntity[];\n}\n\n/** One entity created by the first pass, with the file record that produced it. */\ninterface BuiltEntity {\n /** The entity. */\n readonly entity: Entity;\n /** Its expanded file record. */\n readonly source: ExpandedEntity;\n /** Its components, in the order the file listed them. */\n readonly components: Component[];\n}\n\n/**\n * Indexes the expansion's instances by key.\n *\n * @param instances - The instances the expansion produced.\n * @returns The lookup table.\n */\nfunction indexInstances(instances: readonly ExpandedInstance[]): ReadonlyMap<string, ExpandedInstance> {\n const table = new Map<string, ExpandedInstance>();\n for (let index = 0; index < instances.length; index += 1) {\n const instance = instances[index];\n if (instance !== undefined) {\n table.set(instance.key, instance);\n }\n }\n return table;\n}\n\n/**\n * Pass 1: creates every entity, inactive, in tree order, and applies its plain properties.\n *\n * @param context - The build state.\n * @param entities - The expanded entity list.\n * @param parent - What the file's roots attach to.\n */\nfunction createEntities(context: BuildContext, entities: readonly ExpandedEntity[], parent: Entity | null): void {\n for (let index = 0; index < entities.length; index += 1) {\n const source = entities[index];\n if (source === undefined) {\n continue;\n }\n const data = source.data;\n const owner = data.parent === null ? parent : context.remap.entity(data.parent);\n if (data.parent !== null && owner === null) {\n context.report(\n CoreErrorCode.unresolvedReference,\n `The entity ${data.uid} names parent ${data.parent}, which the file does not declare; it becomes a root.`,\n );\n }\n const entity = context.world.createEntity(data.name, {\n ...(owner === null ? {} : { parent: owner }),\n scene: context.scene,\n active: false,\n uid: data.uid,\n });\n applyTransform(entity, data);\n applyLayer(context, entity, data);\n applyTags(entity, data);\n entity.isStatic = data.static === true;\n context.remap.addEntity(data.uid, entity);\n if (data.parent === null) {\n context.roots.push(entity);\n }\n context.built.push({ entity, source, components: [] });\n }\n}\n\n/**\n * Pass 2: attaches every component with its schema defaults, so the reference table is complete\n * before any prop is decoded.\n *\n * @param context - The build state.\n * @throws IgnifxError with code `IGX-0307` when the file names an unregistered component type: the\n * file cannot be honoured with a component missing, so this one is not recoverable.\n */\nfunction attachComponents(context: BuildContext): void {\n for (let index = 0; index < context.built.length; index += 1) {\n const built = context.built[index];\n if (built === undefined) {\n continue;\n }\n const records = built.source.data.components;\n for (let inner = 0; inner < records.length; inner += 1) {\n const record = records[inner];\n if (record === undefined) {\n continue;\n }\n const type = context.world.registry.get(record.type);\n if (type === null) {\n throw new IgnifxError(\n CoreErrorCode.unknownComponentTypeId,\n `${record.type} is not a registered component type.`,\n {\n context: { typeId: record.type, entity: built.source.data.uid },\n hint: \"Register the class with app.registerComponents before loading a scene that uses it.\",\n },\n );\n }\n // Boundary assertion (coding standards §5.2): only a concrete class reaches the registry's\n // type-id table, because `ComponentRegistry.register` takes a `ConcreteComponentType`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const component = built.entity.addComponent(type as ConcreteComponentType);\n componentInternals(component).uid = record.uid;\n if (record.enabled === false) {\n component.enabled = false;\n }\n context.remap.addComponent(record.uid, component);\n built.components.push(component);\n }\n }\n}\n\n/**\n * Pass 3: records where each entity came from, so `Entity.prefab` answers and the serializer can\n * re-emit the subtree as an `instance` entry with recomputed overrides.\n *\n * @param context - The build state.\n * @param handle - The handle the whole file was loaded through, for `asInstance` builds.\n * @param rootEntity - The entity that stands for the outermost instance, when the caller made one.\n */\nfunction linkInstances(context: BuildContext, handle: AssetHandle<SceneAsset> | null, rootEntity: Entity | null): void {\n const rootOfInstance = new Map<string, Entity>();\n for (let index = 0; index < context.built.length; index += 1) {\n const built = context.built[index];\n const key = built?.source.instanceKey ?? null;\n if (built === undefined || key === null || rootOfInstance.has(key)) {\n continue;\n }\n const instance = context.instances.get(key);\n if (instance === undefined) {\n continue;\n }\n // A nested `instance` entry names the entity it sat on; the outermost instance of a\n // `world.instantiate` has no such entity, so the caller's container — or, when the file has a\n // single root, that root — stands for it.\n const declared = instance.rootUid;\n const resolved = declared === null ? (rootEntity ?? built.entity) : context.remap.entity(declared);\n rootOfInstance.set(key, resolved ?? built.entity);\n }\n const insideOf = new Map<Entity, Entity>();\n for (let index = 0; index < context.built.length; index += 1) {\n const built = context.built[index];\n const key = built?.source.instanceKey ?? null;\n if (built === undefined || key === null) {\n continue;\n }\n const root = rootOfInstance.get(key);\n if (root !== undefined && root !== built.entity) {\n insideOf.set(built.entity, root);\n }\n }\n if (rootEntity !== null) {\n const own = ownedInstance(context, rootEntity, rootOfInstance, handle);\n if (own !== null) {\n entityInternals(rootEntity).origin = {\n sourceUid: \"\",\n instanceRoot: null,\n instanced: own,\n componentSourceUids: new Map<string, string>(),\n };\n }\n }\n for (let index = 0; index < context.built.length; index += 1) {\n const built = context.built[index];\n if (built === undefined) {\n continue;\n }\n const own = ownedInstance(context, built.entity, rootOfInstance, handle);\n const inside = insideOf.get(built.entity) ?? null;\n if (own === null && inside === null) {\n continue;\n }\n const origin: EntityOrigin = {\n sourceUid: built.source.sourceUid,\n instanceRoot: inside,\n instanced: own,\n componentSourceUids: built.source.componentSourceUids,\n };\n entityInternals(built.entity).origin = origin;\n }\n}\n\n/**\n * The instance an entity is the root of, if any.\n *\n * @param context - The build state.\n * @param entity - The candidate root.\n * @param rootOfInstance - Instance key to its root entity.\n * @param handle - The handle the whole file was loaded through, for `asInstance` builds.\n * @returns The link, or `null` when the entity roots no instance.\n */\nfunction ownedInstance(\n context: BuildContext,\n entity: Entity,\n rootOfInstance: ReadonlyMap<string, Entity>,\n handle: AssetHandle<SceneAsset> | null,\n): EntityInstanceLink | null {\n for (const [key, root] of rootOfInstance) {\n if (root !== entity) {\n continue;\n }\n const instance = context.instances.get(key);\n if (instance === undefined) {\n continue;\n }\n return {\n address: instance.address,\n asset: instance.rootUid === null ? handle : instance.asset,\n scene: instance.scene,\n };\n }\n return null;\n}\n\n/**\n * Pass 4: decodes every component's props, resolving `entityRef`/`componentRef` through the now\n * complete uid table (`docs/architecture/06-serialization-and-scene-format.md` §4 step 5).\n *\n * @param context - The build state.\n * @param assets - How an `asset()` field's address becomes the handle the scene already retains.\n */\nfunction decodeAllProps(context: BuildContext, assets: AssetResolver): void {\n const decoder = remapDecoder(context.remap, assets);\n for (let index = 0; index < context.built.length; index += 1) {\n const built = context.built[index];\n if (built === undefined) {\n continue;\n }\n const records = built.source.data.components;\n for (let inner = 0; inner < built.components.length; inner += 1) {\n const component = built.components[inner];\n const record = records[inner];\n if (component === undefined || record === undefined) {\n continue;\n }\n const schema = context.world.registry.describe(component.constructor).schema;\n if (schema !== null) {\n applyProps(context, decoder, component, schema, record.props ?? {}, record.uid);\n }\n }\n }\n}\n\n/**\n * Decodes one component's props and writes them onto the instance.\n *\n * @param context - The build state.\n * @param decoder - How uids resolve to entities and components.\n * @param component - The component to fill.\n * @param schema - Its declared fields.\n * @param props - The JSON from the file.\n * @param uid - The component's file uid, for diagnostics.\n */\nfunction applyProps(\n context: BuildContext,\n decoder: ReferenceDecoder,\n component: Component,\n schema: Schema,\n props: JsonObject,\n uid: string,\n): void {\n const decoded = decodeProps(schema, props, decoder);\n for (let index = 0; index < decoded.issues.length; index += 1) {\n const issue = decoded.issues[index];\n if (issue !== undefined) {\n context.report(issue.code, `${uid}.${issue.path === \"\" ? \"<value>\" : issue.path}: ${issue.message}`);\n }\n }\n // Boundary assertion (coding standards §5.2): the schema declares exactly these property names on\n // the component's generated base class, and `decodeProps` produced one value per declared field.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const target = component as unknown as Record<string, unknown>;\n // Boundary assertion (coding standards §5.2): the same invariant, read side.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const values = decoded.value as Record<string, unknown>;\n for (const name of Object.keys(schema)) {\n target[name] = values[name];\n }\n}\n\n/**\n * Pass 5: writes each entity's file `active` value in tree order, which is what queues `awake` and\n * `onEnable` parents before children.\n *\n * @param context - The build state.\n */\nfunction activate(context: BuildContext): void {\n for (let index = 0; index < context.built.length; index += 1) {\n const built = context.built[index];\n if (built !== undefined && built.source.data.active !== false) {\n built.entity.active = true;\n }\n }\n}\n\n/**\n * Writes the file's local transform onto a freshly created entity.\n *\n * @param entity - The entity.\n * @param data - Its file record.\n */\nfunction applyTransform(entity: Entity, data: MutableSceneEntity): void {\n const { position, rotation, scale } = data.transform;\n entity.transform.localPosition.set(position[0] ?? 0, position[1] ?? 0, position[2] ?? 0);\n entity.transform.localRotation.set(rotation[0] ?? 0, rotation[1] ?? 0, rotation[2] ?? 0, rotation[3] ?? 1);\n entity.transform.localScale.set(scale[0] ?? 1, scale[1] ?? 1, scale[2] ?? 1);\n}\n\n/**\n * Resolves the file's layer name against the project settings, falling back to `Default` with\n * `IGX-0303` rather than failing the load (`docs/architecture/02-scene-graph.md` §7).\n *\n * @param context - The build state.\n * @param entity - The entity.\n * @param data - Its file record.\n */\nfunction applyLayer(context: BuildContext, entity: Entity, data: MutableSceneEntity): void {\n const name = data.layer;\n if (name === undefined) {\n return;\n }\n const slot = context.world.layers.indexOf(name);\n if (slot < 0) {\n context.report(CoreErrorCode.unknownLayer, `${name} is not a layer declared in the project settings.`);\n entity.layer = DEFAULT_LAYER;\n return;\n }\n entity.layer = slot;\n}\n\n/**\n * Copies the file's tags onto an entity.\n *\n * @param entity - The entity.\n * @param data - Its file record.\n */\nfunction applyTags(entity: Entity, data: MutableSceneEntity): void {\n const tags = data.tags;\n if (tags === undefined) {\n return;\n }\n for (let index = 0; index < tags.length; index += 1) {\n const tag = tags[index];\n if (tag !== undefined && tag !== \"\") {\n entity.tags.add(tag);\n }\n }\n}\n\n/**\n * Builds the resolver `asset()` fields decode through: the scene's own retained dependency handles\n * first, then the app's cache (`docs/architecture/05-assets-and-loading.md` §3).\n *\n * @remarks\n * The dependency list is searched first, and by address rather than by identity, because that is\n * the set the file itself declared: an address the file references is loaded and retained by the\n * `SceneAsset`, so the handle it yields is the one whose lifetime matches the scene instance. The\n * cache fallback covers an address a component's props name but the loader's `$asset` walk did not\n * reach — an override written by hand, say — and an in-code `memory:` asset a script registered\n * before instantiating a prefab that names it.\n *\n * @param world - The world being built into, for its app's asset service.\n * @param asset - The scene being built.\n * @returns The resolver, or one that resolves nothing when the app has no asset service yet.\n */\nfunction sceneAssetResolver(world: World, asset: SceneAsset): AssetResolver {\n const dependencies = asset.dependencies;\n return (address: string, type: string | null): AssetHandle | null => {\n for (let index = 0; index < dependencies.length; index += 1) {\n const handle = dependencies[index];\n if (handle !== undefined && handle.address === address && handle.state === \"loaded\") {\n if (type === null || handle.type === type) {\n return handle;\n }\n }\n }\n const cached = world.app.assets.get(address);\n return cached !== null && cached.state === \"loaded\" ? cached : null;\n };\n}\n\n/**\n * Checks that every scene a file instances — at any depth — is among the loaded dependencies, which\n * is what makes `world.instantiate` safe to be synchronous\n * (`docs/architecture/02-scene-graph.md` §2).\n *\n * @param asset - The scene to check.\n * @throws IgnifxError with code `IGX-0301` naming the first instanced scene that is not loaded.\n *\n * @public\n */\nexport function assertSceneDependenciesLoaded(asset: SceneAsset): void {\n const seen = new Set<string>();\n const pending: SceneAsset[] = [asset];\n while (pending.length > 0) {\n const current = pending.pop();\n if (current === undefined || seen.has(current.address)) {\n continue;\n }\n seen.add(current.address);\n const entities = current.file.entities;\n for (let index = 0; index < entities.length; index += 1) {\n const instance = entities[index]?.instance;\n if (instance === undefined) {\n continue;\n }\n const address = instance.scene.$asset;\n const resolved = findSceneDependency(current, address);\n if (resolved === null) {\n throw new IgnifxError(CoreErrorCode.sceneNotLoaded, `The scene ${address} is not loaded yet.`, {\n context: { scene: address, entity: current.address },\n hint: \"Load it through the asset system first; world.instantiateAsync does that for you.\",\n });\n }\n pending.push(resolved.value);\n }\n }\n}\n","import { ComponentRegistry } from \"../component/component-registry.js\";\nimport { ComponentStore } from \"../component/component-store.js\";\nimport { ReferenceTracker } from \"../component/reference-tracker.js\";\nimport { Entity } from \"../entity/entity.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { HandleAllocator } from \"../handles/handle-allocator.js\";\nimport { toComponentHandle, toEntityHandle } from \"../handles/handle.js\";\nimport { createUlidFactory } from \"../ids/ulid.js\";\nimport { createLayerTable } from \"../layers/layer-table.js\";\nimport { LifecycleQueue } from \"../lifecycle/lifecycle-queue.js\";\nimport { createNode } from \"../lite/node.js\";\nimport { raycastRenderScene } from \"../render/raycast.js\";\nimport { SceneInstance } from \"../scene/scene-instance.js\";\nimport { assertSceneDependenciesLoaded, instantiateScene } from \"../serialization/load.js\";\nimport { Signal } from \"../signal/signal.js\";\nimport type { WorldHost } from \"./world-host.js\";\nimport type { WorldInternals } from \"./world-internals.js\";\nimport type { App, ErrorReport, FrameState } from \"../app/types.js\";\nimport type { AssetHandle, AssetRef, Assets } from \"../assets/types.js\";\nimport type { ComponentType } from \"../component/component-type.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { ComponentHandle, EntityHandle } from \"../handles/handle.js\";\nimport type { LayerTable } from \"../layers/layer-table.js\";\nimport type { FrameStateController } from \"../lifecycle/frame-state.js\";\nimport type { LiteScene } from \"../lite/scene.js\";\nimport type { QuatLike, Vec3Like } from \"../math/types.js\";\nimport type { Camera, Ray } from \"../render/camera.js\";\nimport type { RenderPick, RenderPickOptions } from \"../render/renderer.js\";\nimport type { SceneLoadIssue } from \"../serialization/load.js\";\nimport type { SceneAsset } from \"../serialization/scene-asset.js\";\nimport type { SceneFile } from \"../serialization/scene-file.js\";\nimport type { DeferredQueue } from \"../signal/signal.js\";\n\n/**\n * The running simulation: the entity registry, the scene instances, and the lifecycle queues\n * (`docs/architecture/02-scene-graph.md` §2). One world per app in the MVP.\n *\n * @remarks\n * Phase 1 ships the subset that needs no asset system: entity creation, queries, the implicit\n * `\"default\"` scene, and the lifecycle. `loadScene`, `unloadScene`, `instantiate`,\n * `instantiateAsync`, and `moveEntityToScene` arrive in Phase 2, and `onSceneLoaded`/\n * `onSceneUnloaded` exist here but never fire until then.\n *\n * @example\n * ```ts\n * const player = app.world.createEntity(\"Player\");\n * for (const script of app.world.components(Script)) {\n * script.enabled = false;\n * }\n * ```\n *\n * @public\n */\nexport class World implements WorldHost {\n readonly #app: App;\n\n readonly #scene: LiteScene;\n\n /**\n * The object `world.lite` hands out. It is allocated once and updated in place, so reading the\n * escape hatch every frame allocates nothing (coding standards §7).\n */\n readonly #lite: { scene: LiteScene; simulationScene: LiteScene | null };\n\n readonly #frameState: FrameStateController;\n\n readonly #layers: LayerTable;\n\n readonly #registry: ComponentRegistry;\n\n readonly #store = new ComponentStore();\n\n readonly #references = new ReferenceTracker();\n\n readonly #lifecycle: LifecycleQueue;\n\n readonly #entities = new HandleAllocator<Entity>();\n\n readonly #components = new HandleAllocator<Component>();\n\n readonly #byUid = new Map<string, Entity>();\n\n readonly #byTag = new Map<string, Entity[]>();\n\n readonly #scenes: SceneInstance[] = [];\n\n readonly #nextUid: () => string;\n\n readonly #deferredQueue: DeferredQueue | null;\n\n readonly #onEntityCreated: Signal<Entity>;\n\n readonly #onEntityDestroyed: Signal<Entity>;\n\n readonly #onSceneLoaded: Signal<SceneInstance>;\n\n readonly #onSceneUnloaded: Signal<SceneInstance>;\n\n #activeScene: SceneInstance;\n\n #mainCamera: Camera | null = null;\n\n #serial = 0;\n\n #isDisposed = false;\n\n /**\n * Builds a world. Call `createWorld` instead; the runtime owns this.\n *\n * @param options - The app, the Lite scene, the frame state, and the resolved settings.\n *\n * @internal\n */\n constructor(options: CreateWorldOptions) {\n this.#app = options.app;\n this.#scene = options.scene;\n this.#lite = { scene: options.scene, simulationScene: null };\n this.#frameState = options.frameState;\n this.#layers = options.layers ?? createLayerTable();\n this.#registry = options.registry ?? new ComponentRegistry();\n this.#nextUid = options.ulid ?? createUlidFactory();\n this.#deferredQueue = options.deferredQueue ?? null;\n this.#lifecycle = new LifecycleQueue(this);\n this.#onEntityCreated = this.createSignal<Entity>();\n this.#onEntityDestroyed = this.createSignal<Entity>();\n this.#onSceneLoaded = this.createSignal<SceneInstance>();\n this.#onSceneUnloaded = this.createSignal<SceneInstance>();\n const initial = new SceneInstance(this.#nextUid(), \"default\", true);\n this.#scenes.push(initial);\n this.#activeScene = initial;\n }\n\n /**\n * The app that owns the world.\n *\n * @returns The app.\n */\n get app(): App {\n return this.#app;\n }\n\n /**\n * The world itself; `WorldHost` names it so entities can reach it.\n *\n * @returns This world.\n */\n get world(): World {\n return this;\n }\n\n /**\n * The project's resolved layer names. `world.layers.mask(\"Player\", \"Enemy\")` builds a mask.\n *\n * @returns The layer table.\n */\n get layers(): LayerTable {\n return this.#layers;\n }\n\n /**\n * The component-class table.\n *\n * @returns The registry.\n */\n get registry(): ComponentRegistry {\n return this.#registry;\n }\n\n /**\n * The live per-type component index.\n *\n * @returns The store.\n *\n * @internal\n */\n get store(): ComponentStore {\n return this.#store;\n }\n\n /**\n * The tracked-reference table.\n *\n * @returns The tracker.\n *\n * @internal\n */\n get references(): ReferenceTracker {\n return this.#references;\n }\n\n /**\n * Where in the frame the engine is.\n *\n * @returns The frame-state controller.\n *\n * @internal\n */\n get frameState(): FrameStateController {\n return this.#frameState;\n }\n\n /**\n * The lifecycle queues and flushes the scheduler drives.\n *\n * @returns The lifecycle API.\n *\n * @internal\n */\n get lifecycle(): WorldInternals {\n return this.#lifecycle;\n }\n\n /**\n * Every loaded scene instance, in load order; the implicit `\"default\"` scene is always first.\n *\n * @returns The live scene list.\n */\n get scenes(): readonly SceneInstance[] {\n return this.#scenes;\n }\n\n /**\n * The scene that owns entities created in code without an explicit `scene` option. Assigning to\n * it makes another instance the default owner.\n *\n * @returns The active instance.\n */\n get activeScene(): SceneInstance {\n return this.#activeScene;\n }\n\n // The accessor pair is documented on the getter only: API Extractor rejects a doc comment on the\n // setter of a documented property (`ae-setter-with-docs`).\n // eslint-disable-next-line jsdoc/require-jsdoc -- see the comment above\n set activeScene(scene: SceneInstance) {\n this.#activeScene = scene;\n }\n\n /**\n * `true` once {@link World.dispose} has run.\n *\n * @returns `true` when the world has been disposed.\n */\n get isDisposed(): boolean {\n return this.#isDisposed;\n }\n\n /**\n * Emitted for every entity the world creates.\n *\n * @returns The signal.\n */\n get onEntityCreated(): Signal<Entity> {\n return this.#onEntityCreated;\n }\n\n /**\n * Emitted for every entity the destroy flush releases.\n *\n * @returns The signal.\n */\n get onEntityDestroyed(): Signal<Entity> {\n return this.#onEntityDestroyed;\n }\n\n /**\n * Emitted when a scene instance finishes loading. Never fires before Phase 2.\n *\n * @returns The signal.\n */\n get onSceneLoaded(): Signal<SceneInstance> {\n return this.#onSceneLoaded;\n }\n\n /**\n * Emitted when a scene instance is unloaded. Never fires before Phase 2.\n *\n * @returns The signal.\n */\n get onSceneUnloaded(): Signal<SceneInstance> {\n return this.#onSceneUnloaded;\n }\n\n /**\n * Babylon Lite objects the world owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The render scene, and the physics simulation scene once an extension has set one. The\n * object is the same one on every read and is updated in place; do not retain a copy of its\n * fields.\n */\n get lite(): WorldLiteHandles {\n return this.#lite;\n }\n\n /**\n * Points `world.lite.simulationScene` at the scene an extension simulates in, or clears it\n * (`docs/architecture/09-physics.md` §1, `02-scene-graph.md` §2). Reached by extension authors\n * through `ExtensionContext.setSimulationScene`.\n *\n * @param scene - The simulation scene, or `null` to clear it in the extension's `dispose`.\n * @throws IgnifxError with code `IGX-0410` when a different simulation scene is already set.\n *\n * @internal\n */\n setSimulationScene(scene: LiteScene | null): void {\n const current = this.#lite.simulationScene;\n if (scene !== null && current !== null && current !== scene) {\n throw new IgnifxError(\n CoreErrorCode.simulationSceneAlreadySet,\n \"This world already has a different simulation scene; a world has one simulation scene.\",\n { hint: \"Clear it with setSimulationScene(null) before handing the world another one.\" },\n );\n }\n this.#lite.simulationScene = scene;\n }\n\n /**\n * Creates an entity with a transform and a Lite node.\n *\n * @param name - The display name; defaults to `\"Entity\"`.\n * @param options - The parent, the owning scene, and an initial world position and rotation.\n * @returns The new entity, already active and registered.\n *\n * @example\n * ```ts\n * const hand = world.createEntity(\"Hand\", { parent: player, position: { x: 0.3, y: 1.2, z: 0 } });\n * ```\n */\n createEntity(name: string = \"Entity\", options?: CreateEntityOptions): Entity {\n const parent = options?.parent ?? null;\n const scene = options?.scene ?? (parent === null ? this.#activeScene : parent.scene);\n const node = createNode(name);\n const requested = options?.uid;\n const uid = requested === undefined || this.#byUid.has(requested) ? this.#nextUid() : requested;\n // Reserved first, bound second: the entity's constructor writes its own handle into the Lite\n // node's metadata, so the handle has to exist before the entity does.\n const handle = toEntityHandle(this.#entities.reserve());\n const entity = new Entity(this, handle, uid, node, name, scene);\n this.#entities.bind(handle, entity);\n this.#byUid.set(uid, entity);\n if (options?.active === false) {\n entityInternals(entity).active = false;\n }\n if (parent === null) {\n scene.addRoot(entity);\n } else {\n entity.setParent(parent, { worldPositionStays: false });\n }\n const position = options?.position;\n if (position !== undefined) {\n entity.transform.position = position;\n }\n const rotation = options?.rotation;\n if (rotation !== undefined) {\n entity.transform.rotation = rotation;\n }\n this.notifyEntityCreated(entity);\n this.#lifecycle.refreshActivation(entity);\n return entity;\n }\n\n /**\n * Looks an entity up by its stable identifier.\n *\n * @param uid - The ULID.\n * @returns The entity, or `null` when nothing in this world carries that uid.\n */\n getEntity(uid: string): Entity | null {\n return this.#byUid.get(uid) ?? null;\n }\n\n /**\n * Resolves a dense runtime handle.\n *\n * @param handle - The handle.\n * @returns The entity, or `null` when the handle is stale — a handle kept across a destroy never\n * resolves to whatever entity recycled the slot.\n */\n getEntityByHandle(handle: EntityHandle): Entity | null {\n return this.#entities.get(handle);\n }\n\n /**\n * Resolves a dense component handle.\n *\n * @param handle - The handle, as a Lite node's `metadata.ignifx` tag carries it.\n * @returns The component, or `null` when the handle is stale.\n */\n getComponentByHandle(handle: ComponentHandle): Component | null {\n return this.#components.get(handle);\n }\n\n /**\n * The camera this world renders through: the enabled {@link Camera} with the highest `priority`\n * (`docs/architecture/07-rendering.md` §2.1).\n *\n * @remarks\n * The `PreRender` render-sync system chooses it and assigns it to the Lite scene, so the value is\n * the one the **last rendered frame** used, not a live query. A world with no enabled camera\n * renders nothing and logs `IGX-0706` once.\n *\n * @returns The main camera, or `null` when the world has none.\n *\n * @example\n * ```ts\n * const ray = world.mainCamera?.screenToRay(event.offsetX, event.offsetY) ?? null;\n * ```\n */\n get mainCamera(): Camera | null {\n return this.#mainCamera;\n }\n\n /**\n * Records the camera the render-sync system chose.\n *\n * @param camera - The new main camera, or `null`.\n *\n * @internal\n */\n setMainCamera(camera: Camera | null): void {\n this.#mainCamera = camera;\n }\n\n /**\n * Casts a ray against every renderable mesh in the world, on the CPU\n * (`docs/architecture/07-rendering.md` §3).\n *\n * @remarks\n * Distinct from a physics raycast (`09-physics.md` §5): this hits **render** geometry, including\n * meshes that carry no collider, and it ignores visibility — a hidden mesh still occludes, which\n * is Lite's documented behaviour (`src/lite/picking.ts`). It reads each mesh's CPU vertex copy, so\n * a mesh built from a GPU-only path is silently skipped and `app.renderer.pickAsync` is the exact\n * answer.\n *\n * @param ray - The ray to cast.\n * @param options - An entity filter.\n * @returns What was hit, or `null` for a miss.\n *\n * @example\n * ```ts\n * const hit = world.raycastRender(camera.screenToRay(x, y) ?? createRay());\n * ```\n */\n raycastRender(ray: Ray, options?: RenderPickOptions): RenderPick | null {\n return raycastRenderScene(this, this.#scene, ray, options);\n }\n\n /**\n * The first entity with a name, depth-first from the roots of every scene.\n *\n * @remarks\n * Linear in the number of entities, and names are not unique: this is a prototyping and tooling\n * convenience, not a lookup the engine itself uses\n * (`docs/architecture/02-scene-graph.md` §4).\n *\n * @param name - The name to match exactly.\n * @returns The first match, or `null`.\n */\n findByName(name: string): Entity | null {\n for (let index = 0; index < this.#scenes.length; index += 1) {\n const roots = this.#scenes[index]?.roots ?? [];\n for (let root = 0; root < roots.length; root += 1) {\n const entity = roots[root];\n if (entity === undefined) {\n continue;\n }\n const found = findNamed(entity, name);\n if (found !== null) {\n return found;\n }\n }\n }\n return null;\n }\n\n /**\n * Every entity with a name, depth-first from the roots of every scene.\n *\n * @param name - The name to match exactly.\n * @returns A freshly allocated array; empty when nothing matches.\n */\n findAllByName(name: string): Entity[] {\n const found: Entity[] = [];\n for (let index = 0; index < this.#scenes.length; index += 1) {\n const roots = this.#scenes[index]?.roots ?? [];\n for (let root = 0; root < roots.length; root += 1) {\n const entity = roots[root];\n if (entity !== undefined) {\n collectNamed(entity, name, found);\n }\n }\n }\n return found;\n }\n\n /**\n * Every entity carrying a tag.\n *\n * @remarks\n * Indexed, not searched: the world maintains one array per tag as `tags.add`/`tags.delete` run\n * and as entities are destroyed, so this is O(1) to obtain and allocates nothing. The array is\n * **live** and its identity is stable for the tag's lifetime in this world, so it can be cached\n * in `awake`; treat it as read-only.\n *\n * @param tag - The tag.\n * @returns The live list of tagged entities. A tag nothing carries yields a shared frozen empty\n * array.\n */\n findByTag(tag: string): readonly Entity[] {\n return this.#byTag.get(tag) ?? EMPTY_ENTITIES;\n }\n\n /**\n * Every component of a class, by identity **and** inheritance — the primary iteration API for\n * systems (`docs/architecture/02-scene-graph.md` §9).\n *\n * @typeParam T - The component type.\n * @param type - The component class, abstract or concrete; `components(Script)` returns every\n * script.\n * @returns The live list. O(1) to obtain, stable within a phase, and never allocated per call.\n */\n components<T extends Component>(type: ComponentType<T>): readonly T[] {\n return this.#store.components(type);\n }\n\n /**\n * Loads a scene file and builds its entities (`docs/architecture/02-scene-graph.md` §2).\n *\n * @remarks\n * `\"single\"` (the default) unloads every instance that is not `persistent` first — the implicit\n * `\"default\"` scene is persistent, so entities created in code survive. The asset and everything\n * it references are loaded before a single entity is created, which is what lets `asset()` fields\n * be usable in `awake` (`06-serialization-and-scene-format.md` §4 step 2).\n *\n * Construction happens in one synchronous block once the asset is in memory, so nothing observes\n * a half-built scene; `awake` and `onEnable` then run in tree order, through the world's own\n * lifecycle flush, before the returned promise settles. A component queued for `awake` by\n * something else earlier in the frame is flushed with it — the flush drains the whole queue, as\n * it does in the frame.\n *\n * @param scene - The scene address, or a reference carrying one.\n * @param options - The mode, cancellation, progress, and whether to make the result active.\n * @returns The instance, once every entity exists, every reference is resolved, and `awake` has\n * run.\n * @throws IgnifxError with code `IGX-0502` when `options.signal` aborts, and whatever the asset\n * system throws for a missing or malformed file.\n *\n * @example\n * ```ts\n * const level = await world.loadScene(\"levels/level01.scene.json\", { mode: \"additive\" });\n * ```\n */\n async loadScene(scene: AssetRef<SceneAsset> | string, options?: LoadSceneOptions): Promise<SceneInstance> {\n const mode = options?.mode ?? \"single\";\n if (mode === \"single\") {\n await this.#unloadNonPersistent();\n }\n const address = typeof scene === \"string\" ? scene : scene.address;\n const onProgress = options?.onProgress;\n const handle = this.#assets().load<SceneAsset>(scene, {\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n ...(onProgress === undefined\n ? {}\n : {\n onProgress: (fraction: number): void => {\n onProgress({ address, fraction });\n },\n }),\n });\n await handle.promise;\n if (options?.signal?.aborted === true) {\n handle.release();\n throw new IgnifxError(CoreErrorCode.assetLoadAborted, `Loading ${address} was aborted.`, {\n context: { asset: address },\n });\n }\n const asset = handle.value;\n const instance = new SceneInstance(this.#nextUid(), asset.file.name, false);\n instance.setAsset(handle);\n instance.setLoaded(false);\n this.#scenes.push(instance);\n const built = instantiateScene(this, asset, {\n scene: instance,\n ...(options?.strictInstanceHashes === undefined ? {} : { strictInstanceHashes: options.strictInstanceHashes }),\n });\n instance.setRemap(built.remap);\n instance.setSettings(asset.file.settings ?? null);\n instance.setLoaded(true);\n this.#reportSceneIssues(address, built.issues);\n if (options?.setActive ?? mode === \"single\") {\n this.#activeScene = instance;\n }\n this.#lifecycle.flushAwakeAndEnable();\n this.#onSceneLoaded.emit(instance);\n return instance;\n }\n\n /**\n * Unloads a scene instance: `onUnloading` fires while its entities are still valid, its roots are\n * destroyed through the normal destroy path (children before parents, `onDisable` then\n * `onDestroy`), and the assets it held are released\n * (`docs/architecture/02-scene-graph.md` §3).\n *\n * @param instance - The instance to unload. Unloading the implicit `\"default\"` scene, or an\n * instance this world does not own, does nothing.\n * @returns A promise that settles once the destroy flush has run.\n *\n * @example\n * ```ts\n * await world.unloadScene(level);\n * ```\n */\n async unloadScene(instance: SceneInstance): Promise<void> {\n const at = this.#scenes.indexOf(instance);\n if (at <= 0) {\n return;\n }\n instance.onUnloading.emit();\n const roots = [...instance.roots];\n for (let index = 0; index < roots.length; index += 1) {\n roots[index]?.destroy();\n }\n this.#lifecycle.flushDestroy();\n this.#scenes.splice(at, 1);\n if (this.#activeScene === instance) {\n this.#activeScene = this.#scenes[0] ?? instance;\n }\n instance.setLoaded(false);\n instance.remap?.clear();\n instance.setRemap(null);\n const asset = instance.asset;\n instance.setAsset(null);\n asset?.release();\n this.#onSceneUnloaded.emit(instance);\n await Promise.resolve();\n }\n\n /**\n * Instantiates a loaded scene asset as a prefab (ADR-0005) and answers with its root.\n *\n * @remarks\n * Synchronous, because a `SceneAsset` carries its dependencies already loaded. Every entity gets\n * a fresh uid and an `Entity.prefab` link (`02-scene-graph.md` §6, §10). A file with exactly one\n * root answers with that root; a file with several gets a container entity named after the scene,\n * so the call always answers with one entity.\n *\n * `awake` follows the same rule as `addComponent`: queued for the frame's lifecycle flush, or run\n * nested and synchronously when `instantiate` is called from inside a callback\n * (`01-lifecycle-and-time.md` §4).\n *\n * @param scene - The loaded scene asset.\n * @param options - Parent, owning instance, name, and initial placement.\n * @returns The instance root.\n * @throws IgnifxError with code `IGX-0301` when a scene the file instances is not loaded, and\n * `IGX-0302` when instancing would nest a scene inside itself.\n *\n * @example\n * ```ts\n * const enemy = world.instantiate(enemyPrefab, { position: { x: 4, y: 0, z: 2 } });\n * ```\n */\n instantiate(scene: SceneAsset, options?: InstantiateOptions): Entity {\n assertSceneDependenciesLoaded(scene);\n const parent = options?.parent ?? null;\n const owner = options?.scene ?? (parent === null ? this.#activeScene : parent.scene);\n const handle = this.#sceneHandle(scene.address);\n const rootCount = countRoots(scene.file);\n const container =\n rootCount === 1\n ? null\n : this.createEntity(options?.name ?? scene.file.name, {\n ...(parent === null ? {} : { parent }),\n scene: owner,\n active: false,\n });\n const built = instantiateScene(this, scene, {\n parent: container ?? parent,\n scene: owner,\n asInstance: true,\n assetHandle: handle,\n rootEntity: container,\n ...(options?.strictInstanceHashes === undefined ? {} : { strictInstanceHashes: options.strictInstanceHashes }),\n });\n this.#reportSceneIssues(scene.address, built.issues);\n const root = container ?? onlyRoot(built.roots);\n if (container === null && options?.name !== undefined) {\n root.name = options.name;\n }\n placeRoot(root, options);\n if (container !== null) {\n container.active = true;\n }\n return root;\n }\n\n /**\n * Loads a scene asset and instantiates it (`docs/architecture/02-scene-graph.md` §2).\n *\n * @param scene - The scene address, or a reference carrying one.\n * @param options - Parent, owning instance, name, and initial placement.\n * @returns The instance root, once the asset and its dependencies have loaded.\n *\n * @example\n * ```ts\n * const enemy = await world.instantiateAsync(\"prefabs/enemy.prefab.json\");\n * ```\n */\n async instantiateAsync(scene: AssetRef<SceneAsset> | string, options?: InstantiateOptions): Promise<Entity> {\n const handle = await this.#assets().loadAsync<SceneAsset>(scene);\n return this.instantiate(handle.value, options);\n }\n\n /**\n * Moves a root entity and its subtree to another scene instance\n * (`docs/architecture/02-scene-graph.md` §6). This is the per-object equivalent of marking a\n * whole instance `persistent`.\n *\n * @param entity - The entity to move; it must be a root.\n * @param scene - The instance that will own it.\n * @throws IgnifxError with code `IGX-0309` when the entity has a parent — a child follows its\n * parent's instance, so reparent it first — and `IGX-0101` when it has been destroyed.\n *\n * @example\n * ```ts\n * world.moveEntityToScene(player, world.scenes[0]);\n * ```\n */\n moveEntityToScene(entity: Entity, scene: SceneInstance): void {\n if (entity.isDestroyed) {\n throw new IgnifxError(CoreErrorCode.mutationAfterDestroy, \"This entity has been destroyed.\", {\n context: { target: \"entity\", entity: entity.uid, operation: \"moveEntityToScene\" },\n });\n }\n if (entity.parent !== null) {\n throw new IgnifxError(\n CoreErrorCode.entityIsNotSceneRoot,\n `${entity.name} has a parent, so it cannot move between scene instances on its own.`,\n {\n context: { entity: entity.uid, scene: scene.name },\n hint: \"Call entity.setParent(null) first, or move the root of its subtree.\",\n },\n );\n }\n this.moveToScene(entity, scene);\n }\n\n /**\n * Unloads every instance that is not `persistent`, oldest first.\n *\n * @returns A promise that settles once every unload has run.\n */\n async #unloadNonPersistent(): Promise<void> {\n const doomed: SceneInstance[] = [];\n for (let index = 1; index < this.#scenes.length; index += 1) {\n const instance = this.#scenes[index];\n if (instance !== undefined && !instance.persistent) {\n doomed.push(instance);\n }\n }\n // Each unload runs its destroy flush synchronously before it yields, so awaiting them together\n // still releases the scenes in the order they were loaded.\n await Promise.all(doomed.map(async (instance) => this.unloadScene(instance)));\n }\n\n /**\n * The asset service, which every scene operation needs.\n *\n * @returns The service.\n */\n #assets(): Assets {\n return this.#app.assets;\n }\n\n /**\n * The handle a loaded scene asset stands behind, when the asset service knows one.\n *\n * @param address - The scene's address.\n * @returns The handle, or `null` when there is no asset service or no cached handle.\n */\n #sceneHandle(address: string): AssetHandle<SceneAsset> | null {\n return this.#app.assets.get<SceneAsset>(address);\n }\n\n /**\n * Writes a load's recoverable problems to the app log, one record each.\n *\n * @param address - The scene being built.\n * @param issues - What the build found.\n */\n #reportSceneIssues(address: string, issues: readonly SceneLoadIssue[]): void {\n for (let index = 0; index < issues.length; index += 1) {\n const issue = issues[index];\n if (issue !== undefined) {\n this.#app.log.warn(`${issue.code}: ${address}: ${issue.message}`);\n }\n }\n }\n\n /**\n * Destroys every entity, cancels every coroutine, releases every Lite node, and clears every\n * index. The Lite scene itself belongs to the app and is left alone.\n */\n dispose(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#isDisposed = true;\n this.#lite.simulationScene = null;\n this.#lifecycle.disposeWorld();\n this.#byUid.clear();\n this.#byTag.clear();\n this.#entities.clear();\n this.#components.clear();\n }\n\n /**\n * The next ULID.\n *\n * @returns A fresh identifier.\n *\n * @internal\n */\n nextUid(): string {\n return this.#nextUid();\n }\n\n /**\n * The next creation serial.\n *\n * @returns A monotonically increasing integer.\n *\n * @internal\n */\n nextSerial(): number {\n this.#serial += 1;\n return this.#serial;\n }\n\n /**\n * Issues a component handle.\n *\n * @param component - The component being attached.\n * @returns Its handle.\n *\n * @internal\n */\n allocateComponentHandle(component: Component): ComponentHandle {\n return toComponentHandle(this.#components.allocate(component));\n }\n\n /**\n * Invalidates a component handle.\n *\n * @param handle - The handle.\n *\n * @internal\n */\n releaseComponentHandle(handle: ComponentHandle): void {\n this.#components.release(handle);\n }\n\n /**\n * Removes a released entity from every index.\n *\n * @param entity - The entity the destroy flush has finished with.\n *\n * @internal\n */\n releaseEntity(entity: Entity): void {\n const internals = entityInternals(entity);\n this.#byUid.delete(internals.uid);\n this.#entities.release(internals.handle);\n if (internals.parent === null) {\n internals.scene.removeRoot(entity);\n }\n const tags = internals.tags;\n for (const tag of tags.values()) {\n this.#removeTag(entity, tag);\n }\n }\n\n /**\n * Creates a signal wired to the app's deferred queue.\n *\n * @typeParam T - The payload type.\n * @returns The signal.\n *\n * @internal\n */\n createSignal<T>(): Signal<T> {\n const queue = this.#deferredQueue;\n return queue === null ? new Signal<T>() : new Signal<T>({ deferredQueue: queue });\n }\n\n /**\n * Keeps the `findByTag` index current.\n *\n * @param entity - The entity whose tags changed.\n * @param tag - The tag.\n * @param added - `true` for an add.\n *\n * @internal\n */\n notifyTagChanged(entity: Entity, tag: string, added: boolean): void {\n if (added) {\n let bucket = this.#byTag.get(tag);\n if (bucket === undefined) {\n bucket = [];\n this.#byTag.set(tag, bucket);\n }\n if (!bucket.includes(entity)) {\n bucket.push(entity);\n }\n return;\n }\n this.#removeTag(entity, tag);\n }\n\n /**\n * Moves an entity and its subtree to another scene instance.\n *\n * @param entity - The entity that crossed a scene boundary.\n * @param scene - Its new owner.\n *\n * @internal\n */\n moveToScene(entity: Entity, scene: SceneInstance): void {\n const internals = entityInternals(entity);\n if (internals.scene === scene) {\n return;\n }\n if (internals.parent === null) {\n internals.scene.removeRoot(entity);\n scene.addRoot(entity);\n }\n internals.scene = scene;\n const children = internals.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n this.moveToScene(child, scene);\n }\n }\n }\n\n /**\n * Emits `onEntityCreated`.\n *\n * @param entity - The new entity.\n *\n * @internal\n */\n notifyEntityCreated(entity: Entity): void {\n this.#onEntityCreated.emit(entity);\n }\n\n /**\n * Emits `onEntityDestroyed`.\n *\n * @param entity - The released entity.\n *\n * @internal\n */\n notifyEntityDestroyed(entity: Entity): void {\n this.#onEntityDestroyed.emit(entity);\n }\n\n /**\n * Reports a caught failure through `app.onError`.\n *\n * @param report - What failed, and where.\n *\n * @internal\n */\n reportError(report: ErrorReport): void {\n this.#app.onError.emit(report);\n }\n\n /**\n * Removes an entity from one tag bucket.\n *\n * @param entity - The entity.\n * @param tag - The tag.\n */\n #removeTag(entity: Entity, tag: string): void {\n const bucket = this.#byTag.get(tag);\n if (bucket === undefined) {\n return;\n }\n const index = bucket.indexOf(entity);\n if (index >= 0) {\n // Swap-remove: `findByTag` promises a stable array identity, not a stable order.\n const last = bucket.length - 1;\n const moved = bucket[last];\n if (index !== last && moved !== undefined) {\n bucket[index] = moved;\n }\n bucket.pop();\n }\n }\n}\n\n/** Shared empty result for a tag nothing carries, so `findByTag` never allocates. */\nconst EMPTY_ENTITIES: readonly Entity[] = Object.freeze([]);\n\n/**\n * Babylon Lite objects a world owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3, `02-scene-graph.md` §2); excluded from the stability\n * guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport interface WorldLiteHandles {\n /** The Lite scene the world's entities are rendered from. */\n readonly scene: LiteScene;\n /**\n * The scene a physics extension steps its simulation in (`docs/architecture/09-physics.md` §1),\n * or `null` when no extension has set one.\n */\n readonly simulationScene: LiteScene | null;\n}\n\n/**\n * Options accepted by {@link World.createEntity}.\n *\n * @public\n */\nexport interface CreateEntityOptions {\n /** The parent to attach the new entity to; `undefined` makes it a root of its scene. */\n readonly parent?: Entity;\n /** The owning scene instance; defaults to the parent's scene, or `world.activeScene`. */\n readonly scene?: SceneInstance;\n /** The initial world position, in metres. */\n readonly position?: Vec3Like;\n /** The initial world rotation. */\n readonly rotation?: QuatLike;\n /**\n * The entity's own `active` flag at creation. Defaults to `true`.\n *\n * @remarks\n * Scene loading passes `false` so that no component can `awake` before the whole scene exists and\n * its references are resolved (`docs/architecture/01-lifecycle-and-time.md` §4), then sets the\n * file's value in tree order once construction is complete.\n */\n readonly active?: boolean;\n /**\n * The uid to adopt instead of a freshly minted ULID.\n *\n * @remarks\n * Scene loading passes the uid the file carries, which is what makes save → load → save\n * byte-identical (`docs/architecture/06-serialization-and-scene-format.md` §1). A uid another\n * entity of this world already holds is ignored and a fresh one minted, so two instances of one\n * scene never collide (`02-scene-graph.md` §10).\n */\n readonly uid?: string;\n}\n\n/**\n * How far a scene load has got, as `world.loadScene`'s `onProgress` reports it.\n *\n * @public\n */\nexport interface LoadProgress {\n /** The address being loaded. */\n readonly address: string;\n /** How far along, in `[0, 1]`, counting every dependency the scene pulls in. */\n readonly fraction: number;\n}\n\n/**\n * Options accepted by {@link World.loadScene} (`docs/architecture/02-scene-graph.md` §2).\n *\n * @public\n */\nexport interface LoadSceneOptions {\n /**\n * `\"single\"` (the default) unloads every instance that is not `persistent` first; `\"additive\"`\n * keeps them.\n */\n readonly mode?: \"single\" | \"additive\";\n /** Cancels the load; an abort after the asset arrived still rejects with `IGX-0502`. */\n readonly signal?: AbortSignal;\n /** Called as the scene and its dependencies load. */\n readonly onProgress?: (progress: LoadProgress) => void;\n /**\n * Makes the loaded instance `world.activeScene`. Defaults to `true` for a `\"single\"` load and\n * `false` for an additive one, which is what \"the level you just loaded owns new entities\" means.\n */\n readonly setActive?: boolean;\n /** `true` turns an `IGX-0604` instance hash mismatch from a logged warning into a throw. */\n readonly strictInstanceHashes?: boolean;\n}\n\n/**\n * Options accepted by {@link World.instantiate} and {@link World.instantiateAsync}\n * (`docs/architecture/02-scene-graph.md` §2).\n *\n * @public\n */\nexport interface InstantiateOptions {\n /** The parent to attach the instance root to; `null` or omitted makes it a root. */\n readonly parent?: Entity | null;\n /** The instance that owns the new entities; defaults to the parent's, else `world.activeScene`. */\n readonly scene?: SceneInstance;\n /** Renames the instance root. */\n readonly name?: string;\n /** Places the instance root. */\n readonly position?: Vec3Like;\n /** Rotates the instance root. */\n readonly rotation?: QuatLike;\n /** `true` reads `position`/`rotation` as world values; `false` (the default) as local ones. */\n readonly worldSpace?: boolean;\n /** `true` turns an `IGX-0604` instance hash mismatch from a logged warning into a throw. */\n readonly strictInstanceHashes?: boolean;\n}\n\n/**\n * Options accepted by `createWorld`.\n *\n * @internal\n */\nexport interface CreateWorldOptions {\n /** The app that owns the world. */\n readonly app: App;\n /** The Lite scene the world renders into. */\n readonly scene: LiteScene;\n /** The frame-state controller the scheduler owns. */\n readonly frameState: FrameStateController;\n /** The project's resolved layer names; an empty table when omitted. */\n readonly layers?: LayerTable;\n /** The component-class table; a fresh one when omitted. */\n readonly registry?: ComponentRegistry;\n /** The identifier factory; a crypto-seeded ULID factory when omitted. */\n readonly ulid?: () => string;\n /** The scheduler's `EndOfFrame` queue, so `{ deferred: true }` signal connections work. */\n readonly deferredQueue?: DeferredQueue;\n}\n\n/**\n * Creates the world of one app.\n *\n * @param options - The app, the Lite scene, the frame state, and the resolved settings.\n * @returns The world, with its implicit `\"default\"` scene instance already present.\n *\n * @example\n * ```ts\n * const frameState = createFrameState();\n * const world = createWorld({ app, scene, frameState, layers: createLayerTable(config.layers) });\n * ```\n *\n * @internal\n */\nexport function createWorld(options: CreateWorldOptions): World {\n return new World(options);\n}\n\n/**\n * The world's internal lifecycle API, for the scheduler.\n *\n * @param world - The world.\n * @returns The queues and flushes the frame function drives.\n *\n * @internal\n */\nexport function getWorldInternals(world: World): WorldInternals {\n return world.lifecycle;\n}\n\n/**\n * The frame state a world was built with, for the scheduler and for tests.\n *\n * @param world - The world.\n * @returns The read-only frame state.\n *\n * @internal\n */\nexport function getFrameState(world: World): FrameState {\n return world.frameState.state;\n}\n\n/**\n * Depth-first search for a named entity.\n *\n * @param entity - Where to start.\n * @param name - The name to match.\n * @returns The first match, or `null`.\n */\nfunction findNamed(entity: Entity, name: string): Entity | null {\n if (entity.name === name) {\n return entity;\n }\n const children = entityInternals(entity).children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child === undefined) {\n continue;\n }\n const found = findNamed(child, name);\n if (found !== null) {\n return found;\n }\n }\n return null;\n}\n\n/**\n * Depth-first collection of named entities.\n *\n * @param entity - Where to start.\n * @param name - The name to match.\n * @param out - Where matches are appended.\n */\nfunction collectNamed(entity: Entity, name: string, out: Entity[]): void {\n if (entity.name === name) {\n out.push(entity);\n }\n const children = entityInternals(entity).children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectNamed(child, name, out);\n }\n }\n}\n\n/**\n * How many roots a scene file declares.\n *\n * @param file - The file.\n * @returns The count of entities with no parent.\n */\nfunction countRoots(file: SceneFile): number {\n let count = 0;\n for (let index = 0; index < file.entities.length; index += 1) {\n if (file.entities[index]?.parent === null) {\n count += 1;\n }\n }\n return count;\n}\n\n/**\n * Applies an instantiate call's placement options to the instance root.\n *\n * @param root - The instance root.\n * @param options - The placement options.\n */\nfunction placeRoot(root: Entity, options?: InstantiateOptions): void {\n const worldSpace = options?.worldSpace === true;\n const position = options?.position;\n if (position !== undefined) {\n if (worldSpace) {\n root.transform.position = position;\n } else {\n root.transform.localPosition.set(position.x, position.y, position.z);\n }\n }\n const rotation = options?.rotation;\n if (rotation !== undefined) {\n if (worldSpace) {\n root.transform.rotation = rotation;\n } else {\n root.transform.localRotation.set(rotation.x, rotation.y, rotation.z, rotation.w);\n }\n }\n}\n\n/**\n * The single root of an instance built from a file that declares exactly one.\n *\n * @param roots - What the builder produced.\n * @returns The root.\n */\nfunction onlyRoot(roots: readonly Entity[]): Entity {\n // Boundary assertion (coding standards §5.2). The invariant: `instantiate` takes this path only\n // when `countRoots` said the file declares exactly one root, and the builder creates one entity\n // per file entity, so index 0 is always present. A container covers every other shape.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return roots[0] as Entity;\n}\n","import { Signal } from \"../signal/signal.js\";\nimport type { AppEvents, DeviceLostInfo } from \"./types.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\n\n/**\n * `app.events` (`docs/architecture/02-scene-graph.md` §8: \"Engine-wide events live on `app.events`\n * as typed signals\"). The world already emits `onSceneLoaded`/`onSceneUnloaded`; the app forwards\n * them so that a script does not have to know whether an event belongs to the world or to the\n * device, and so extensions can add their own through declaration merging.\n *\n * The three device signals are emitted by the rendering layer through the `@internal` `emit*`\n * methods (`07-rendering.md` §4). Keeping the emitters off the public {@link AppEvents} interface is\n * what makes `app.events` a read-only surface for game code.\n */\n\n/**\n * The engine-wide event table of one app.\n *\n * @internal\n */\nexport class AppEventsImpl implements AppEvents {\n /** Emitted after a scene instance and its entities exist. */\n readonly onSceneLoaded: Signal<SceneInstance>;\n\n /** Emitted just before a scene instance's entities are destroyed. */\n readonly onSceneUnloaded: Signal<SceneInstance>;\n\n /** Emitted when the WebGPU device was lost. */\n readonly onDeviceLost: Signal<DeviceLostInfo>;\n\n /** Emitted when the WebGPU device and its resources were rebuilt. */\n readonly onDeviceRecovered: Signal;\n\n /** Emitted when recovery failed and the app cannot render again. */\n readonly onDeviceRecoveryFailed: Signal<unknown>;\n\n /**\n * Creates the table.\n *\n * @param onHandlerError - Where a handler's exception goes; the app routes it to `app.onError` so\n * one listener throwing never stops the others (`02-scene-graph.md` §8).\n */\n constructor(onHandlerError: (error: unknown) => void) {\n this.onSceneLoaded = new Signal<SceneInstance>({ onHandlerError });\n this.onSceneUnloaded = new Signal<SceneInstance>({ onHandlerError });\n this.onDeviceLost = new Signal<DeviceLostInfo>({ onHandlerError });\n this.onDeviceRecovered = new Signal({ onHandlerError });\n this.onDeviceRecoveryFailed = new Signal<unknown>({ onHandlerError });\n }\n\n /**\n * Announces that the WebGPU device was lost.\n *\n * @param info - Lite's reason and message.\n */\n emitDeviceLost(info: DeviceLostInfo): void {\n this.onDeviceLost.emit(info);\n }\n\n /** Announces that the device and its resources were rebuilt. */\n emitDeviceRecovered(): void {\n this.onDeviceRecovered.emit();\n }\n\n /**\n * Announces that recovery failed.\n *\n * @param reason - Whatever the recovery path reported.\n */\n emitDeviceRecoveryFailed(reason: unknown): void {\n this.onDeviceRecoveryFailed.emit(reason);\n }\n\n /** Detaches every handler; the app calls it on disposal. */\n clear(): void {\n this.onSceneLoaded.clear();\n this.onSceneUnloaded.clear();\n this.onDeviceLost.clear();\n this.onDeviceRecovered.clear();\n this.onDeviceRecoveryFailed.clear();\n }\n}\n","import { AssetsImpl } from \"../assets/assets-service.js\";\nimport { ComponentRegistry } from \"../component/component-registry.js\";\nimport { componentInternals } from \"../component/internals.js\";\nimport { CoroutineHostImpl } from \"../coroutine/coroutine-host.js\";\nimport { Diagnostics } from \"../diagnostics/diagnostics.js\";\nimport { createErrorCodeRegistry } from \"../errors/error-code-registry.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { coreExtension } from \"../extension/core-extension.js\";\nimport { ExtensionHost } from \"../extension/host.js\";\nimport { ServiceRegistryImpl } from \"../extension/service-registry.js\";\nimport { createLayerTable } from \"../layers/layer-table.js\";\nimport { ScriptCallbackKind } from \"../lifecycle/callbacks.js\";\nimport { createFrameState } from \"../lifecycle/frame-state.js\";\nimport { createHeadlessEngine, createRenderEngine, disposeEngineHandles } from \"../lite/engine.js\";\nimport { enableSceneDeviceLossRecovery } from \"../lite/gpu/device-loss.js\";\nimport { registerFrameCallback, startEngineLoop, stopRenderLoop, unregisterFrameCallback } from \"../lite/loop.js\";\nimport { enableLiteErrorDecoding, toLiteEngineOptions } from \"../lite/render-diagnostics.js\";\nimport { applyRenderingFeatures, registerRenderScene } from \"../lite/render-features.js\";\nimport { createConsoleSink } from \"../log/console-sink.js\";\nimport { createLogger } from \"../log/logger.js\";\nimport { detectPlatform } from \"../platform/platform.js\";\nimport { RendererService, rendererInternals } from \"../render/renderer.js\";\nimport { toRendererOptions, toSurfaceFormat, RENDERING_SETTINGS_SECTION } from \"../render/rendering-settings.js\";\nimport { EndOfFrameQueue } from \"../scheduler/deferred-queue.js\";\nimport { Scheduler } from \"../scheduler/scheduler.js\";\nimport { SettingsStore } from \"../settings/settings-store.js\";\nimport { Signal } from \"../signal/signal.js\";\nimport { createPerformanceClock } from \"../time/clock.js\";\nimport { TimeImpl } from \"../time/time.js\";\nimport { createWorld } from \"../world/world.js\";\nimport { AppEventsImpl } from \"./events.js\";\nimport { PHASE_NAMES, Phase } from \"./types.js\";\nimport { VERSION } from \"./version.js\";\nimport type { App, AppLiteHandles, AppSettings, ErrorReport, Extension, System } from \"./types.js\";\nimport type { AssetManifest, AssetsSettings, FetchLike } from \"../assets/types.js\";\nimport type { ConcreteComponentType } from \"../component/component-type.js\";\nimport type { ErrorFormatMode } from \"../errors/ignifx-error.js\";\nimport type { ScriptCallbackKind as ScriptCallbackKindValue } from \"../lifecycle/callbacks.js\";\nimport type { EngineHandles } from \"../lite/engine.js\";\nimport type { FrameCallbackHandle } from \"../lite/loop.js\";\nimport type { LogSink, LogThreshold } from \"../log/log-level.js\";\nimport type { Logger } from \"../log/logger.js\";\nimport type { PlatformInfo } from \"../platform/platform.js\";\nimport type { RenderSurface } from \"../platform/webgpu.js\";\nimport type { Renderer } from \"../render/renderer.js\";\nimport type { RenderingSettings } from \"../render/rendering-settings.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\nimport type { Script } from \"../script/script.js\";\nimport type { SettingsInput } from \"../settings/settings-input.js\";\nimport type { Clock } from \"../time/clock.js\";\nimport type { World } from \"../world/world.js\";\n\n/**\n * `createApp` and the `App` implementation: the root object of a game\n * (`docs/architecture/00-overview.md` §1, `01-lifecycle-and-time.md` §1 and §8,\n * `04-extensions.md` §2). There are no globals — every engine service hangs off this object\n * (`CONSTITUTION.md` §3.6), and two apps in one process share nothing.\n *\n * Decisions the documents leave open:\n *\n * - **Settings are frozen before the engine is created**, not after. §2 rule 5 lists engine, world,\n * then freeze; freezing first is the same work in a better order, because a project that names an\n * unknown settings section then fails before a GPU device has been acquired.\n * - **`app.step(dt)` does not require `app.start()`.** §8's example starts first, and extensions'\n * `onStart` hooks may well be required for a meaningful frame, but nothing in §3 depends on the\n * loop having been started, and unit tests are much simpler when a bare `createApp` can be\n * stepped. What `step` does refuse is running while Babylon Lite's own loop is driving frames\n * (`IGX-0105`).\n * - **`stop()` may be followed by `start()`.** The frame callback is registered again and the\n * `onStart` hooks run again; nothing in §1 says otherwise, and a template that stops on\n * `visibilitychange` needs it.\n */\n\n/** Milliseconds in one second; the boundary the Lite callback's delta crosses. */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * The asset options {@link CreateAppOptions.assets} carries.\n *\n * @public\n */\nexport interface AssetsCreateOptions {\n /** The address-to-URL table. Defaults to an empty manifest rooted at the `assets` setting. */\n readonly manifest?: AssetManifest;\n /** The `fetch` every asset read goes through. Defaults to `globalThis.fetch`. */\n readonly fetch?: FetchLike;\n}\n\n/**\n * Options accepted by {@link createApp}.\n *\n * @example\n * ```ts\n * const app = await createApp({ canvas, extensions: [physics(), input()] });\n * await app.start();\n * ```\n *\n * @public\n */\nexport interface CreateAppOptions {\n /**\n * Run on Babylon Lite's null engine with no render surface\n * (`docs/architecture/01-lifecycle-and-time.md` §8). Defaults to `true` when no `canvas` is\n * given, so `createApp({})` is a headless app.\n */\n readonly headless?: boolean;\n /** The canvas to render into. Ignored when `headless` is `true`. */\n readonly canvas?: RenderSurface;\n /** The extensions to register, after the implicit core extension. */\n readonly extensions?: readonly Extension[];\n /**\n * Project settings, as `ignifx.config.ts` would supply them\n * (`docs/architecture/04-extensions.md` §5). The Vite plugin injects the resolved config in\n * Phase 2; tests and Electron tooling pass it here.\n */\n readonly settings?: SettingsInput;\n /**\n * The asset service's construction options\n * (`docs/architecture/05-assets-and-loading.md` §7). The manifest normally arrives from\n * `@ignifx/vite-plugin`; tests and Electron tooling pass it here.\n *\n * @remarks\n * The `assets` **settings** section configures the root, the concurrency limit, the collector\n * delay, and the retry count. The manifest and the injected `fetch` are not settings: neither\n * survives schema validation, so they are creation options instead.\n */\n readonly assets?: AssetsCreateOptions;\n /**\n * The `fetch` the asset service reads through, as a shorthand for `assets.fetch`. Defaults to\n * `globalThis.fetch`; headless tests pass a fake so responses are deterministic.\n */\n readonly fetch?: FetchLike;\n /**\n * The wall clock behind `time.realtimeSinceStartup` and the development phase timings. Defaults\n * to `performance.now()`; headless tests pass {@link createManualClock}.\n */\n readonly clock?: Clock;\n /**\n * `\"development\"` turns on per-phase CPU timings, full error messages, and the strict half of\n * every rule `04-extensions.md` §2 relaxes in production. Defaults to `\"development\"`; the Vite\n * plugin sets it from the build mode in Phase 2.\n */\n readonly mode?: ErrorFormatMode;\n /** Where `app.log` writes. Defaults to the console sink. */\n readonly logSink?: LogSink;\n /**\n * The lowest level `app.log` writes to the sink. Defaults to `\"info\"` in every mode, so an app\n * prints nothing at startup; pass `\"debug\"` to see the kernel's own diagnostics.\n */\n readonly logLevel?: LogThreshold;\n}\n\n/** The options after {@link createApp} has applied its defaults. */\ninterface ResolvedAppOptions {\n /** The canvas to render into, or `null` for a headless app. */\n readonly canvas: RenderSurface | null;\n /** Project settings. */\n readonly settings: SettingsInput;\n /** The address-to-URL table, or `null` to start from the empty manifest. */\n readonly manifest: AssetManifest | null;\n /** The injected `fetch`, or `null` to use the host's. */\n readonly fetch: FetchLike | null;\n /** The wall clock. */\n readonly clock: Clock;\n /** The build mode. */\n readonly mode: ErrorFormatMode;\n /** Where `app.log` writes. */\n readonly logSink: LogSink;\n readonly logLevel: LogThreshold;\n}\n\n/**\n * The root object of a game.\n *\n * @internal\n */\nclass AppImpl implements App {\n /** The clock. */\n readonly time: TimeImpl;\n\n /** The app-scoped logger. */\n readonly log: Logger;\n\n /** Per-frame counters and profiling scopes. */\n readonly diagnostics: Diagnostics;\n\n /** Services registered by extensions. */\n readonly services: ServiceRegistryImpl;\n\n /** Every failure the engine caught at a boundary rather than rethrowing. */\n readonly onError: Signal<ErrorReport>;\n\n /** Addressed, reference-counted asset loading. */\n readonly assets: AssetsImpl;\n\n /** Engine-wide events. */\n readonly events: AppEventsImpl;\n\n /** The coroutine scheduler. */\n readonly coroutines: CoroutineHostImpl;\n\n /** `true` when the app runs on Lite's null engine with no render surface. */\n readonly isHeadless: boolean;\n\n /** The `@ignifx/core` version this app was built from. */\n readonly version: string = VERSION;\n\n /** Where the app is running. */\n readonly platform: PlatformInfo;\n\n readonly #canvas: RenderSurface | null;\n\n readonly #clock: Clock;\n\n readonly #mode: ErrorFormatMode;\n\n readonly #frameState = createFrameState();\n\n readonly #registry = new ComponentRegistry();\n\n readonly #settings: SettingsStore;\n\n readonly #deferred: EndOfFrameQueue;\n\n readonly #scheduler: Scheduler;\n\n readonly #host: ExtensionHost;\n\n #world: World | null = null;\n\n #handles: EngineHandles | null = null;\n\n #frameCallback: FrameCallbackHandle | null = null;\n\n #deviceLoss: { disable(): void } | null = null;\n\n #isLoopRunning = false;\n\n #isRunning = false;\n\n #isDisposed = false;\n\n /**\n * Runs one ignifx frame from Babylon Lite's render loop.\n *\n * @param deltaMs - The frame delta Lite delivered, in milliseconds; the adapter boundary is where\n * it becomes ignifx's seconds (`docs/architecture/00-overview.md` §4).\n */\n readonly #onLiteFrame = (deltaMs: number): void => {\n this.#scheduler.runFrame(deltaMs / MILLISECONDS_PER_SECOND);\n };\n\n /** The document became hidden or visible. */\n readonly #onVisibilityChange = (): void => {\n this.#dispatchApplication(ScriptCallbackKind.onApplicationPause, globalThis.document.hidden);\n };\n\n /** The window gained focus. */\n readonly #onFocus = (): void => {\n this.#dispatchApplication(ScriptCallbackKind.onApplicationFocus, true);\n };\n\n /** The window lost focus. */\n readonly #onBlur = (): void => {\n this.#dispatchApplication(ScriptCallbackKind.onApplicationFocus, false);\n };\n\n /**\n * Builds an app. Call {@link createApp}, which also runs the asynchronous half of construction.\n *\n * @param options - The resolved creation options.\n */\n constructor(options: ResolvedAppOptions) {\n this.#canvas = options.canvas;\n this.#clock = options.clock;\n this.#mode = options.mode;\n this.isHeadless = options.canvas === null;\n this.platform = detectPlatform();\n const development = options.mode === \"development\";\n this.log = createLogger({ sink: options.logSink, level: options.logLevel });\n this.diagnostics = new Diagnostics({ development, now: (): number => this.#clock.nowMs() });\n this.time = new TimeImpl(options.clock);\n this.services = new ServiceRegistryImpl();\n this.#settings = new SettingsStore(options.settings, options.mode, this.log);\n this.onError = new Signal<ErrorReport>({\n onHandlerError: (error: unknown): void => {\n this.log.error(\"An app.onError handler threw.\", error);\n },\n });\n this.events = new AppEventsImpl((error: unknown): void => {\n this.log.error(\"An app.events handler threw.\", error);\n });\n this.assets = new AssetsImpl({\n app: this,\n diagnostics: this.diagnostics,\n ...(options.fetch === null ? {} : { fetch: options.fetch }),\n ...(options.manifest === null ? {} : { manifest: options.manifest }),\n });\n this.#deferred = new EndOfFrameQueue((error: unknown): void => {\n this.#report({ error, source: \"system\", phase: Phase.EndOfFrame, entity: null, component: null });\n });\n this.coroutines = new CoroutineHostImpl({\n frameState: this.#frameState,\n report: (error: unknown, owner: Script): void => {\n this.#report({\n error,\n source: \"coroutine\",\n phase: this.#scheduler.currentPhase,\n entity: componentInternals(owner).entity,\n component: owner,\n });\n },\n });\n this.#scheduler = new Scheduler({\n time: this.time,\n diagnostics: this.diagnostics,\n frameState: this.#frameState,\n coroutines: this.coroutines,\n deferred: this.#deferred,\n clock: options.clock,\n development,\n report: (error: unknown, system: System, phase: Phase): void => {\n this.log.error(\"The system {system} threw in {phase}.\", system.name, PHASE_NAMES[phase] ?? \"\", error);\n this.#report({ error, source: \"system\", phase, entity: null, component: null });\n },\n });\n this.#host = new ExtensionHost({\n app: this,\n log: this.log,\n registry: this.#registry,\n services: this.services,\n settings: this.#settings,\n errorCodes: createErrorCodeRegistry(),\n scheduler: this.#scheduler,\n version: VERSION,\n mode: options.mode,\n report: (report: ErrorReport): void => {\n this.#report(report);\n },\n });\n this.onError.connect((report: ErrorReport): void => {\n this.#logError(report);\n });\n }\n\n /**\n * The running simulation.\n *\n * @returns The world.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed, or `IGX-0107` when it\n * is read from inside an extension's `register` hook, before the world exists.\n */\n get world(): World {\n this.#assertUsable(\"app.world\");\n const world = this.#world;\n if (world === null) {\n throw new IgnifxError(CoreErrorCode.appNotReady, \"app.world is not available until createApp() resolves.\", {\n context: { member: \"app.world\" },\n hint: \"Extensions declare components and systems in register(); touch the world in onStart().\",\n });\n }\n return world;\n }\n\n /**\n * Surface sizing, material warm-up, GPU picking, screenshots, and the render diagnostics\n * (`docs/architecture/07-rendering.md` §1, §3, §5).\n *\n * @returns The rendering service.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed, or `IGX-0107` when it\n * is read from inside an extension's `register` hook, before the core extension has built it.\n */\n get renderer(): Renderer {\n this.#assertUsable(\"app.renderer\");\n const found = this.services.tryGet(RendererService);\n if (found === null) {\n throw new IgnifxError(CoreErrorCode.appNotReady, \"app.renderer is not available until createApp() resolves.\", {\n context: { member: \"app.renderer\" },\n hint: \"The core extension builds it from the rendering settings; touch it in onStart().\",\n });\n }\n return found;\n }\n\n /**\n * Resolved project settings.\n *\n * @returns The settings table.\n */\n get settings(): AppSettings {\n return this.#settings;\n }\n\n /**\n * `true` between `start()` and `stop()`/`dispose()`.\n *\n * @returns Whether the app is running.\n */\n get isRunning(): boolean {\n return this.#isRunning;\n }\n\n /**\n * Unstable Babylon Lite escape hatch (`docs/architecture/00-overview.md` §3).\n *\n * @returns The engine and the render scene.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed, or `IGX-0107` before\n * `createApp()` resolves.\n */\n get lite(): AppLiteHandles {\n this.#assertUsable(\"app.lite\");\n const handles = this.#handles;\n if (handles === null) {\n throw new IgnifxError(CoreErrorCode.appNotReady, \"app.lite is not available until createApp() resolves.\", {\n context: { member: \"app.lite\" },\n });\n }\n return handles;\n }\n\n /**\n * Makes component `typeId`s known to the serializer and the inspector.\n *\n * @param types - The component classes to register.\n * @throws IgnifxError with code `IGX-0203` when a `typeId` is already registered.\n */\n registerComponents(types: readonly ConcreteComponentType[]): void {\n this.#assertUsable(\"app.registerComponents()\");\n this.#registry.registerAll(types);\n }\n\n /**\n * Runs extension `onStart` hooks and starts the frame loop\n * (`docs/architecture/01-lifecycle-and-time.md` §1).\n *\n * @returns A promise that settles once the first frame has been submitted. In headless mode there\n * is no loop to start, so it settles once the hooks have run.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed.\n */\n\n async start(): Promise<void> {\n this.#assertUsable(\"app.start()\");\n if (this.#isRunning) {\n return;\n }\n await this.#host.start();\n this.#isRunning = true;\n this.#applicationListeners(true);\n const handles = this.#handles;\n if (this.isHeadless || handles === null) {\n return;\n }\n // §1: exactly one Lite before-render callback per world, registered after every extension has\n // finished register() — which `createApp` guarantees by resolving only once they have — and\n // before startEngine, so the ignifx frame sits at the front of the scene's callback list.\n if (this.#frameCallback !== null) {\n throw new IgnifxError(CoreErrorCode.appNotReady, \"app.start() already registered this world's frame callback.\", {\n context: { member: \"app.start()\" },\n });\n }\n await this.#registerRenderScene(handles);\n this.#frameCallback = registerFrameCallback(handles.scene, this.#onLiteFrame);\n this.#isLoopRunning = true;\n rendererInternals(this.renderer).setLoopRunning(true);\n await startEngineLoop(handles.engine);\n }\n\n /** Stops the frame loop without disposing anything, then runs `onStop` in reverse order. */\n stop(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#stopInternal();\n }\n\n /**\n * Stops the loop, disposes the world, the extensions, and the Lite objects, in the order of\n * `docs/architecture/07-rendering.md` §7. Disposing twice is a no-op.\n */\n dispose(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#stopInternal();\n // The world is disposed **before** the app is marked disposed: destroying an entity runs its\n // components' `onDetach`, and a render component's teardown reaches `app.renderer`, which\n // refuses to answer a disposed app (`IGX-0106`). Marking first would turn one teardown into a\n // cascade of caught failures.\n this.#world?.dispose();\n this.#isDisposed = true;\n this.#host.dispose();\n this.coroutines.dispose();\n this.#deferred.clear();\n this.#scheduler.dispose();\n this.#deviceLoss?.disable();\n this.#deviceLoss = null;\n this.services.clear();\n this.events.clear();\n const handles = this.#handles;\n if (handles !== null) {\n disposeEngineHandles(handles);\n }\n this.#handles = null;\n this.#world = null;\n }\n\n /**\n * Runs exactly one frame with a supplied delta — the headless driver\n * (`docs/architecture/01-lifecycle-and-time.md` §8).\n *\n * @param deltaSeconds - The raw frame delta in seconds, before the maximum-delta clamp.\n * @throws IgnifxError with code `IGX-0105` when Babylon Lite's render loop is driving the frames,\n * or `IGX-0106` when the app has been disposed.\n */\n step(deltaSeconds: number): void {\n this.#assertUsable(\"app.step()\");\n if (this.#isLoopRunning) {\n throw new IgnifxError(\n CoreErrorCode.stepOutsideHeadless,\n \"step() is only available in headless mode or while the render loop is stopped.\",\n { hint: \"Call app.stop() first, or create the app with { headless: true }.\" },\n );\n }\n this.#scheduler.runFrame(deltaSeconds);\n }\n\n /** Sets `time.paused` (`docs/architecture/01-lifecycle-and-time.md` §7). */\n pause(): void {\n this.time.paused = true;\n }\n\n /** Clears `time.paused`. */\n resume(): void {\n this.time.paused = false;\n }\n\n /**\n * The asynchronous half of construction: extensions register, the Lite engine and scene are\n * created, and the world is built (`docs/architecture/04-extensions.md` §2 rule 5).\n *\n * @param extensions - The game's extension list, after the implicit core extension.\n * @returns A promise that settles once the app is ready to start.\n */\n async initialize(extensions: readonly Extension[]): Promise<void> {\n const list: Extension[] = [coreExtension()];\n for (let index = 0; index < extensions.length; index += 1) {\n const extension = extensions[index];\n if (extension !== undefined) {\n list.push(extension);\n }\n }\n await this.#host.register(list);\n this.#settings.freeze();\n this.assets.applySettings(this.#settings.section<AssetsSettings>(\"assets\"));\n const rendering = this.#settings.section<RenderingSettings>(RENDERING_SETTINGS_SECTION);\n if (this.#mode === \"development\") {\n // §5: development builds decode Lite's numeric error codes to prose. It is process-global and\n // idempotent, and it needs no device, so it runs before the engine exists.\n enableLiteErrorDecoding();\n }\n const canvas = this.#canvas;\n const renderer = rendererInternals(this.renderer);\n this.#handles =\n canvas === null\n ? createHeadlessEngine()\n : await createRenderEngine(canvas, this.#engineOptions(rendering), {\n // §1.1: the render path is a frame-graph decision, so it is made when the scene is\n // created rather than in `start()` with the opt-ins that only change what is compiled.\n postProcessing: renderer.renderingFeatures.postProcessing,\n });\n this.assets.attachEngine(this.#handles.engine);\n renderer.attachHandles(this.#handles.engine, this.#handles.scene, this.#handles.presenter);\n this.#enableDeviceLossRecovery(rendering);\n const time = this.#settings.time;\n this.time.applySettings(time.fixedDeltaTime, time.maximumDeltaTime, time.timeScale);\n const world = createWorld({\n app: this,\n scene: this.#handles.scene,\n frameState: this.#frameState,\n layers: createLayerTable(this.#settings.layers.layers),\n registry: this.#registry,\n deferredQueue: this.#deferred,\n });\n this.#world = world;\n // `app.events` is the one place a script subscribes to engine-wide events\n // (`docs/architecture/02-scene-graph.md` §8); the world keeps its own signals and the app\n // forwards them, so neither surface has to know about the other.\n world.onSceneLoaded.connect((scene: SceneInstance): void => {\n this.events.onSceneLoaded.emit(scene);\n });\n world.onSceneUnloaded.connect((scene: SceneInstance): void => {\n this.events.onSceneUnloaded.emit(scene);\n });\n this.#scheduler.attachWorld(world);\n if (this.#mode === \"development\") {\n this.log.debug(`ignifx ${VERSION} ready with ${String(this.#host.extensions.length)} extensions.`);\n }\n }\n\n /**\n * Maps the `rendering` settings section onto the options `createEngine` takes.\n *\n * @param rendering - The resolved section.\n * @returns The engine and surface options.\n */\n #engineOptions(rendering: RenderingSettings): Record<string, unknown> {\n const options: Record<string, unknown> = {\n ...toLiteEngineOptions(toRendererOptions(rendering, 1), hostDevicePixelRatio()),\n };\n const format = toSurfaceFormat(rendering);\n if (format !== null) {\n options[\"format\"] = format;\n }\n return options;\n }\n\n /**\n * Turns on Babylon Lite's device-loss recovery and fans its callbacks out to `app.events`\n * (`docs/architecture/07-rendering.md` §4).\n *\n * @remarks\n * It runs immediately after the engine is created and before any resource exists, which is\n * Lite's requirement: the capture that stamps a *recovery source* onto a texture is installed by\n * this call, so a texture created earlier has nothing to rebuild from\n * (`src/lite/gpu/device-loss.ts`).\n *\n * @param rendering - The resolved section, for the `deviceLostRecovery` feature flag.\n */\n #enableDeviceLossRecovery(rendering: RenderingSettings): void {\n const handles = this.#handles;\n if (handles === null || handles.isHeadless || !rendering.features.deviceLostRecovery) {\n return;\n }\n this.#deviceLoss = enableSceneDeviceLossRecovery(handles.engine, {\n onLost: (info: GPUDeviceLostInfo): void => {\n this.events.emitDeviceLost({ reason: info.reason, message: info.message });\n },\n onRecovered: (): void => {\n this.events.emitDeviceRecovered();\n },\n onRecoveryFailed: (error: unknown): void => {\n this.events.emitDeviceRecoveryFailed(error);\n },\n });\n }\n\n /**\n * Applies the rendering feature opt-ins, warms the material families, and registers the render\n * scene — in the order `docs/architecture/07-rendering.md` §1.1 and ADR-0014 require.\n *\n * @param handles - The engine and scene.\n * @returns A promise that settles once the scene is registered.\n */\n async #registerRenderScene(handles: EngineHandles): Promise<void> {\n const renderer = rendererInternals(this.renderer);\n const features = renderer.renderingFeatures;\n await applyRenderingFeatures(handles.engine, handles.scene, features);\n // §1.1: what exists before `registerScene` is compiled by it. One reconciliation puts the\n // world's cameras, lights, and meshes into the Lite scene first, so a game that loaded its\n // scene before starting registers with its content — and the warm-up has lights to compile\n // against.\n const world = this.#world;\n if (world !== null) {\n renderer.syncBeforeRegister(world);\n }\n renderer.warmUpAtStart();\n await registerRenderScene(handles.scene, { shadows: features.shadows });\n renderer.markSceneRegistered();\n }\n\n /** Stops the Lite loop, detaches the browser listeners, and runs `onStop` in reverse order. */\n #stopInternal(): void {\n const handles = this.#handles;\n if (this.#isLoopRunning && handles !== null) {\n stopRenderLoop(handles.engine);\n rendererInternals(this.renderer).setLoopRunning(false);\n }\n this.#isLoopRunning = false;\n if (this.#frameCallback !== null) {\n unregisterFrameCallback(this.#frameCallback);\n this.#frameCallback = null;\n }\n this.#applicationListeners(false);\n if (!this.#isRunning) {\n return;\n }\n this.#isRunning = false;\n this.#host.stop();\n }\n\n /**\n * Attaches or detaches the document and window listeners behind `onApplicationPause` and\n * `onApplicationFocus` (`docs/architecture/01-lifecycle-and-time.md` §4, §7).\n *\n * @remarks\n * The host is re-checked rather than trusted from `platform.kind`, which was resolved when the\n * app was built: a window torn down before `dispose()` runs — an Electron window closing, an\n * iframe removed from its parent — must not turn teardown into a `TypeError`.\n *\n * @param attach - `true` to add the listeners, `false` to remove them.\n */\n #applicationListeners(attach: boolean): void {\n if (this.platform.kind !== \"browser\") {\n return;\n }\n if (!(\"document\" in globalThis) || !(\"window\" in globalThis)) {\n return;\n }\n const host = globalThis.document;\n const frame = globalThis.window;\n if (attach) {\n host.addEventListener(\"visibilitychange\", this.#onVisibilityChange);\n frame.addEventListener(\"focus\", this.#onFocus);\n frame.addEventListener(\"blur\", this.#onBlur);\n return;\n }\n host.removeEventListener(\"visibilitychange\", this.#onVisibilityChange);\n frame.removeEventListener(\"focus\", this.#onFocus);\n frame.removeEventListener(\"blur\", this.#onBlur);\n }\n\n /**\n * Delivers an application callback to every script implementing it\n * (`docs/architecture/01-lifecycle-and-time.md` §4).\n *\n * @param kind - `onApplicationPause` or `onApplicationFocus`.\n * @param value - The boolean the callback receives.\n */\n #dispatchApplication(kind: ScriptCallbackKindValue, value: boolean): void {\n const world = this.#world;\n if (world === null) {\n return;\n }\n const internals = world.lifecycle;\n // One closure per document event, not per frame: `visibilitychange` and window focus fire on\n // human timescales, so coding standards §7's no-closures rule does not reach here.\n internals.forEachScript(kind, (script: Script): void => {\n internals.invokeCallback(script, kind, value);\n });\n }\n\n /**\n * Emits an error report.\n *\n * @param report - What failed, and where.\n */\n #report(report: ErrorReport): void {\n this.onError.emit(report);\n }\n\n /**\n * The default `onError` handler: one log line naming the boundary, the phase, and the object\n * (`docs/architecture/15-devtools-and-diagnostics.md` §1). The development overlay is\n * `@ignifx/devtools`' job, not the kernel's.\n *\n * @param report - What failed, and where.\n */\n #logError(report: ErrorReport): void {\n const phase = report.phase === null ? \"no phase\" : (PHASE_NAMES[report.phase] ?? \"no phase\");\n const entity = report.entity === null ? \"-\" : report.entity.name;\n const component = report.component === null ? \"-\" : report.component.constructor.name;\n this.log.error(\n \"A {source} boundary caught a failure in {phase} on {entity}/{component}.\",\n report.source,\n phase,\n entity,\n component,\n report.error,\n );\n }\n\n /**\n * Refuses to serve a disposed app.\n *\n * @param member - What was being reached, for the message.\n * @throws IgnifxError with code `IGX-0106` when the app has been disposed.\n */\n #assertUsable(member: string): void {\n if (this.#isDisposed) {\n throw new IgnifxError(CoreErrorCode.appDisposed, `The app has been disposed; ${member} is no longer available.`, {\n context: { member },\n hint: \"Create a new app; a disposed one releases its world, its extensions, and its engine.\",\n });\n }\n }\n}\n\n/**\n * The host's device pixel ratio, or `1` on a host that has no `window` — a worker, or Node.\n *\n * @returns The ratio.\n */\nfunction hostDevicePixelRatio(): number {\n return \"devicePixelRatio\" in globalThis ? globalThis.devicePixelRatio : 1;\n}\n\n/**\n * Creates a game (`docs/architecture/00-overview.md` §1, `04-extensions.md` §2).\n *\n * @remarks\n * The whole of construction happens here: the extension list is built, sorted, and validated, every\n * `register` hook runs in order, the Lite engine and scene are created, the project settings are\n * frozen, and the world is built. Nothing runs a frame until `app.start()` (browser) or\n * `app.step(dt)` (headless).\n *\n * @param options - The canvas or `headless`, the extensions, the project settings, and the clock.\n * @returns The app, ready to start.\n * @throws IgnifxError with the `IGX-04xx` codes of `04-extensions.md` §2 when the extension list\n * does not validate, `IGX-0408`/`IGX-0407` when the project settings do not, and `IGX-0701` when a\n * canvas was given but the host has no WebGPU.\n *\n * @example\n * ```ts\n * const app = await createApp({ headless: true, clock: createManualClock() });\n * const player = app.world.createEntity(\"Player\");\n * player.addComponent(Mover);\n * app.step(1 / 60);\n * app.dispose();\n * ```\n *\n * @public\n */\nexport async function createApp(options: CreateAppOptions = {}): Promise<App> {\n const wantsHeadless = options.headless ?? options.canvas === undefined;\n const canvas = wantsHeadless ? null : (options.canvas ?? null);\n const app = new AppImpl({\n canvas,\n settings: options.settings ?? {},\n manifest: options.assets?.manifest ?? null,\n fetch: options.assets?.fetch ?? options.fetch ?? null,\n clock: options.clock ?? createPerformanceClock(),\n mode: options.mode ?? \"development\",\n logSink: options.logSink ?? createConsoleSink(),\n logLevel: options.logLevel ?? \"info\",\n });\n await app.initialize(options.extensions ?? []);\n return app;\n}\n","import type { LogRecord, LogSink } from \"./log-level.js\";\n\n/**\n * A {@link LogSink} that keeps the most recent records in a fixed-size ring buffer. Used by the\n * devtools console panel, which needs scrollback without unbounded growth, and by unit tests, which\n * assert on what was logged.\n *\n * @public\n */\nexport interface MemorySink extends LogSink {\n /** The maximum number of records retained. */\n readonly limit: number;\n /** How many records are currently retained, never more than {@link MemorySink.limit}. */\n readonly length: number;\n\n /**\n * Reads one retained record without copying the buffer.\n *\n * @param index - `0` is the oldest retained record, `length - 1` the newest.\n * @returns The record, or `null` when the index is out of range.\n */\n at(index: number): LogRecord | null;\n\n /**\n * Copies the retained records, oldest first.\n *\n * @returns A new array; allocating here is fine because only tests and devtools call it.\n */\n toArray(): readonly LogRecord[];\n\n /** Drops every retained record. */\n clear(): void;\n}\n\n/**\n * How many records {@link createMemorySink} keeps when no limit is given.\n *\n * @public\n */\nexport const DEFAULT_MEMORY_SINK_LIMIT = 200;\n\nclass MemorySinkImpl implements MemorySink {\n readonly limit: number;\n readonly #records: (LogRecord | null)[];\n #head = 0;\n #count = 0;\n\n constructor(limit: number) {\n this.limit = Math.max(1, Math.floor(limit));\n this.#records = Array.from<LogRecord | null>({ length: this.limit }).fill(null);\n }\n\n get length(): number {\n return this.#count;\n }\n\n write(record: LogRecord): void {\n this.#records[this.#head] = record;\n this.#head = (this.#head + 1) % this.limit;\n if (this.#count < this.limit) {\n this.#count += 1;\n }\n }\n\n at(index: number): LogRecord | null {\n if (index < 0 || index >= this.#count) {\n return null;\n }\n const oldest = (this.#head - this.#count + this.limit) % this.limit;\n return this.#records[(oldest + index) % this.limit] ?? null;\n }\n\n toArray(): readonly LogRecord[] {\n const out: LogRecord[] = [];\n for (let index = 0; index < this.#count; index += 1) {\n const record = this.at(index);\n if (record !== null) {\n out.push(record);\n }\n }\n return out;\n }\n\n clear(): void {\n this.#records.fill(null);\n this.#head = 0;\n this.#count = 0;\n }\n}\n\n/**\n * Creates an in-memory ring-buffer sink.\n *\n * @param limit - How many records to retain. Defaults to {@link DEFAULT_MEMORY_SINK_LIMIT}; values\n * below one are clamped to one.\n * @returns The sink, with the retained records readable through {@link MemorySink.at}.\n *\n * @example\n * ```ts\n * const sink = createMemorySink(4);\n * const log = createLogger({ sink, now: () => 0 });\n * log.warn(\"no atlas\");\n * sink.at(0)?.level; // \"warn\"\n * ```\n *\n * @public\n */\nexport function createMemorySink(limit: number = DEFAULT_MEMORY_SINK_LIMIT): MemorySink {\n return new MemorySinkImpl(limit);\n}\n","import { EPSILON, lerp } from \"./math-utils.js\";\nimport type { MutableVec4, Vec4Like } from \"./types.js\";\n\n/**\n * A 4-component vector: homogeneous coordinates, a tangent with a handedness sign, or any packed\n * quadruple headed for a shader. Rotations use {@link Quat}, not this type.\n *\n * Instance methods mutate the receiver and return `this`; `ToRef` statics write into a final `out`\n * argument and allocate nothing; the remaining statics allocate and say so.\n *\n * @example\n * ```ts\n * const tangent = new Vec4(1, 0, 0, -1);\n * tangent.toArray(vertexBuffer, offset);\n * ```\n *\n * @public\n */\nexport class Vec4 {\n /** The X component. */\n x: number;\n /** The Y component. */\n y: number;\n /** The Z component. */\n z: number;\n /** The W component. */\n w: number;\n\n /**\n * Creates a vector.\n *\n * @param x - The X component. Defaults to 0.\n * @param y - The Y component. Defaults to 0.\n * @param z - The Z component. Defaults to 0.\n * @param w - The W component. Defaults to 0.\n */\n constructor(x: number = 0, y: number = 0, z: number = 0, w: number = 0) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n\n /**\n * Assigns every component at once.\n *\n * @param x - The new X component.\n * @param y - The new Y component.\n * @param z - The new Z component.\n * @param w - The new W component.\n * @returns This vector.\n */\n set(x: number, y: number, z: number, w: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n }\n\n /**\n * Copies every component from another vector.\n *\n * @param v - The vector to read.\n * @returns This vector.\n */\n copyFrom(v: Vec4Like): this {\n this.x = v.x;\n this.y = v.y;\n this.z = v.z;\n this.w = v.w;\n return this;\n }\n\n /**\n * Copies this vector into a new one.\n *\n * @returns A new vector. **Allocates.**\n */\n clone(): Vec4 {\n return new Vec4(this.x, this.y, this.z, this.w);\n }\n\n /**\n * Adds another vector to this one.\n *\n * @param v - The vector to add.\n * @returns This vector.\n */\n add(v: Vec4Like): this {\n this.x += v.x;\n this.y += v.y;\n this.z += v.z;\n this.w += v.w;\n return this;\n }\n\n /**\n * Subtracts another vector from this one.\n *\n * @param v - The vector to subtract.\n * @returns This vector.\n */\n subtract(v: Vec4Like): this {\n this.x -= v.x;\n this.y -= v.y;\n this.z -= v.z;\n this.w -= v.w;\n return this;\n }\n\n /**\n * Multiplies this vector by another component by component.\n *\n * @param v - The vector to multiply by.\n * @returns This vector.\n */\n multiply(v: Vec4Like): this {\n this.x *= v.x;\n this.y *= v.y;\n this.z *= v.z;\n this.w *= v.w;\n return this;\n }\n\n /**\n * Multiplies every component by a number.\n *\n * @param scale - The factor.\n * @returns This vector.\n */\n scale(scale: number): this {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n this.w *= scale;\n return this;\n }\n\n /**\n * Flips every component's sign.\n *\n * @returns This vector.\n */\n negate(): this {\n this.x = -this.x;\n this.y = -this.y;\n this.z = -this.z;\n this.w = -this.w;\n return this;\n }\n\n /**\n * Scales this vector to unit length; a zero-length vector is left at zero rather than becoming\n * `NaN`.\n *\n * @returns This vector.\n */\n normalize(): this {\n const length = Math.hypot(this.x, this.y, this.z, this.w);\n if (length === 0) {\n return this;\n }\n return this.scale(1 / length);\n }\n\n /**\n * Moves this vector towards a target by an interpolant.\n *\n * @param target - The vector reached at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns This vector.\n */\n lerp(target: Vec4Like, t: number): this {\n return Vec4.lerpToRef(this, target, t, this);\n }\n\n /**\n * The dot product of this vector with another.\n *\n * @param v - The other vector.\n * @returns The dot product.\n */\n dot(v: Vec4Like): number {\n return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;\n }\n\n /**\n * The length of this vector.\n *\n * @returns The length.\n */\n length(): number {\n return Math.hypot(this.x, this.y, this.z, this.w);\n }\n\n /**\n * The squared length of this vector.\n *\n * @returns The squared length.\n */\n lengthSquared(): number {\n return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;\n }\n\n /**\n * Compares this vector with another, component by component, with a tolerance.\n *\n * @param v - The vector to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(v: Vec4Like, epsilon: number = EPSILON): boolean {\n return Vec4.equalsWithEpsilon(this, v, epsilon);\n }\n\n /**\n * Writes this vector into a `Float32Array`, for GPU upload. The output comes first to mirror\n * Babylon Lite's `toArray` helpers.\n *\n * @param out - The array to write into.\n * @param offset - The index of the X component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.x;\n out[offset + 1] = this.y;\n out[offset + 2] = this.z;\n out[offset + 3] = this.w;\n return out;\n }\n\n /**\n * The zero vector.\n *\n * @returns A new `(0, 0, 0, 0)`. **Allocates.**\n */\n static zero(): Vec4 {\n return new Vec4(0, 0, 0, 0);\n }\n\n /**\n * The vector whose components are all one.\n *\n * @returns A new `(1, 1, 1, 1)`. **Allocates.**\n */\n static one(): Vec4 {\n return new Vec4(1, 1, 1, 1);\n }\n\n /**\n * Copies any vector-shaped value into a `Vec4`.\n *\n * @param v - The vector to copy.\n * @returns A new vector. **Allocates.**\n */\n static from(v: Vec4Like): Vec4 {\n return new Vec4(v.x, v.y, v.z, v.w);\n }\n\n /**\n * Adds two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns A new vector. **Allocates.**\n */\n static add(a: Vec4Like, b: Vec4Like): Vec4 {\n return Vec4.addToRef(a, b, new Vec4());\n }\n\n /**\n * Subtracts one vector from another.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @returns A new vector holding `a - b`. **Allocates.**\n */\n static subtract(a: Vec4Like, b: Vec4Like): Vec4 {\n return Vec4.subtractToRef(a, b, new Vec4());\n }\n\n /**\n * Multiplies a vector by a number.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @returns A new vector. **Allocates.**\n */\n static scale(v: Vec4Like, scale: number): Vec4 {\n return Vec4.scaleToRef(v, scale, new Vec4());\n }\n\n /**\n * A unit-length copy of a vector.\n *\n * @param v - The vector to normalize.\n * @returns A new vector. **Allocates.**\n */\n static normalize(v: Vec4Like): Vec4 {\n return Vec4.normalizeToRef(v, new Vec4());\n }\n\n /**\n * Linearly interpolates between two vectors.\n *\n * @param a - The vector returned at `t === 0`.\n * @param b - The vector returned at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns A new vector. **Allocates.**\n */\n static lerp(a: Vec4Like, b: Vec4Like, t: number): Vec4 {\n return Vec4.lerpToRef(a, b, t, new Vec4());\n }\n\n /**\n * Writes `a + b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static addToRef<TOut extends MutableVec4>(a: Vec4Like, b: Vec4Like, out: TOut): TOut {\n out.set(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);\n return out;\n }\n\n /**\n * Writes `a - b` into `out`.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static subtractToRef<TOut extends MutableVec4>(a: Vec4Like, b: Vec4Like, out: TOut): TOut {\n out.set(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);\n return out;\n }\n\n /**\n * Writes the component-wise product `a * b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends MutableVec4>(a: Vec4Like, b: Vec4Like, out: TOut): TOut {\n out.set(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);\n return out;\n }\n\n /**\n * Writes `v * scale` into `out`.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static scaleToRef<TOut extends MutableVec4>(v: Vec4Like, scale: number, out: TOut): TOut {\n out.set(v.x * scale, v.y * scale, v.z * scale, v.w * scale);\n return out;\n }\n\n /**\n * Writes `-v` into `out`.\n *\n * @param v - The vector to flip.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static negateToRef<TOut extends MutableVec4>(v: Vec4Like, out: TOut): TOut {\n out.set(-v.x, -v.y, -v.z, -v.w);\n return out;\n }\n\n /**\n * Writes a unit-length copy of `v` into `out`; a zero-length input is written as zero.\n *\n * @param v - The vector to normalize.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static normalizeToRef<TOut extends MutableVec4>(v: Vec4Like, out: TOut): TOut {\n const length = Math.hypot(v.x, v.y, v.z, v.w);\n if (length === 0) {\n out.set(0, 0, 0, 0);\n return out;\n }\n const inv = 1 / length;\n out.set(v.x * inv, v.y * inv, v.z * inv, v.w * inv);\n return out;\n }\n\n /**\n * Writes the interpolation of `a` and `b` into `out`.\n *\n * @param a - The vector written at `t === 0`.\n * @param b - The vector written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static lerpToRef<TOut extends MutableVec4>(a: Vec4Like, b: Vec4Like, t: number, out: TOut): TOut {\n out.set(lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t), lerp(a.w, b.w, t));\n return out;\n }\n\n /**\n * The dot product of two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The dot product.\n */\n static dot(a: Vec4Like, b: Vec4Like): number {\n return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;\n }\n\n /**\n * The length of a vector.\n *\n * @param v - The vector to measure.\n * @returns The length.\n */\n static length(v: Vec4Like): number {\n return Math.hypot(v.x, v.y, v.z, v.w);\n }\n\n /**\n * The squared length of a vector.\n *\n * @param v - The vector to measure.\n * @returns The squared length.\n */\n static lengthSquared(v: Vec4Like): number {\n return v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w;\n }\n\n /**\n * Compares two vectors component by component, with a tolerance.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: Vec4Like, b: Vec4Like, epsilon: number = EPSILON): boolean {\n return (\n Math.abs(a.x - b.x) <= epsilon &&\n Math.abs(a.y - b.y) <= epsilon &&\n Math.abs(a.z - b.z) <= epsilon &&\n Math.abs(a.w - b.w) <= epsilon\n );\n }\n}\n","import { describeSchema } from \"../schema/describe.js\";\nimport { describeSceneFileFormat } from \"../serialization/scene-file.js\";\nimport { Camera } from \"./camera.js\";\nimport { ENVIRONMENT_FILE_FORMAT, ENVIRONMENT_FORMAT_VERSION } from \"./environment-asset.js\";\nimport { Environment } from \"./environment.js\";\nimport { Light } from \"./light.js\";\nimport {\n MATERIAL_ALPHA_MODE_NAMES,\n MATERIAL_FILE_FORMAT,\n MATERIAL_FORMAT_VERSION,\n MATERIAL_KINDS,\n} from \"./material-asset.js\";\nimport { MeshRenderer } from \"./mesh-renderer.js\";\nimport { Model } from \"./model.js\";\nimport { PostProcessStack } from \"./post-process-stack.js\";\nimport type { SchemaDescription } from \"../schema/describe.js\";\n\n/**\n * The documentation harness's view of everything `@ignifx/core` declares\n * (`scripts/README.md`, \"Schema discovery convention\";\n * `docs/architecture/16-docs-harness-and-skill.md` §3).\n *\n * `pnpm docs:schemas` imports the built entry point, calls {@link describeSchemas}, and turns the\n * result into `references/formats/<format>.md` and `ignifx.schemas.json`. The **function** form is\n * what a package uses rather than a `schemas` object, because building the record means calling\n * `describeSchema` for every component and module scope holds declarations only\n * (`CONSTITUTION.md` §3.5).\n *\n * ## Two corrections to the convention\n *\n * The harness requires every key to be a namespaced `<package>/<Name>` type id\n * (`scripts/lib/schema-source.ts` rejects a key with no `/`), and it groups entries onto a page by\n * their `format`. A *file* format is not a component and has no type id, so the three file formats\n * below are keyed `ignifx/scene-file`, `ignifx/material-file`, and `ignifx/environment-file` while\n * declaring `format: \"ignifx.scene\"`, `\"ignifx.material\"`, and `\"ignifx.environment\"`. The wave-1\n * hand-off asked for the key `\"ignifx.scene\"`; that key fails the namespacing check, and the\n * grouping — which is what actually decides the page — comes from `format` either way.\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 * const schemas = describeSchemas();\n * schemas[\"ignifx/Camera\"].fields[\"fov\"].default; // 60\n * ```\n *\n * @public\n */\nexport function describeSchemas(): Readonly<Record<string, SchemaDescription>> {\n return {\n \"ignifx/Camera\": describeSchema(\"ignifx/Camera\", Camera.schema, {\n description: \"The camera an entity renders the world through; the entity's transform is the view.\",\n }),\n \"ignifx/Light\": describeSchema(\"ignifx/Light\", Light.schema, {\n description: \"A directional, point, spot, or hemispheric light, with optional shadow casting.\",\n }),\n \"ignifx/MeshRenderer\": describeSchema(\"ignifx/MeshRenderer\", MeshRenderer.schema, {\n description: \"Draws one clone of a mesh asset with a material.\",\n }),\n \"ignifx/Model\": describeSchema(\"ignifx/Model\", Model.schema, {\n description: \"One instance of a loaded glTF, cloned under the entity's node.\",\n }),\n \"ignifx/Environment\": describeSchema(\"ignifx/Environment\", Environment.schema, {\n description: \"The world's image-based lighting, skybox, fog, image processing, and clear colour.\",\n }),\n \"ignifx/PostProcessStack\": describeSchema(\"ignifx/PostProcessStack\", PostProcessStack.schema, {\n description: \"Bloom, SMAA, and image processing, inserted into the scene's frame graph.\",\n }),\n \"ignifx/scene-file\": describeSceneFileFormat(),\n \"ignifx/material-file\": describeMaterialFileFormat(),\n \"ignifx/environment-file\": describeEnvironmentFileFormat(),\n };\n}\n\n/**\n * Describes the `ignifx.material` file format\n * (`docs/architecture/06-serialization-and-scene-format.md` §6, `07-rendering.md` §2.6).\n *\n * @returns The description of the top-level file fields.\n *\n * @public\n */\nexport function describeMaterialFileFormat(): SchemaDescription {\n return {\n title: \"Material file\",\n format: MATERIAL_FILE_FORMAT,\n description:\n 'A PBR or Standard material: colours in sRGB, factors unitless, textures as { \"$asset\": … } references.',\n fields: {\n format: { kind: \"str\", default: MATERIAL_FILE_FORMAT, description: `Always \"${MATERIAL_FILE_FORMAT}\".` },\n formatVersion: {\n kind: \"u32\",\n default: MATERIAL_FORMAT_VERSION,\n description: \"The file format version; 1 before ignifx 1.0.\",\n },\n type: {\n kind: \"enum\",\n default: \"pbr\",\n description: `The material family: ${MATERIAL_KINDS.join(\", \")}. \"shader\" arrives in Phase 7.`,\n },\n name: { kind: \"str\", default: \"\", description: \"A human-readable name; glTF overrides match on it.\" },\n baseColor: { kind: \"color\", default: [1, 1, 1, 1], description: \"PBR: sRGB base colour and alpha.\" },\n metallic: { kind: \"f32\", default: 1, description: \"PBR: metallic factor, 0 to 1.\" },\n roughness: { kind: \"f32\", default: 1, description: \"PBR: roughness factor, 0 to 1.\" },\n normalScale: { kind: \"f32\", default: 1, description: \"PBR: normal map strength.\" },\n emissive: { kind: \"color\", default: [0, 0, 0, 1], description: \"sRGB emissive colour.\" },\n occlusionStrength: { kind: \"f32\", default: 1, description: \"PBR: how strongly occlusion darkens.\" },\n alphaMode: {\n kind: \"enum\",\n default: \"opaque\",\n description: `How alpha is read: ${MATERIAL_ALPHA_MODE_NAMES.join(\", \")}.`,\n },\n alphaCutoff: { kind: \"f32\", default: 0.5, description: 'The cutoff a \"mask\" material discards below.' },\n alpha: { kind: \"f32\", default: 1, description: \"Overall material alpha, 0 to 1.\" },\n doubleSided: { kind: \"bool\", default: false, description: \"Whether back faces are drawn.\" },\n unlit: { kind: \"bool\", default: false, description: \"Whether lighting is skipped entirely.\" },\n environmentIntensity: { kind: \"f32\", default: 1, description: \"PBR: environment map contribution.\" },\n diffuse: { kind: \"color\", default: [1, 1, 1, 1], description: \"Standard: sRGB diffuse colour.\" },\n specular: { kind: \"color\", default: [1, 1, 1, 1], description: \"Standard: sRGB specular colour.\" },\n specularPower: { kind: \"f32\", default: 64, description: \"Standard: specular exponent.\" },\n baseColorTexture: { kind: \"asset\", default: null, description: \"PBR: the base colour map (sRGB).\" },\n metallicRoughnessTexture: { kind: \"asset\", default: null, description: \"PBR: the packed ORM map.\" },\n normalTexture: { kind: \"asset\", default: null, description: \"The tangent-space normal map.\" },\n emissiveTexture: { kind: \"asset\", default: null, description: \"The emissive map (sRGB).\" },\n occlusionTexture: { kind: \"asset\", default: null, description: \"PBR: a separate occlusion map.\" },\n diffuseTexture: { kind: \"asset\", default: null, description: \"Standard: the diffuse map (sRGB).\" },\n specularTexture: { kind: \"asset\", default: null, description: \"Standard: the specular map.\" },\n opacityTexture: { kind: \"asset\", default: null, description: \"Standard: the opacity map.\" },\n },\n };\n}\n\n/**\n * Describes the `ignifx.environment` file format\n * (`docs/architecture/06-serialization-and-scene-format.md` §6, `07-rendering.md` §2.5).\n *\n * @returns The description of the top-level file fields.\n *\n * @public\n */\nexport function describeEnvironmentFileFormat(): SchemaDescription {\n return {\n title: \"Environment file\",\n format: ENVIRONMENT_FILE_FORMAT,\n description: \"An image-based lighting environment, its BRDF lookup table, and its skybox.\",\n fields: {\n format: { kind: \"str\", default: ENVIRONMENT_FILE_FORMAT, description: `Always \"${ENVIRONMENT_FILE_FORMAT}\".` },\n formatVersion: {\n kind: \"u32\",\n default: ENVIRONMENT_FORMAT_VERSION,\n description: \"The file format version; 1 before ignifx 1.0.\",\n },\n environment: { kind: \"str\", default: \"\", description: \"The .env address holding the prefiltered cube map.\" },\n brdfLut: { kind: \"str\", default: \"\", description: \"The RGBD BRDF table; empty takes rendering.brdfLut.\" },\n skybox: { kind: \"str\", default: \"\", description: \"A .dds or .env skybox address; empty for none.\" },\n skyboxSize: { kind: \"f32\", default: 20, description: \"The skybox cube's size, in metres.\" },\n skyboxEnabled: { kind: \"bool\", default: true, description: \"Whether a skybox is drawn at all.\" },\n blur: { kind: \"f32\", default: 0, description: \"How blurred the specular reflection is, 0 to 1.\" },\n rotation: { kind: \"f32\", default: 0, description: \"Rotation around world Y, in degrees.\" },\n },\n };\n}\n","import { VERSION } from \"../app/version.js\";\nimport { entityInternals } from \"../entity/internals.js\";\nimport { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { canonicalizeNumber, encodeProps, encodeValue } from \"../schema/encode.js\";\nimport { SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION } from \"./scene-file.js\";\nimport { membershipEncoder } from \"./uid-remap.js\";\nimport type { SceneAsset } from \"./scene-asset.js\";\nimport type {\n SceneFile,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileInstance,\n SceneFileOverride,\n SceneFileTransform,\n} from \"./scene-file.js\";\nimport type { Component } from \"../component/component.js\";\nimport type { Entity } from \"../entity/entity.js\";\nimport type { EntityOrigin } from \"../entity/internals.js\";\nimport type { SceneInstance } from \"../scene/scene-instance.js\";\nimport type { ReferenceEncoder } from \"../schema/encode.js\";\nimport type { SchemaIssue } from \"../schema/issues.js\";\nimport type { JsonObject, JsonValue } from \"../schema/json.js\";\nimport type { Schema } from \"../schema/types.js\";\nimport type { Transform } from \"../transform/transform.js\";\n\n/**\n * One problem found while writing a file. Serialization is total — it always produces valid JSON —\n * so a problem means one value was written as `null` or one link was dropped, never that the save\n * failed (`docs/architecture/06-serialization-and-scene-format.md` §3).\n *\n * @public\n */\nexport interface SerializeIssue {\n /** The diagnostic code, for example `IGX-0602`. */\n readonly code: string;\n /** The actionable sentence. */\n readonly message: string;\n}\n\n/**\n * Options accepted by {@link serializeScene}.\n *\n * @public\n */\nexport interface SerializeSceneOptions {\n /**\n * `true` writes every entity of an instanced subtree as a plain entity instead of one `instance`\n * entry with computed overrides (`docs/architecture/06-serialization-and-scene-format.md` §5).\n * Flattened files no longer track the prefab and their uids are the runtime ones, which differ\n * per load.\n */\n readonly flatten?: boolean;\n /** Overrides the file's `name`; defaults to the instance's name, or `\"scene\"`. */\n readonly name?: string;\n /** Overrides the file's `settings` block; defaults to the instance's. */\n readonly settings?: JsonObject | null;\n /** Overrides the recorded `engineVersion`; `null` omits it, which is what byte-stable tests use. */\n readonly engineVersion?: string | null;\n /** Receives every problem found, in discovery order. */\n readonly onIssue?: (issue: SerializeIssue) => void;\n}\n\n/**\n * Writes a scene instance, or a set of entities, as a scene file object\n * (`docs/architecture/06-serialization-and-scene-format.md` §5).\n *\n * @remarks\n * Everything about the output is fixed so that two saves of the same state are byte-identical:\n * entities appear in tree order, object keys in the canonical order of §1, numbers rounded by\n * {@link canonicalizeNumber}, props in their schema's declaration order, and properties equal to\n * their default (`active`, `static`, `layer`, `tags`, `enabled`) omitted. Pass the result to\n * `stringifySceneFile` for the canonical text.\n *\n * An entity that came from an `instance` entry is re-emitted as one — with overrides recomputed by\n * diffing its current state against the instanced scene — unless `flatten` is set.\n *\n * @param source - The instance to write, or the entities to write as a file's roots.\n * @param options - Flattening, naming, and the issue collector.\n * @returns The file object.\n *\n * @example\n * ```ts\n * const text = stringifySceneFile(serializeScene(world.activeScene));\n * ```\n *\n * @public\n */\nexport function serializeScene(source: SceneInstance | readonly Entity[], options?: SerializeSceneOptions): SceneFile {\n const instance = isEntityList(source) ? null : source;\n const roots = instance === null ? [...(isEntityList(source) ? source : [])] : [...instance.roots];\n const issues: SerializeIssue[] = [];\n const report = (code: string, message: string): void => {\n const issue = { code, message };\n issues.push(issue);\n options?.onIssue?.(issue);\n };\n const flatten = options?.flatten === true;\n const plan = planEntities(roots, flatten, report);\n const references = membershipEncoder(plan.entities, plan.components);\n const entities: SceneFileEntity[] = [];\n for (let index = 0; index < plan.order.length; index += 1) {\n const planned = plan.order[index];\n if (planned !== undefined) {\n entities.push(writeEntity(planned, references, report));\n }\n }\n const engineVersion = options?.engineVersion === undefined ? VERSION : options.engineVersion;\n const settings = options?.settings === undefined ? (instance?.settings ?? null) : options.settings;\n return {\n format: SCENE_FILE_FORMAT,\n formatVersion: SCENE_FORMAT_VERSION,\n ...(engineVersion === null ? {} : { engineVersion }),\n name: options?.name ?? instance?.name ?? \"scene\",\n ...(settings === null ? {} : { settings }),\n entities,\n };\n}\n\n/**\n * Writes one entity as a file record, for tooling and tests\n * (`docs/architecture/06-serialization-and-scene-format.md` §5).\n *\n * @remarks\n * The entity is written on its own: its `parent` is whatever its runtime parent's uid is, its\n * instanced subtree is not consulted, and references to objects outside it become `null`.\n *\n * @param entity - The entity to write.\n * @param references - How entity and component references resolve to uids; by default every\n * reference resolves to the target's own uid, which is what an inspector wants.\n * @returns The entity record.\n *\n * @example\n * ```ts\n * expect(serializeEntity(player).transform.position).toEqual([0, 1, 0]);\n * ```\n *\n * @public\n */\nexport function serializeEntity(entity: Entity, references: ReferenceEncoder = ownUidEncoder()): SceneFileEntity {\n const planned: PlannedEntity = { entity, parentUid: entity.parent?.uid ?? null, origin: null };\n return writeEntity(planned, references, ignoreIssue);\n}\n\n/**\n * Drops a reported problem, for the standalone writers that have no collector.\n */\nfunction ignoreIssue(): void {\n // The standalone writers are for tooling and tests; their caller has no issue collector.\n}\n\n/**\n * Writes one component as a file record, for tooling and tests.\n *\n * @param component - The component to write.\n * @param references - How entity and component references resolve to uids.\n * @param onIssue - Receives problems found while encoding props.\n * @returns The component record.\n * @throws IgnifxError with code `IGX-0204` when the component's class declares no `typeId`.\n *\n * @example\n * ```ts\n * expect(serializeComponent(mover).props).toEqual({ speed: 5 });\n * ```\n *\n * @public\n */\nexport function serializeComponent(\n component: Component,\n references: ReferenceEncoder = ownUidEncoder(),\n onIssue?: (issue: SerializeIssue) => void,\n): SceneFileComponent {\n const info = component.world.registry.describe(component.constructor);\n const typeId = component.world.registry.requireTypeId(component.constructor);\n const schema = info.schema;\n const record: SceneFileComponent = {\n uid: component.uid,\n type: typeId,\n ...(component.enabled ? {} : { enabled: false }),\n ...(schemaVersionOf(component) === 1 ? {} : { schemaVersion: schemaVersionOf(component) }),\n ...(schema === null ? {} : { props: encodeComponentProps(component, references, onIssue) }),\n };\n return record;\n}\n\n/**\n * Splits {@link serializeScene}'s union. `Array.isArray` narrows to `any[]`, which does not remove\n * `readonly Entity[]` from a union, so the predicate states the discrimination once.\n *\n * @param source - What the caller passed.\n * @returns `true` when it is a list of entities rather than a scene instance.\n */\nfunction isEntityList(source: SceneInstance | readonly Entity[]): source is readonly Entity[] {\n return Array.isArray(source);\n}\n\n/** One entity that will be written, with the parent uid the file records for it. */\ninterface PlannedEntity {\n /** The entity. */\n readonly entity: Entity;\n /** The uid written as `parent`. */\n readonly parentUid: string | null;\n /** Its origin, when it is an instance root that will be written as an `instance` entry. */\n readonly origin: EntityOrigin | null;\n}\n\n/** What {@link planEntities} worked out. */\ninterface EntityPlan {\n /** The entities to write, in tree order. */\n readonly order: readonly PlannedEntity[];\n /** The membership set references are resolved against. */\n readonly entities: ReadonlySet<Entity>;\n /** The membership set component references are resolved against. */\n readonly components: ReadonlySet<Component>;\n}\n\n/**\n * Walks the roots in tree order and decides which entities the file contains: everything, except\n * the entities an `instance` entry stands for when `flatten` is off.\n *\n * @param roots - The roots to walk.\n * @param flatten - `true` writes instanced entities as plain entities.\n * @param report - Receives problems.\n * @returns The plan.\n */\nfunction planEntities(\n roots: readonly Entity[],\n flatten: boolean,\n report: (code: string, message: string) => void,\n): EntityPlan {\n const order: PlannedEntity[] = [];\n const entities = new Set<Entity>();\n const components = new Set<Component>();\n const visit = (entity: Entity, parentUid: string | null): void => {\n if (entity.isDestroyed) {\n return;\n }\n const origin = entityInternals(entity).origin;\n const asInstance = !flatten && origin !== null && origin.instanced !== null;\n order.push({ entity, parentUid, origin: asInstance ? origin : null });\n entities.add(entity);\n const own = entity.components;\n for (let index = 0; index < own.length; index += 1) {\n const component = own[index];\n if (component !== undefined) {\n components.add(component);\n }\n }\n const children = entity.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child === undefined) {\n continue;\n }\n if (asInstance && belongsToInstance(child, entity)) {\n continue;\n }\n if (asInstance) {\n report(\n CoreErrorCode.unresolvedReference,\n `${child.name} was added under the instance ${entity.name} at run time; it is written as a plain entity.`,\n );\n }\n visit(child, entity.uid);\n }\n };\n for (let index = 0; index < roots.length; index += 1) {\n const root = roots[index];\n if (root !== undefined) {\n visit(root, null);\n }\n }\n return { order, entities, components };\n}\n\n/**\n * Reports whether an entity is part of the instance a root stands for, at any depth.\n *\n * @param entity - The candidate.\n * @param root - The instance root.\n * @returns `true` when the entity came from that instance.\n */\nfunction belongsToInstance(entity: Entity, root: Entity): boolean {\n let origin = entityInternals(entity).origin;\n let guard = 0;\n const limit = 64;\n while (origin !== null && guard < limit) {\n const inside = origin.instanceRoot;\n if (inside === null) {\n return false;\n }\n if (inside === root) {\n return true;\n }\n origin = entityInternals(inside).origin;\n guard += 1;\n }\n return false;\n}\n\n/**\n * Writes one planned entity.\n *\n * @param planned - The entity and its file parent.\n * @param references - How references resolve.\n * @param report - Receives problems.\n * @returns The record.\n */\nfunction writeEntity(\n planned: PlannedEntity,\n references: ReferenceEncoder,\n report: (code: string, message: string) => void,\n): SceneFileEntity {\n const entity = planned.entity;\n const tags = [...entity.tags.values()].toSorted();\n const layerName = entity.world.layers.nameOf(entity.layer);\n const origin = planned.origin;\n const instance = origin === null ? null : writeInstance(entity, origin, references, report);\n const components = writeComponents(entity, references, report);\n return {\n uid: entity.uid,\n name: entity.name,\n parent: planned.parentUid,\n ...(entity.active ? {} : { active: false }),\n ...(entity.isStatic ? { static: true } : {}),\n ...(layerName === null || layerName === \"Default\" ? {} : { layer: layerName }),\n ...(tags.length === 0 ? {} : { tags }),\n transform: writeTransform(entity.transform),\n ...(instance === null ? {} : { instance }),\n ...(components.length === 0 ? {} : { components }),\n };\n}\n\n/**\n * Writes an entity's own components, skipping the transform, which the file records separately.\n *\n * @param entity - The entity.\n * @param references - How references resolve.\n * @param report - Receives problems.\n * @returns The records, in attach order.\n */\nfunction writeComponents(\n entity: Entity,\n references: ReferenceEncoder,\n report: (code: string, message: string) => void,\n): SceneFileComponent[] {\n const records: SceneFileComponent[] = [];\n const components = entity.components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component === undefined || component === entity.transform || component.isDestroyed) {\n continue;\n }\n const info = component.world.registry.describe(component.constructor);\n if (info.typeId === null) {\n report(\n CoreErrorCode.componentTypeIdMissing,\n `${component.constructor.name} on ${entity.name} has no typeId and cannot be written.`,\n );\n continue;\n }\n records.push(\n serializeComponent(component, references, (issue) => {\n report(issue.code, issue.message);\n }),\n );\n }\n return records;\n}\n\n/**\n * Writes an entity's local transform.\n *\n * @param transform - The transform.\n * @returns The record.\n */\nfunction writeTransform(transform: Transform): SceneFileTransform {\n const position = transform.localPosition;\n const rotation = transform.localRotation;\n const scale = transform.localScale;\n return {\n position: [canonicalizeNumber(position.x), canonicalizeNumber(position.y), canonicalizeNumber(position.z)],\n rotation: [\n canonicalizeNumber(rotation.x),\n canonicalizeNumber(rotation.y),\n canonicalizeNumber(rotation.z),\n canonicalizeNumber(rotation.w),\n ],\n scale: [canonicalizeNumber(scale.x), canonicalizeNumber(scale.y), canonicalizeNumber(scale.z)],\n };\n}\n\n/**\n * Writes the `instance` entry of an instance root, recomputing its overrides by diffing the\n * instanced scene's entities against what they are now\n * (`docs/architecture/06-serialization-and-scene-format.md` §5).\n *\n * @param root - The instance root.\n * @param origin - Its origin, whose `instanced` link names the scene.\n * @param references - How references resolve.\n * @param report - Receives problems.\n * @returns The entry.\n */\nfunction writeInstance(\n root: Entity,\n origin: EntityOrigin,\n references: ReferenceEncoder,\n report: (code: string, message: string) => void,\n): SceneFileInstance | null {\n const link = origin.instanced;\n if (link === null) {\n return null;\n }\n const overrides = computeOverrides(root, link.scene, references, report);\n return {\n scene: { $asset: link.address },\n hash: link.scene.hash,\n ...(overrides.length === 0 ? {} : { overrides }),\n };\n}\n\n/**\n * Diffs every direct member of an instance against the record the instanced file holds for it.\n *\n * @remarks\n * Only entities the instanced file itself declares are diffed. An entity that came from a scene\n * the instanced scene itself instanced is not addressable by the §2 path grammar — its uid lives in\n * a third file — so deep edits inside a nested prefab are not written back; `flatten: true` is the\n * escape hatch.\n *\n * @param root - The instance root.\n * @param scene - The instanced scene.\n * @param references - How references resolve.\n * @param report - Receives problems.\n * @returns The overrides, in a stable order: entity records in file order, then per entity its\n * plain properties, then its components.\n */\nfunction computeOverrides(\n root: Entity,\n scene: SceneAsset,\n references: ReferenceEncoder,\n report: (code: string, message: string) => void,\n): SceneFileOverride[] {\n const current = new Map<string, Entity>();\n collectDirectMembers(root, root, current);\n const overrides: SceneFileOverride[] = [];\n const source = scene.file.entities;\n for (let index = 0; index < source.length; index += 1) {\n const record = source[index];\n if (record === undefined) {\n continue;\n }\n const entity = current.get(record.uid);\n if (entity === undefined) {\n continue;\n }\n diffEntity(entity, record, overrides, references, report);\n }\n return overrides;\n}\n\n/**\n * Collects the entities of an instance that the instanced file itself declared, keyed by the uid it\n * gave them.\n *\n * @param entity - Where to walk from.\n * @param root - The instance root.\n * @param out - Filled with source uid to entity.\n */\nfunction collectDirectMembers(entity: Entity, root: Entity, out: Map<string, Entity>): void {\n const children = entity.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child === undefined || child.isDestroyed) {\n continue;\n }\n const origin = entityInternals(child).origin;\n if (origin !== null && origin.instanceRoot === root) {\n out.set(origin.sourceUid, child);\n }\n collectDirectMembers(child, root, out);\n }\n}\n\n/**\n * Diffs one instanced entity against its file record.\n *\n * @param entity - The runtime entity.\n * @param record - What the instanced file says it should be.\n * @param overrides - Where patches are appended.\n * @param references - How references resolve.\n * @param report - Receives problems.\n */\nfunction diffEntity(\n entity: Entity,\n record: SceneFileEntity,\n overrides: SceneFileOverride[],\n references: ReferenceEncoder,\n report: (code: string, message: string) => void,\n): void {\n const uid = record.uid;\n if (entity.name !== record.name) {\n overrides.push({ path: `${uid}/name`, value: entity.name });\n }\n if (entity.active !== (record.active ?? true)) {\n overrides.push({ path: `${uid}/active`, value: entity.active });\n }\n if (entity.isStatic !== (record.static ?? false)) {\n overrides.push({ path: `${uid}/static`, value: entity.isStatic });\n }\n const layerName = entity.world.layers.nameOf(entity.layer) ?? \"Default\";\n if (layerName !== (record.layer ?? \"Default\")) {\n overrides.push({ path: `${uid}/layer`, value: layerName });\n }\n const tags = [...entity.tags.values()].toSorted();\n if (!sameStrings(tags, record.tags ?? [])) {\n overrides.push({ path: `${uid}/tags`, value: tags });\n }\n diffTransform(entity, record, uid, overrides);\n diffComponents(entity, record, uid, overrides, references, report);\n}\n\n/**\n * Diffs an instanced entity's transform against its file record.\n *\n * @param entity - The runtime entity.\n * @param record - Its file record.\n * @param uid - The record's uid, for paths.\n * @param overrides - Where patches are appended.\n */\nfunction diffTransform(entity: Entity, record: SceneFileEntity, uid: string, overrides: SceneFileOverride[]): void {\n const current = writeTransform(entity.transform);\n if (!sameNumbers(current.position, record.transform.position)) {\n overrides.push({ path: `${uid}/transform/position`, value: [...current.position] });\n }\n if (!sameNumbers(current.rotation, record.transform.rotation)) {\n overrides.push({ path: `${uid}/transform/rotation`, value: [...current.rotation] });\n }\n if (!sameNumbers(current.scale, record.transform.scale)) {\n overrides.push({ path: `${uid}/transform/scale`, value: [...current.scale] });\n }\n}\n\n/**\n * Diffs an instanced entity's components: added ones become `add`, removed ones `remove`, and each\n * differing prop or `enabled` flag becomes a `replace`.\n *\n * @param entity - The runtime entity.\n * @param record - Its file record.\n * @param uid - The record's uid, for paths.\n * @param overrides - Where patches are appended.\n * @param references - How references resolve.\n * @param report - Receives problems.\n */\nfunction diffComponents(\n entity: Entity,\n record: SceneFileEntity,\n uid: string,\n overrides: SceneFileOverride[],\n references: ReferenceEncoder,\n report: (code: string, message: string) => void,\n): void {\n const origin = entityInternals(entity).origin;\n const sourceUids = origin?.componentSourceUids ?? new Map<string, string>();\n const declared = record.components ?? [];\n const seen = new Set<string>();\n const components = entity.components;\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (component === undefined || component === entity.transform || component.isDestroyed) {\n continue;\n }\n if (component.world.registry.describe(component.constructor).typeId === null) {\n continue;\n }\n const sourceUid = sourceUids.get(component.uid);\n const written = serializeComponent(component, references, (issue) => {\n report(issue.code, issue.message);\n });\n if (sourceUid === undefined) {\n overrides.push({ op: \"add\", path: `${uid}/components`, value: toJson(written) });\n continue;\n }\n seen.add(sourceUid);\n const before = declared.find((candidate) => candidate.uid === sourceUid);\n if (before === undefined) {\n overrides.push({ op: \"add\", path: `${uid}/components`, value: toJson(written) });\n continue;\n }\n const schema = component.world.registry.describe(component.constructor).schema;\n diffProps(uid, sourceUid, before, written, schema, overrides);\n }\n for (let index = 0; index < declared.length; index += 1) {\n const before = declared[index];\n if (before !== undefined && !seen.has(before.uid)) {\n overrides.push({ op: \"remove\", path: `${uid}/components/${before.uid}` });\n }\n }\n}\n\n/**\n * Diffs one component's `enabled` flag and props.\n *\n * @param entityUid - The instanced entity's uid.\n * @param componentUid - The instanced component's uid.\n * @param before - What the instanced file says.\n * @param after - What the component is now.\n * @param schema - The component's declared fields, so an omitted prop compares against its default.\n * @param overrides - Where patches are appended.\n */\nfunction diffProps(\n entityUid: string,\n componentUid: string,\n before: SceneFileComponent,\n after: SceneFileComponent,\n schema: Schema | null,\n overrides: SceneFileOverride[],\n): void {\n if ((before.enabled ?? true) !== (after.enabled ?? true)) {\n overrides.push({ path: `${entityUid}/components/${componentUid}/enabled`, value: after.enabled ?? true });\n }\n const beforeProps = before.props ?? {};\n const afterProps = after.props ?? {};\n const references = ownUidEncoder();\n for (const name of Object.keys(afterProps)) {\n const next = afterProps[name] ?? null;\n // A prop the instanced file omits means \"the schema default\" (§2), so the comparison is against\n // the encoded default rather than against `undefined` — otherwise every terse prefab would\n // re-save with an override per field.\n const field = schema?.[name];\n const previous =\n beforeProps[name] ?? (field === undefined ? null : encodeValue(field, field.createDefault(), references));\n if (!sameJson(previous, next)) {\n overrides.push({ path: `${entityUid}/components/${componentUid}/props/${name}`, value: next });\n }\n }\n}\n\n/**\n * Encodes a component's props against its schema.\n *\n * @param component - The component.\n * @param references - How references resolve.\n * @param onIssue - Receives encoding problems.\n * @returns The props object, in schema declaration order.\n */\nfunction encodeComponentProps(\n component: Component,\n references: ReferenceEncoder,\n onIssue?: (issue: SerializeIssue) => void,\n): JsonObject {\n const schema = component.world.registry.describe(component.constructor).schema;\n if (schema === null) {\n return {};\n }\n // Boundary assertion (coding standards §5.2): a schema-defined class carries exactly the schema's\n // field names as own properties, assigned by the generated base class's constructor.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const values = component as unknown as Record<string, unknown>;\n const props: Record<string, unknown> = {};\n for (const name of Object.keys(schema)) {\n props[name] = values[name];\n }\n const issues: SchemaIssue[] = [];\n // Boundary assertion (coding standards §5.2): `encodeProps` reads the bag by the schema's own\n // field names, which is exactly what was just collected.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const encoded = encodeProps(schema, props as never, references, issues);\n for (let index = 0; index < issues.length; index += 1) {\n const issue = issues[index];\n if (issue !== undefined) {\n onIssue?.({ code: issue.code, message: `${component.uid}.${issue.path}: ${issue.message}` });\n }\n }\n return encoded;\n}\n\n/**\n * The `schemaVersion` a component's class declares, defaulting to `1`\n * (`docs/architecture/06-serialization-and-scene-format.md` §7).\n *\n * @param component - The component.\n * @returns The version.\n */\nfunction schemaVersionOf(component: Component): number {\n const declared: unknown = Reflect.get(component.constructor, \"schemaVersion\");\n return typeof declared === \"number\" && Number.isInteger(declared) && declared > 0 ? declared : 1;\n}\n\n/**\n * The reference encoder standalone `serializeEntity`/`serializeComponent` use: every target\n * resolves to its own uid, because there is no file membership to test against.\n *\n * @returns The encoder.\n */\nfunction ownUidEncoder(): ReferenceEncoder {\n return { entityUid: readUid, componentUid: readUid };\n}\n\n/**\n * Reads a reference target's own uid.\n *\n * @param value - The field value.\n * @returns Its uid, or `null` when the value is not an object carrying one.\n */\nfunction readUid(value: unknown): string | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const uid: unknown = Reflect.get(value, \"uid\");\n return typeof uid === \"string\" ? uid : null;\n}\n\n/**\n * Views a component record as plain JSON, for an `add` override's `value`.\n *\n * @param record - The record.\n * @returns The same object, typed as JSON.\n */\nfunction toJson(record: SceneFileComponent): JsonValue {\n // Boundary assertion (coding standards §5.2): every field of a component record is already JSON;\n // the interface exists to name the shape, not to add anything to it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return record as unknown as JsonValue;\n}\n\n/**\n * Compares two string lists.\n *\n * @param left - The first.\n * @param right - The second.\n * @returns `true` when they hold the same strings in the same order.\n */\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compares two number lists.\n *\n * @param left - The first.\n * @param right - The second.\n * @returns `true` when they hold the same numbers in the same order.\n */\nfunction sameNumbers(left: readonly number[], right: readonly number[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compares two JSON values structurally. Both sides come out of the same canonical encoder, so\n * comparing their canonical text is exact and cheap.\n *\n * @param left - The first.\n * @param right - The second.\n * @returns `true` when they encode identically.\n */\nfunction sameJson(left: JsonValue, right: JsonValue): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n","import type { WaitInstruction } from \"../app/types.js\";\n\n/**\n * The wait instructions a coroutine yields\n * (`docs/architecture/01-lifecycle-and-time.md` §5, ADR-0010). Each factory allocates one small,\n * frozen object; a coroutine that waits every frame therefore allocates one object per wait, which\n * is why long-running loops hoist a wait into a field and yield it repeatedly where the wait is\n * stateless (`waitFixedUpdate`, a fixed `waitSeconds`).\n */\n\n/**\n * Waits for a number of **scaled** seconds — `time.timeScale` applies, so a slow-motion effect\n * slows the wait too.\n *\n * @param seconds - How long to wait, in seconds.\n * @returns The instruction to `yield`. Allocates one small object.\n *\n * @example\n * ```ts\n * reload() {\n * this.isReloading = true;\n * yield waitSeconds(1.5);\n * this.isReloading = false;\n * }\n * ```\n *\n * @public\n */\nexport function waitSeconds(seconds: number): WaitInstruction {\n return Object.freeze({ kind: \"seconds\", seconds });\n}\n\n/**\n * Waits for a number of **unscaled** seconds — unaffected by `time.timeScale`, so a pause menu's\n * animations keep running while the game is frozen.\n *\n * @param seconds - How long to wait, in seconds of wall-clock time.\n * @returns The instruction to `yield`. Allocates one small object.\n *\n * @public\n */\nexport function waitSecondsRealtime(seconds: number): WaitInstruction {\n return Object.freeze({ kind: \"secondsRealtime\", seconds });\n}\n\n/**\n * Waits until just after the next fixed step, so the coroutine sees the same world state a\n * `fixedUpdate` would.\n *\n * @returns The instruction to `yield`. Allocates one small object; hoist it into a field when a\n * loop yields it every iteration.\n *\n * @example\n * ```ts\n * push() {\n * const step = waitFixedUpdate();\n * for (let index = 0; index < 30; index += 1) {\n * this.body.addForce(this.direction);\n * yield step;\n * }\n * }\n * ```\n *\n * @public\n */\nexport function waitFixedUpdate(): WaitInstruction {\n return Object.freeze({ kind: \"fixedUpdate\" });\n}\n\n/**\n * Waits until a predicate becomes `true`. The predicate is evaluated once per frame in the\n * `Update` phase, so it must be cheap and free of side effects.\n *\n * @param predicate - Evaluated each frame; the coroutine resumes on the first `true`.\n * @returns The instruction to `yield`. Allocates one small object.\n *\n * @example\n * ```ts\n * yield waitUntil(() => this.door.isOpen);\n * ```\n *\n * @public\n */\nexport function waitUntil(predicate: () => boolean): WaitInstruction {\n return Object.freeze({ kind: \"until\", predicate });\n}\n\n/**\n * Waits while a predicate stays `true` — the complement of {@link waitUntil}.\n *\n * @param predicate - Evaluated each frame; the coroutine resumes on the first `false`.\n * @returns The instruction to `yield`. Allocates one small object.\n *\n * @public\n */\nexport function waitWhile(predicate: () => boolean): WaitInstruction {\n return Object.freeze({ kind: \"while\", predicate });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,aAAa;;CAExB,WAAW;;CAEX,YAAY;;CAEZ,QAAQ;;CAER,YAAY;;CAEZ,QAAQ;;CAER,eAAe;;CAEf,WAAW;;CAEX,OAAO;;CAEP,SAAS;;CAET,OAAO;;CAEP,MAAM;;CAEN,QAAQ;;CAER,IAAI;;CAEJ,UAAU;;CAEV,UAAU;AACZ;;;;;;;AAeA,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;AAmCxC,MAAa,gBAAgB;;CAE3B,sBAAsB;;CAEtB,4BAA4B;;CAE5B,gCAAgC;;CAEhC,oBAAoB;;CAEpB,qBAAqB;;CAErB,aAAa;;CAEb,aAAa;;CAEb,kBAAkB;;CAElB,0BAA0B;;CAE1B,8BAA8B;;CAE9B,0BAA0B;;CAE1B,wBAAwB;;CAExB,yBAAyB;;CAEzB,sBAAsB;;CAEtB,gBAAgB;;CAEhB,oBAAoB;;CAEpB,cAAc;;CAEd,oBAAoB;;CAEpB,eAAe;;CAEf,gBAAgB;;CAEhB,wBAAwB;;CAExB,eAAe;;CAEf,sBAAsB;;CAEtB,2BAA2B;;CAE3B,wBAAwB;;CAExB,kBAAkB;;CAElB,yBAAyB;;CAEzB,sBAAsB;;CAEtB,wBAAwB;;CAExB,wBAAwB;;CAExB,iBAAiB;;CAEjB,iCAAiC;;CAEjC,2BAA2B;;CAE3B,gBAAgB;;CAEhB,kBAAkB;;CAElB,kBAAkB;;CAElB,eAAe;;CAEf,iBAAiB;;CAEjB,sBAAsB;;CA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