@ignifx/core 0.21.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +22 -0
  2. package/dist/{agx-tone-mapping-Cgt844j6.js → agx-tone-mapping-CCdGk_ly.js} +2 -2
  3. package/dist/agx-tone-mapping-CCdGk_ly.js.map +1 -0
  4. package/dist/auto-exposure-uzPn0beO.js.map +1 -1
  5. package/dist/{bloom-hdr-CLtQj-oY.js → bloom-hdr-xPwkIdHG.js} +5 -6
  6. package/dist/bloom-hdr-xPwkIdHG.js.map +1 -0
  7. package/dist/contact-shadows-T523EXaP.js.map +1 -1
  8. package/dist/effect-task-CMbuO6Kb.js.map +1 -1
  9. package/dist/{environment-Bf4aphSb.js → environment-7fJbN402.js} +2 -2
  10. package/dist/{environment-Bf4aphSb.js.map → environment-7fJbN402.js.map} +1 -1
  11. package/dist/{gtao-Bpu5-0Ne.js → gtao-BmdrXXJz.js} +10 -11
  12. package/dist/gtao-BmdrXXJz.js.map +1 -0
  13. package/dist/{hdr-output-DBQwMphy.js → hdr-output-_2TU-jWy.js} +8 -8
  14. package/dist/hdr-output-_2TU-jWy.js.map +1 -0
  15. package/dist/index.d.ts +40 -42
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +104 -108
  18. package/dist/index.js.map +1 -1
  19. package/dist/{instanced-mesh-instance-B-fXKSrY.js → instanced-mesh-instance-BLdAJTj8.js} +3 -3
  20. package/dist/instanced-mesh-instance-BLdAJTj8.js.map +1 -0
  21. package/dist/{light-probe-asset-BqfSrJe9.js → light-probe-asset-DGNIwKNb.js} +2 -2
  22. package/dist/light-probe-asset-DGNIwKNb.js.map +1 -0
  23. package/dist/{light-probes-DDojYajw.js → light-probes-C8jharz9.js} +6 -6
  24. package/dist/light-probes-C8jharz9.js.map +1 -0
  25. package/dist/lightmaps-BUUIIkt9.js.map +1 -1
  26. package/dist/material-myMbl9mW.js.map +1 -1
  27. package/dist/{material-plugin-DapJNj04.js → material-plugin-BBxIy6eo.js} +4 -4
  28. package/dist/material-plugin-BBxIy6eo.js.map +1 -0
  29. package/dist/{overlay-CjVgsfrm.js → overlay-DokHzP6_.js} +2 -3
  30. package/dist/overlay-DokHzP6_.js.map +1 -0
  31. package/dist/{post-effect-Cu3Enpz7.js → post-effect-DEZD-r0I.js} +3 -3
  32. package/dist/post-effect-DEZD-r0I.js.map +1 -0
  33. package/dist/{post-effect-compiler-cCq9lcHt.js → post-effect-compiler-unDD3hod.js} +4 -4
  34. package/dist/post-effect-compiler-unDD3hod.js.map +1 -0
  35. package/dist/{prefab-overrides-C2GsgOQc.js → prefab-overrides-Bb7jVm7A.js} +3 -3
  36. package/dist/prefab-overrides-Bb7jVm7A.js.map +1 -0
  37. package/dist/{prefab-overrides-htDc_5Po.d.ts → prefab-overrides-DwrPDVVt.d.ts} +61 -63
  38. package/dist/{prefab-overrides-htDc_5Po.d.ts.map → prefab-overrides-DwrPDVVt.d.ts.map} +1 -1
  39. package/dist/prefab.d.ts +1 -1
  40. package/dist/prefab.js +1 -1
  41. package/dist/{reflection-probe-QkD1Fo_d.js → reflection-probe-C2jcreI1.js} +5 -5
  42. package/dist/reflection-probe-C2jcreI1.js.map +1 -0
  43. package/dist/{reflection-probes-CAzSuqf8.js → reflection-probes-BMVQfbhm.js} +10 -10
  44. package/dist/reflection-probes-BMVQfbhm.js.map +1 -0
  45. package/dist/{render-path-D11i_7X8.js → render-path-CWXHrRa2.js} +2 -2
  46. package/dist/render-path-CWXHrRa2.js.map +1 -0
  47. package/dist/{scene-color-passes-B93qTOka.js → scene-color-passes-DgXJ45Ql.js} +2 -2
  48. package/dist/scene-color-passes-DgXJ45Ql.js.map +1 -0
  49. package/dist/{scene-inputs-BxGOsnIZ.js → scene-inputs-_0j2Hi6L.js} +9 -8
  50. package/dist/scene-inputs-_0j2Hi6L.js.map +1 -0
  51. package/dist/{shader-declaration-5q__jycG.js → shader-declaration-BGprFBLq.js} +4 -4
  52. package/dist/shader-declaration-BGprFBLq.js.map +1 -0
  53. package/dist/{shader-material-TM4f8eKA.js → shader-material-C9sYMGWw.js} +8 -9
  54. package/dist/shader-material-C9sYMGWw.js.map +1 -0
  55. package/dist/{shader-material-CJIDFvSb.js → shader-material-vmkJ25II.js} +3 -3
  56. package/dist/shader-material-vmkJ25II.js.map +1 -0
  57. package/dist/{shader-pragma-ljmAbVc2.js → shader-pragma-D0MjCOIg.js} +3 -3
  58. package/dist/shader-pragma-D0MjCOIg.js.map +1 -0
  59. package/dist/ssgi-DSnhqotl.js.map +1 -1
  60. package/dist/{surface-shader-rpPpeosD.js → surface-shader-BfADq9Wx.js} +6 -6
  61. package/dist/surface-shader-BfADq9Wx.js.map +1 -0
  62. package/dist/{taa-BwBZLy11.js → taa-nxVA78Ur.js} +5 -6
  63. package/dist/taa-nxVA78Ur.js.map +1 -0
  64. package/dist/vec3-2C3LBZnt.js.map +1 -1
  65. package/package.json +1 -1
  66. package/dist/agx-tone-mapping-Cgt844j6.js.map +0 -1
  67. package/dist/bloom-hdr-CLtQj-oY.js.map +0 -1
  68. package/dist/gtao-Bpu5-0Ne.js.map +0 -1
  69. package/dist/hdr-output-DBQwMphy.js.map +0 -1
  70. package/dist/instanced-mesh-instance-B-fXKSrY.js.map +0 -1
  71. package/dist/light-probe-asset-BqfSrJe9.js.map +0 -1
  72. package/dist/light-probes-DDojYajw.js.map +0 -1
  73. package/dist/material-plugin-DapJNj04.js.map +0 -1
  74. package/dist/overlay-CjVgsfrm.js.map +0 -1
  75. package/dist/post-effect-Cu3Enpz7.js.map +0 -1
  76. package/dist/post-effect-compiler-cCq9lcHt.js.map +0 -1
  77. package/dist/prefab-overrides-C2GsgOQc.js.map +0 -1
  78. package/dist/reflection-probe-QkD1Fo_d.js.map +0 -1
  79. package/dist/reflection-probes-CAzSuqf8.js.map +0 -1
  80. package/dist/render-path-D11i_7X8.js.map +0 -1
  81. package/dist/scene-color-passes-B93qTOka.js.map +0 -1
  82. package/dist/scene-inputs-BxGOsnIZ.js.map +0 -1
  83. package/dist/shader-declaration-5q__jycG.js.map +0 -1
  84. package/dist/shader-material-CJIDFvSb.js.map +0 -1
  85. package/dist/shader-material-TM4f8eKA.js.map +0 -1
  86. package/dist/shader-pragma-ljmAbVc2.js.map +0 -1
  87. package/dist/surface-shader-rpPpeosD.js.map +0 -1
  88. package/dist/taa-BwBZLy11.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"reflection-probe-QkD1Fo_d.js","names":[],"sources":["../src/signal/signal.ts","../src/schema/schema.ts","../src/handles/handle.ts","../src/component/internals.ts","../src/component/component.ts","../src/lite/picking.ts","../src/schema/types.ts","../src/schema/field-kinds.ts","../src/render/render-texture.ts","../src/render/reflection-probe.ts"],"sourcesContent":["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","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 * Refuses a field name that every plain object already has through `Object.prototype`:\n * `constructor`, `toString`, `valueOf`, `hasOwnProperty`, `__proto__` and the rest. Encoders,\n * decoders, and the inspector walk a schema and read each field as `values[name]`, so a value that\n * omits such a field yields the inherited member instead of `undefined`; and they write it as\n * `out[name] = …`, which for `__proto__` replaces the object's prototype instead of adding a key.\n * Refusing the name once, where the schema is declared, keeps every one of those sites correct.\n * `prototype` is not inherited by plain objects, so it stays a legal name.\n *\n * A literal `{ __proto__: f32(1) }` (not computed) never makes a key at all: it sets the object's\n * prototype, so the field would vanish without a word. The fields object must therefore be a plain\n * object (its prototype `Object.prototype`, or `null`).\n *\n * @param fields - The field definitions being declared.\n * @param where - What declares them, for the message: `\"schema\"` or `\"record\"`.\n * @throws IgnifxError with code `IGX-0607` when a name is an `Object.prototype` member, or the\n * fields object is not a plain object.\n *\n * @internal\n */\nexport function assertNoInheritedFieldNames(fields: Schema, where: string): void {\n const prototype: unknown = Object.getPrototypeOf(fields);\n if (prototype !== Object.prototype && prototype !== null) {\n throwSchemaError(\n SchemaIssueCode.unknownField,\n `${where} fields are not a plain object, so a field is hidden in its prototype; a literal ` +\n `\"__proto__: …\" key sets the prototype instead of declaring a field. Rename the field.`,\n );\n }\n for (const name of Object.keys(fields)) {\n if (Object.hasOwn(Object.prototype, name)) {\n throwSchemaError(\n SchemaIssueCode.unknownField,\n `${where} field \"${name}\" names a member every object inherits (Object.prototype.${name}); rename the field.`,\n );\n }\n }\n}\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 IgnifxError with code `IGX-0607` when a field name is not identifier-like, starts with\n * `_`, collides with a `Component`/`Script` member such as `enabled` or `update`, or names an\n * `Object.prototype` member such as `constructor` or `toString`, or when `fields` is not a plain\n * object (a literal `__proto__: …` key sets its prototype rather than declaring a field).\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 assertNoInheritedFieldNames(fields, \"schema\");\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 // 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, collides\n * with a `Component`/`Script` member, or names an `Object.prototype` member such as `constructor`.\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 * Runs after a tool changed the component's serialized fields from outside it: an editor's\n * inspector or document op, or a hot reload that gave a field its new default. The engine's own\n * loads and a script's assignments do not call it. A component that builds something from its\n * fields (a physics shape, say) rebuilds it here. Not gated in edit mode (ADR-0028).\n *\n * @param fields - The names of the fields that changed.\n */\n onValidate?(fields: readonly string[]): 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 { pickMeshesWithRay, pickWithRay } from \"@babylonjs/lite\";\nimport { parentNode, readNodeTag } from \"./node.js\";\nimport type { NodeTag } from \"./node.js\";\nimport type { Mesh, PickingInfo, Ray, RayPickOptions, SceneContext, SceneNode } 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 * Decides whether a mesh may be picked, from the ignifx tag that owns it and the mesh itself.\n *\n * @remarks\n * The tag is the one {@link readOwnerTag} finds, so a glTF mesh inside a `Model` is judged by the\n * model's entity. The mesh is passed only so a caller can compare it by identity against an earlier\n * hit; nothing outside `src/lite/**` reads it.\n *\n * @internal\n */\nexport type PickAccept = (tag: NodeTag | null, mesh: Mesh) => boolean;\n\n/**\n * The ignifx tag that owns a node: its own, or the nearest tagged ancestor's.\n *\n * @remarks\n * A `MeshRenderer` tags the mesh it clones, but a `Model` tags only the cloned glTF root, and the\n * meshes Lite draws are that root's descendants (`render/gpu/model-instance.ts`). Walking up to the\n * nearest tag resolves both, and any other renderable that parents several Lite nodes under one\n * tagged node, to the entity and component that created them (editor spike S0.2 §6.1). The walk\n * stops at the first tag, so an entity parented under a model's bone still owns its own meshes.\n *\n * @param node - The picked node, usually a mesh.\n * @returns The nearest tag, or `null` when no node on the way to the root carries one.\n *\n * @internal\n */\nexport function readOwnerTag(node: SceneNode): NodeTag | null {\n for (let current: SceneNode | null = node; current !== null; current = parentNode(current)) {\n const tag = readNodeTag(current);\n if (tag !== null) {\n return tag;\n }\n }\n return null;\n}\n\n/**\n * Casts a ray against a scene's renderable meshes, considering only the meshes a predicate accepts.\n *\n * @remarks\n * The predicate is stated over the owning *tag* rather than over Lite's `Mesh` so the component\n * layer can 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 that owns it.\n * @returns Lite's picking info.\n *\n * @internal\n */\nexport function raycastSceneWhere(scene: SceneContext, ray: PickRay, accept: PickAccept): PickingInfo {\n const options: RayPickOptions = { predicate: (mesh: Mesh): boolean => accept(readOwnerTag(mesh), 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 tag — the picked mesh's own or its nearest tagged ancestor's, so a glTF mesh\n * inside a `Model` resolves to the model — or `null` when the ray missed or no node on the way to\n * the root is one ignifx created.\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 readOwnerTag(mesh);\n}\n\n/**\n * The name of the mesh a hit landed on.\n *\n * @param info - A hit.\n * @returns The Lite mesh's name — for a glTF model, the name the file gives the node or primitive —\n * or `\"\"` for a miss or an unnamed mesh.\n *\n * @internal\n */\nexport function readPickedMeshName(info: PickingInfo): string {\n const name: unknown = info.pickedMesh?.name;\n return typeof name === \"string\" ? name : \"\";\n}\n\n/**\n * The identity of one earlier hit, which a pick can be told to look through.\n *\n * @internal\n */\nexport interface PickedIdentity {\n /** The mesh that was hit. */\n readonly mesh: Mesh;\n /** The thin instance that was hit, or `-1` when the mesh has none. */\n readonly thinInstanceIndex: number;\n}\n\n/**\n * Reads the identity of a hit, for a later pick to ignore.\n *\n * @param info - A hit.\n * @returns The mesh and thin instance, or `null` for a miss or a hit on something other than a\n * regular Lite mesh (a Gaussian-splatting mesh, which Lite's `ignore` cannot name).\n *\n * @internal\n */\nexport function readPickedIdentity(info: PickingInfo): PickedIdentity | null {\n const mesh = info.pickedMesh;\n if (mesh === null || !(\"material\" in mesh)) {\n return null;\n }\n return { mesh, thinInstanceIndex: info.thinInstanceIndex };\n}\n","import type { JsonObject, JsonValue } from \"./json.js\";\n\n/**\n * Field kinds supported by component schemas.\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 /**\n * Increment used by the inspector's drag and spinner controls. A `quat` field is edited as\n * intrinsic XYZ Euler angles, so its step is in degrees.\n */\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 /**\n * The instance shape the token names. A class token carries it for free; a plain token for an\n * asset that has no class (a scene, a prefab) leaves it out and fixes `A` through its annotation —\n * see `SceneAssetToken`. Nothing reads it at runtime.\n */\n readonly prototype?: A;\n}\n\n/**\n * A serializable asset reference used by scene tools before an app resolves it.\n * Runtime `asset()` fields hold `AssetHandle<A> | null`; the encoder accepts both forms through\n * their shared address and optional type.\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 { assertNoInheritedFieldNames, 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 * @throws IgnifxError with code `IGX-0607` when a sub-field name is an `Object.prototype` member\n * such as `__proto__`, `constructor`, or `toString`.\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 assertNoInheritedFieldNames(fields, \"record\");\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 field's value is a read-only array of names. The kernel's `LayerMask` satisfies the same\n * structural shape, so a component may hold either.\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 { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { RenderCapture } from \"./renderer.js\";\nimport type { LiteCamera } from \"../lite/camera.js\";\nimport type { LiteRenderTexture } from \"../lite/gpu/render-texture.js\";\n\n/**\n * The largest side of a render texture, in pixels.\n *\n * @public\n */\nexport const RENDER_TEXTURE_MAX_SIZE = 4096;\n\n/**\n * The Babylon Lite `metadata` key that keeps a render-scene mesh out of every render texture.\n *\n * @remarks\n * A mesh whose `metadata[EDITOR_ONLY_METADATA_KEY]` is `true` draws in the main view but never in\n * a {@link RenderTexture}: an editor's grid or helper that must not show in its game view or\n * thumbnails. Set it on a mesh reached through a `.lite` escape hatch, such as\n * `RenderOverlay.lite.mainScene` (no stability guarantee, `CONSTITUTION.md` §3.4).\n *\n * @beta\n */\nexport const EDITOR_ONLY_METADATA_KEY = \"ignifxEditorOnly\";\n\n/**\n * An offscreen colour target a camera renders into (`docs/architecture/07-rendering.md` §2.11).\n *\n * @remarks\n * Create one with `app.renderer.createRenderTexture(width, height)`. Fill it once with\n * `app.renderer.renderToTexture(camera, texture)`, or every frame by setting a camera's\n * `renderTarget`. It holds a GPU pass of the render scene and its target from the first render\n * on; `dispose()` frees both, and `app.dispose()` disposes every texture still open.\n *\n * @example\n * ```ts\n * const texture = app.renderer.createRenderTexture(256, 256);\n * await app.renderer.renderToTexture(minimapCamera, texture);\n * const pixels = await texture.readPixels();\n * texture.dispose();\n * ```\n *\n * @beta\n */\nexport interface RenderTexture {\n /** The width, in pixels. */\n readonly width: number;\n /** The height, in pixels. */\n readonly height: number;\n /** Whether `dispose()` has run. */\n readonly isDisposed: boolean;\n /**\n * Reads the texture as the last rendered frame left it.\n *\n * @returns Tightly packed RGBA8, top row first. All zeros before anything was rendered into it.\n * @throws IgnifxError with code `IGX-0729` on a headless app or while no render loop runs, and\n * `IGX-0731` once the texture is disposed.\n */\n readPixels(): Promise<RenderCapture>;\n /** Frees the texture's GPU pass and target. Idempotent; a camera rendering into it stops. */\n dispose(): void;\n}\n\n/**\n * What a render texture needs from the renderer that made it.\n *\n * @internal\n */\nexport interface RenderTextureOwner {\n /**\n * Creates the texture's GPU pass, or throws why it cannot.\n *\n * @param width - The width.\n * @param height - The height.\n * @param member - The API member asking, for the error.\n * @returns The pass.\n */\n createPass(width: number, height: number, member: string): Promise<LiteRenderTexture>;\n /**\n * Forgets a disposed texture.\n *\n * @param texture - The texture.\n */\n release(texture: RenderTextureImpl): void;\n}\n\n/** A pending one-frame render. */\ninterface RenderRequest {\n /** The camera to render through. */\n readonly camera: LiteCamera;\n /** Settles the request once its frame has been submitted. */\n readonly resolve: () => void;\n}\n\n/**\n * Checks a render texture's size.\n *\n * @param width - The requested width.\n * @param height - The requested height.\n * @throws IgnifxError with code `IGX-0730` for a side that is not a whole number from 1 to\n * {@link RENDER_TEXTURE_MAX_SIZE}.\n *\n * @internal\n */\nexport function assertRenderTextureSize(width: number, height: number): void {\n const isSide = (side: number): boolean => Number.isSafeInteger(side) && side >= 1 && side <= RENDER_TEXTURE_MAX_SIZE;\n if (!isSide(width) || !isSide(height)) {\n throw new IgnifxError(\n CoreErrorCode.invalidRenderTextureSize,\n `A render texture of ${String(width)}x${String(height)}: each side must be a whole number from 1 to ${String(RENDER_TEXTURE_MAX_SIZE)}.`,\n { context: { member: \"app.renderer.createRenderTexture()\", width, height, max: RENDER_TEXTURE_MAX_SIZE } },\n );\n }\n}\n\n/**\n * What {@link bindFrameCameras} reads of a camera: a structural slice of `Camera`.\n *\n * @internal\n */\nexport interface FrameCameraSource {\n /** The camera's render target, or `null` for the canvas. */\n readonly renderTarget: RenderTexture | null;\n /** The Lite camera, `null` while detached. */\n readonly lite: { readonly camera: LiteCamera | null };\n /** Whether the camera and its entity are enabled. */\n readonly isEnabledInHierarchy: boolean;\n}\n\n/**\n * Tells each live texture which enabled, attached camera renders into it this frame.\n *\n * @param cameras - Every camera in the world, in creation order; the last one per texture wins.\n * @param live - The renderer's live textures; a camera aiming at any other is ignored.\n *\n * @internal\n */\nexport function bindFrameCameras(cameras: readonly FrameCameraSource[], live: ReadonlySet<RenderTextureImpl>): void {\n for (const camera of cameras) {\n const target = camera.renderTarget;\n const lite = camera.lite.camera;\n if (target instanceof RenderTextureImpl && live.has(target) && lite !== null && camera.isEnabledInHierarchy) {\n target.setFrameCamera(lite);\n }\n }\n}\n\n/**\n * The renderer's render texture: the per-frame camera choice and the one-frame requests.\n *\n * @internal\n */\nexport class RenderTextureImpl implements RenderTexture {\n readonly width: number;\n\n readonly height: number;\n\n readonly #owner: RenderTextureOwner;\n\n #pass: LiteRenderTexture | null = null;\n\n #creating: Promise<LiteRenderTexture> | null = null;\n\n /** The camera whose `renderTarget` this is, as the current frame's sync found it. */\n #frameCamera: LiteCamera | null = null;\n\n readonly #requests: RenderRequest[] = [];\n\n #isDisposed = false;\n\n /**\n * Creates the texture; its GPU pass is created on first use.\n *\n * @param owner - The renderer.\n * @param width - The checked width.\n * @param height - The checked height.\n */\n constructor(owner: RenderTextureOwner, width: number, height: number) {\n this.#owner = owner;\n this.width = width;\n this.height = height;\n }\n\n get isDisposed(): boolean {\n return this.#isDisposed;\n }\n\n /**\n * Resolves the texture's GPU pass, creating it once.\n *\n * @param member - The API member asking, for the error.\n * @returns The pass.\n */\n async pass(member: string): Promise<LiteRenderTexture> {\n this.assertUsable(member);\n this.#creating ??= this.#owner.createPass(this.width, this.height, member).then(\n (pass) => {\n if (this.#isDisposed) {\n pass.dispose();\n } else {\n this.#pass = pass;\n }\n return pass;\n },\n (error: unknown) => {\n this.#creating = null;\n throw error;\n },\n );\n const pass = await this.#creating;\n this.assertUsable(member);\n return pass;\n }\n\n /**\n * Queues a render through a camera on the next frame.\n *\n * @param camera - The Lite camera.\n * @returns A promise that settles once that frame has been submitted.\n */\n request(camera: LiteCamera): Promise<void> {\n return new Promise((resolve) => {\n this.#requests.push({ camera, resolve });\n });\n }\n\n /**\n * Notes the camera that renders into this texture every frame. The render sync system calls it\n * for every enabled camera whose `renderTarget` this is, before {@link RenderTextureImpl.flush}.\n *\n * @param camera - The Lite camera.\n */\n setFrameCamera(camera: LiteCamera): void {\n this.#frameCamera = camera;\n if (this.#pass === null && this.#creating === null) {\n // The first frame only starts the pass; a failure leaves it for the next frame to retry.\n this.pass(\"Camera.renderTarget\").catch(() => null);\n }\n }\n\n /**\n * Points the pass at this frame's camera: the oldest request's, else the `renderTarget` one's,\n * else none. Requests for that camera settle once the frame is submitted.\n */\n flush(): void {\n const pass = this.#pass;\n const requested = this.#requests[0]?.camera ?? null;\n const camera = requested ?? this.#frameCamera;\n this.#frameCamera = null;\n if (pass === null) {\n return;\n }\n pass.setCamera(camera);\n if (requested === null) {\n return;\n }\n const served: RenderRequest[] = [];\n for (let index = this.#requests.length - 1; index >= 0; index -= 1) {\n const pending = this.#requests[index];\n if (pending !== undefined && pending.camera === requested) {\n served.push(pending);\n this.#requests.splice(index, 1);\n }\n }\n // The frame graph executes after this frame callback and submits in the same task; a microtask\n // runs once it has.\n queueMicrotask(() => {\n for (const pending of served) {\n pending.resolve();\n }\n });\n }\n\n async readPixels(): Promise<RenderCapture> {\n const pass = await this.pass(\"RenderTexture.readPixels()\");\n const data = await pass.read();\n return { width: this.width, height: this.height, data };\n }\n\n dispose(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#isDisposed = true;\n this.#pass?.dispose();\n this.#pass = null;\n this.#owner.release(this);\n // Nothing will render them now; settling beats leaving the caller waiting forever.\n for (const pending of this.#requests.splice(0)) {\n pending.resolve();\n }\n }\n\n /**\n * Refuses a disposed texture.\n *\n * @param member - The API member asking.\n * @throws IgnifxError with code `IGX-0731` once disposed.\n */\n assertUsable(member: string): void {\n if (this.#isDisposed) {\n throw renderTextureUnusableError(member);\n }\n }\n}\n\n/**\n * The error for a disposed or foreign render texture.\n *\n * @param member - The API member asking.\n * @returns The error.\n *\n * @internal\n */\nexport function renderTextureUnusableError(member: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.renderTextureUnusable,\n `${member}: the render texture is disposed or belongs to another app.`,\n {\n context: { member },\n hint: \"Create a render texture with this app's app.renderer.createRenderTexture() and keep it until you dispose it.\",\n },\n );\n}\n","import { Component } from \"../component/component.js\";\nimport { enumOf, f32, layerMask, optional, u32, vec3 } from \"../schema/field-kinds.js\";\nimport { createDefaults, defineSchema } from \"../schema/schema.js\";\nimport type { Vec3Like } from \"../math/types.js\";\nimport type { Schema } from \"../schema/types.js\";\n\n/**\n * The `ReflectionProbe` component (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B1).\n *\n * The component only holds settings and the \"capture again\" request. The renderer loads the probe's\n * GPU code (`./gpu/reflection-probes.ts`, `../lite/gpu/reflection-probe.ts`) only once a world has\n * a probe, so a project without one pays nothing for it (`CONSTITUTION.md` §2.5). Headless, a probe\n * captures nothing.\n */\n\n/**\n * The `as const` name table behind {@link ReflectionProbeRefreshMode}.\n *\n * @public\n */\nexport const REFLECTION_PROBE_REFRESH_MODES = [\"once\", \"onDemand\", \"everyFrame\"] as const;\n\n/**\n * When a reflection probe renders its cube map again.\n *\n * @remarks\n * - `\"once\"` (default): when the probe is first ready, and again on {@link ReflectionProbe.refresh}.\n * - `\"onDemand\"`: only on {@link ReflectionProbe.refresh}; until then the probe reflects nothing.\n * - `\"everyFrame\"`: every frame, six extra scene passes each frame. Use it for one probe at most, on\n * desktop. The `low` and `medium` quality tiers (`rendering.quality`) treat it as `\"once\"`.\n *\n * @public\n */\nexport type ReflectionProbeRefreshMode = (typeof REFLECTION_PROBE_REFRESH_MODES)[number];\n\n/** The smallest and largest cube face, in pixels. */\nconst MIN_SIZE = 16;\nconst MAX_SIZE = 1024;\n\n/**\n * A point that captures the scene around it into a cube map, which nearby shiny PBR materials then\n * reflect instead of the scene environment.\n *\n * @remarks\n * Each lit PBR material reflects the nearest enabled probe that has captured: a probe whose\n * `boxProjection` box holds the mesh wins over one that does not, then the closer probe wins. With no\n * probe, materials reflect the `Environment` again. A material shared by several meshes follows the\n * first of them. Diffuse lighting still comes from the scene environment.\n *\n * Blending: once two or more box probes have captured and one of them has a `blendDistance` above\n * 0, every lit PBR material blends them per fragment instead, fading each probe out over the last\n * `blendDistance` metres inside its box. Probes without a box take no part then, and a probe that\n * captures `\"everyFrame\"` (or is still capturing) keeps the nearest-probe choice for that frame.\n *\n * The probe needs a loaded `Environment` (it reuses its lighting tables) and a canvas-backed app;\n * until an environment map is loaded it waits, holding no GPU memory and costing no frame time. A\n * `rendering.quality` tier caps `size` and allows `\"everyFrame\"` only at `high` (below, the probe\n * captures as `\"once\"`); with the `custom` tier nothing is capped.\n * Mip levels are box-filtered, so very rough materials look blurrier than with a prefiltered `.env`.\n *\n * @example\n * ```ts\n * const probe = world.createEntity(\"Room probe\", { position: { x: 0, y: 1.5, z: 0 } });\n * probe.addComponent(ReflectionProbe, { size: 128, boxProjection: { x: 8, y: 3, z: 8 } });\n * ```\n *\n * @beta\n */\nexport class ReflectionProbe extends Component {\n /** The namespaced registration id. */\n static typeId = \"ignifx/ReflectionProbe\";\n\n /** What the component does, in one line, for an inspector. */\n static description = \"Captures the scene around it into a cube map that nearby PBR materials reflect.\";\n\n /** One probe per entity. */\n static allowMultiple = false;\n\n /** The serialized field declarations (ADR-0004). */\n static schema: Schema = reflectionProbeSchema();\n\n /**\n * Cube face size in pixels, rounded down to a power of two from 16 to 1024. Defaults to `128`. A\n * `rendering.quality` tier caps it: 64 at `low`, 128 at `medium`, 256 at `high`.\n */\n declare size: number;\n\n /** When the probe captures again. Defaults to `\"once\"`. */\n declare refreshMode: ReflectionProbeRefreshMode;\n\n /**\n * The full size, in metres, of the box (centred on the probe) that reflections are projected onto,\n * or `null` (default) for no box: reflections then look infinitely far away.\n */\n declare boxProjection: Vec3Like | null;\n\n /**\n * How far inside its box, in metres, the probe fades out where it overlaps another box probe.\n * Defaults to `0`, no blending; see the class remarks. Needs `boxProjection`.\n */\n declare blendDistance: number;\n\n /** The layer names the probe captures; empty (default) captures every layer. */\n declare cullingMask: readonly string[];\n\n /** The near clip distance of the capture, in metres. Defaults to `0.1`. */\n declare near: number;\n\n /** The far clip distance of the capture, in metres. Defaults to `1000`. */\n declare far: number;\n\n /** Applies the schema defaults, exactly as `Component.define` would. */\n constructor() {\n super();\n Object.assign(this, createDefaults(ReflectionProbe.schema));\n }\n\n #isRefreshRequested = false;\n\n /**\n * Asks the probe to capture again from the next frame, whatever its `refreshMode`.\n *\n * @remarks\n * Call it after the static scene around the probe changed, such as a door opening. A capture\n * repeats over a few frames, so meshes whose materials are still compiling are caught.\n */\n refresh(): void {\n this.#isRefreshRequested = true;\n }\n\n /**\n * Reads and clears the request {@link ReflectionProbe.refresh} made.\n *\n * @returns Whether a capture was requested since the last call.\n *\n * @internal\n */\n consumeRefreshRequest(): boolean {\n const requested = this.#isRefreshRequested;\n this.#isRefreshRequested = false;\n return requested;\n }\n}\n\n/**\n * The cube face size a probe captures at.\n *\n * @param size - The authored size.\n * @param maxSize - The quality tier's cap (`RenderingQualityPreset.reflectionProbeMaxSize`); 1024\n * when no tier applies.\n * @returns `size` rounded down to a power of two and clamped to 16..`maxSize`; 128 (or `maxSize` if\n * smaller) for a value that is not a finite number.\n *\n * @internal\n */\nexport function resolveReflectionProbeSize(size: number, maxSize: number = MAX_SIZE): number {\n const upper = Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.floor(maxSize)));\n const clamped = Number.isFinite(size) ? Math.min(upper, Math.max(MIN_SIZE, Math.floor(size))) : Math.min(upper, 128);\n return 2 ** Math.floor(Math.log2(clamped));\n}\n\n/**\n * The refresh mode a probe runs with under a quality tier.\n *\n * @param mode - The authored mode.\n * @param allowsEveryFrame - Whether the tier lets a probe capture every frame\n * (`RenderingQualityPreset.reflectionProbeEveryFrame`; `true` when no tier applies).\n * @returns `mode`, except `\"everyFrame\"` reads as `\"once\"` when the tier forbids it.\n *\n * @internal\n */\nexport function resolveReflectionProbeRefreshMode(\n mode: ReflectionProbeRefreshMode,\n allowsEveryFrame: boolean,\n): ReflectionProbeRefreshMode {\n return mode === \"everyFrame\" && !allowsEveryFrame ? \"once\" : mode;\n}\n\n/**\n * A probe as {@link selectReflectionProbe} sees it.\n *\n * @internal\n */\nexport interface ReflectionProbeCandidate {\n /** The probe's world position. */\n readonly x: number;\n readonly y: number;\n readonly z: number;\n /** The full size of its projection box, or `null`. */\n readonly box: Vec3Like | null;\n}\n\n/**\n * Picks the probe a point reflects.\n *\n * @remarks\n * A probe whose box holds the point wins, the smallest such box first; with none, the closest\n * probe centre wins. Ties keep the earlier probe.\n *\n * @param x - The point's world X.\n * @param y - The point's world Y.\n * @param z - The point's world Z.\n * @param candidates - The enabled probes that have captured.\n * @returns The index of the chosen probe, or `-1` when there is none.\n *\n * @internal\n */\nexport function selectReflectionProbe(\n x: number,\n y: number,\n z: number,\n candidates: readonly ReflectionProbeCandidate[],\n): number {\n let inside = -1;\n let insideVolume = Number.POSITIVE_INFINITY;\n let nearest = -1;\n let nearestDistance = Number.POSITIVE_INFINITY;\n for (let index = 0; index < candidates.length; index += 1) {\n const probe = candidates[index];\n if (probe === undefined) {\n continue;\n }\n const dx = x - probe.x;\n const dy = y - probe.y;\n const dz = z - probe.z;\n const box = probe.box;\n if (box !== null && Math.abs(dx) <= box.x / 2 && Math.abs(dy) <= box.y / 2 && Math.abs(dz) <= box.z / 2) {\n const volume = box.x * box.y * box.z;\n if (volume < insideVolume) {\n inside = index;\n insideVolume = volume;\n }\n }\n const distance = dx * dx + dy * dy + dz * dz;\n if (distance < nearestDistance) {\n nearest = index;\n nearestDistance = distance;\n }\n }\n return inside >= 0 ? inside : nearest;\n}\n\n/**\n * A probe as {@link reflectionProbeBlendLayout} sees it.\n *\n * @internal\n */\nexport interface ReflectionProbeBlendCandidate extends ReflectionProbeCandidate {\n /** Its `blendDistance`. */\n readonly blendDistance: number;\n}\n\n/**\n * One probe of a blended set: its box, and the inner box where it alone counts.\n *\n * @internal\n */\nexport interface ReflectionProbeBlendVolume {\n /** The index of the candidate it came from. */\n readonly index: number;\n /** The probe's world position, the centre of both boxes. */\n readonly position: readonly [number, number, number];\n /** The full size of the projection box, where the probe reaches zero weight. */\n readonly outer: readonly [number, number, number];\n /** The full size of the box where it has full weight: `outer` less `2 · blendDistance`, at least 0. */\n readonly inner: readonly [number, number, number];\n}\n\n/**\n * The blended probe set for a frame's candidates, and the voxel grid that indexes it.\n *\n * @internal\n */\nexport interface ReflectionProbeBlendLayout {\n /** The box probes, smallest box first, then in candidate order. */\n readonly volumes: readonly ReflectionProbeBlendVolume[];\n /** The grid's world-space minimum corner: the union of the boxes. */\n readonly minimum: readonly [number, number, number];\n /** The grid's world-space maximum corner. */\n readonly maximum: readonly [number, number, number];\n /** The voxel edge: the longest side over {@link REFLECTION_PROBE_GRID_CELLS}. */\n readonly cellSize: number;\n}\n\n/**\n * The voxel count along the longest side of a blended set's grid.\n *\n * @internal\n */\nexport const REFLECTION_PROBE_GRID_CELLS = 32;\n\n/**\n * Whether a frame's probes blend, and how.\n *\n * @remarks\n * They blend when at least two have a `boxProjection` box and at least one of those has a\n * `blendDistance` above 0. Probes without a box are left out of the set.\n *\n * @param candidates - The enabled probes that have captured.\n * @returns The layout, or `null` when the nearest-probe choice applies.\n *\n * @internal\n */\nexport function reflectionProbeBlendLayout(\n candidates: readonly ReflectionProbeBlendCandidate[],\n): ReflectionProbeBlendLayout | null {\n const volumes: ReflectionProbeBlendVolume[] = [];\n let blends = false;\n const minimum: [number, number, number] = [\n Number.POSITIVE_INFINITY,\n Number.POSITIVE_INFINITY,\n Number.POSITIVE_INFINITY,\n ];\n const maximum: [number, number, number] = [\n Number.NEGATIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n ];\n for (let index = 0; index < candidates.length; index += 1) {\n const candidate = candidates[index];\n const box = candidate?.box ?? null;\n if (candidate === undefined || box === null || !(box.x > 0 && box.y > 0 && box.z > 0)) {\n continue;\n }\n const blend = Number.isFinite(candidate.blendDistance) ? Math.max(0, candidate.blendDistance) : 0;\n blends ||= blend > 0;\n const position: [number, number, number] = [candidate.x, candidate.y, candidate.z];\n const outer: [number, number, number] = [box.x, box.y, box.z];\n volumes.push({\n index,\n position,\n outer,\n inner: [Math.max(0, box.x - 2 * blend), Math.max(0, box.y - 2 * blend), Math.max(0, box.z - 2 * blend)],\n });\n for (let axis = 0; axis < 3; axis += 1) {\n const centre = position[axis] ?? 0;\n const half = (outer[axis] ?? 0) / 2;\n minimum[axis] = Math.min(minimum[axis] ?? 0, centre - half);\n maximum[axis] = Math.max(maximum[axis] ?? 0, centre + half);\n }\n }\n if (volumes.length < 2 || !blends) {\n return null;\n }\n // Lite takes the first candidate whose inner box holds a fragment, so the smallest box goes first,\n // as in selectReflectionProbe; ties keep candidate order.\n volumes.sort(\n (a, b) => a.outer[0] * a.outer[1] * a.outer[2] - b.outer[0] * b.outer[1] * b.outer[2] || a.index - b.index,\n );\n const longest = Math.max(maximum[0] - minimum[0], maximum[1] - minimum[1], maximum[2] - minimum[2]);\n return { volumes, minimum, maximum, cellSize: longest / REFLECTION_PROBE_GRID_CELLS };\n}\n\n/**\n * Builds the component's declared fields.\n *\n * @returns The schema. Built inside a function: module scope holds declarations and immutable\n * constants only (`CONSTITUTION.md` §3.5).\n */\nfunction reflectionProbeSchema(): Schema {\n return defineSchema({\n size: u32(128, {\n min: MIN_SIZE,\n max: MAX_SIZE,\n tooltip:\n \"Cube face size in pixels, rounded down to a power of two. Larger is sharper and slower to capture. Quality tiers cap it (low 64, medium 128, high 256).\",\n }),\n refreshMode: enumOf(REFLECTION_PROBE_REFRESH_MODES, \"once\", {\n tooltip:\n \"once: capture when ready and on refresh(); onDemand: only on refresh(); everyFrame: every frame (costly; one probe; the low and medium quality tiers treat it as once).\",\n }),\n boxProjection: optional(vec3({ x: 10, y: 10, z: 10 }), {\n tooltip:\n \"Full size in metres of the box, centred on the probe, that reflections are projected onto; null for none.\",\n }),\n blendDistance: f32(0, {\n min: 0,\n tooltip:\n \"How far inside its box, in metres, the probe fades out where it overlaps another box probe; 0 for no blending. Needs boxProjection.\",\n }),\n cullingMask: layerMask([], { tooltip: \"The layers the probe captures; empty captures every layer.\" }),\n near: f32(0.1, { min: 0.001, tooltip: \"Near clip distance of the capture, in metres.\" }),\n far: f32(1000, { min: 0.01, tooltip: \"Far clip distance of the capture, in metres.\" }),\n });\n}\n"],"mappings":";;;;;;AAoHA,IAAM,aAAN,MAAoB;CAClB;CACA;CACA;;CAEA;;CAEA,kBAAqC;CAErC,YAAY,SAA2B,MAAe,UAAmB,OAAe;EACtF,KAAK,UAAU;EACf,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,QAAQ;CACf;AACF;;AAGA,SAAS,iBAAuB,CAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,SAAb,MAAuD;CACrD,eAAyC,CAAC;CAC1C;CACA;CACA,aAAa;CACb,aAAa;CACb,aAAa;;;;;;;CAQb,YAAY,SAA4B;EACtC,KAAK,iBAAiB,SAAS,iBAAiB;EAChD,KAAK,kBAAkB,SAAS,kBAAkB;CACpD;;;;;;CAOA,IAAI,kBAA0B;EAC5B,OAAO,KAAK;CACd;;;;;;;;;;;;;;;;;CAkBA,QAAQ,SAA2B,SAAsC;EACvE,MAAM,WAAW,SAAS,YAAY;EACtC,IAAI,YAAY,KAAK,mBAAmB,MACtC,MAAM,IAAI,YACR,cAAc,gCACd,2FACA,EAAE,MAAM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AE,MAAM,KAAK,EAAE,MAAM,KAAK,EAAE,MAAM,KAAK,EAAE,MAAM,KAAK,EAAE,MAAM,KAAK,EAAE,MAAM,MAAM,EAAE,QAAQ,EAAE,KACvG;CAEA,OAAO;EAAE;EAAS;EAAS;EAAS,UADpB,KAAK,IAAI,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,QAAQ,EAC5C,IAAA;CAAgC;AACtF;;;;;;;AAQA,SAAS,wBAAgC;CACvC,OAAO,aAAa;EAClB,MAAM,IAAI,KAAK;GACb,KAAK;GACL,KAAK;GACL,SACE;EACJ,CAAC;EACD,aAAa,OAAO,gCAAgC,QAAQ,EAC1D,SACE,0KACJ,CAAC;EACD,eAAe,SAAS,KAAK;GAAE,GAAG;GAAI,GAAG;GAAI,GAAG;EAAG,CAAC,GAAG,EACrD,SACE,4GACJ,CAAC;EACD,eAAe,IAAI,GAAG;GACpB,KAAK;GACL,SACE;EACJ,CAAC;EACD,aAAa,UAAU,CAAC,GAAG,EAAE,SAAS,6DAA6D,CAAC;EACpG,MAAM,IAAI,IAAK;GAAE,KAAK;GAAO,SAAS;EAAgD,CAAC;EACvF,KAAK,IAAI,KAAM;GAAE,KAAK;GAAM,SAAS;EAA+C,CAAC;CACvF,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reflection-probes-CAzSuqf8.js","names":[],"sources":["../src/lite/gpu/reflection-probe.ts","../src/render/gpu/reflection-probes.ts"],"sourcesContent":["import {\n addTask,\n buildFrameGraphTask,\n clearPbrLocalEnvironment,\n createBankedFreeCamera,\n createPbrLocalEnvironmentProbeSet,\n createRenderTarget,\n createRenderTask,\n enablePbrLocalCubemap,\n getFrameGraph,\n getPbrUnlit,\n isPbrMaterial,\n isPbrSkybox,\n rebuildMaterial,\n setPbrEnvironment,\n setPbrLocalEnvironment,\n setPbrLocalEnvironmentProbeSet,\n} from \"@babylonjs/lite\";\nimport { readOwnerTag } from \"../picking.js\";\nimport { readSceneEnvironment } from \"./environment.js\";\nimport { colorTextureOf, deviceOf, removeTask } from \"./render-texture.js\";\nimport type { NodeTag } from \"../node.js\";\nimport type {\n BankedFreeCamera,\n EngineContext,\n EnvironmentTextures,\n Mesh,\n PbrLocalEnvironmentProbe,\n PbrLocalEnvironmentProbeSet,\n PbrMaterialProps,\n RenderTarget,\n RenderTask,\n SceneContext,\n} from \"@babylonjs/lite\";\n\n/**\n * Reflection probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B1). Its own chunk,\n * loaded only when a world has a `ReflectionProbe` (`CONSTITUTION.md` §2.5). Every Lite claim was\n * read from `@babylonjs/lite@1.34.0`.\n *\n * - **Capture.** Lite has no cube capture, so six render tasks (`createRenderTask`, each with its own\n * `rgba16float` target and a `createBankedFreeCamera` looking down one axis, 90° field of view,\n * square target) are appended to the frame graph, switched on for the frames that capture, like\n * `./render-texture.ts`. Faces follow the cube-map convention in Lite's left-handed space: +X, −X\n * and ±Z faces use +Y as up, +Y uses −Z and −Y uses +Z.\n * - **Cube and mips.** In the next frame's `PreRender`, a small render pipeline of ignifx's own copies\n * each face into a cube texture, decoding gamma when `rendering.hdr` is off (the faces then hold\n * tone-mapped sRGB), and box-downsamples the mip chain. It is submitted before Lite's frame, so queue\n * order makes it read the frame that rendered the faces. Mips are not GGX-prefiltered.\n * - **Environment.** The cube is wrapped in an `EnvironmentTextures` (`index.d.ts` 5598) that shares\n * the scene environment's BRDF table and spherical harmonics, so diffuse light is unchanged.\n * - **Materials.** `setPbrLocalEnvironment` (box parallax) or `setPbrEnvironment` (no box) per lit PBR\n * material, then a material rebuild (`index.d.ts` 12612–12654). `enablePbrLocalCubemap` must have\n * resolved first; it is called when the chunk loads.\n * - **Culling mask.** Render tasks have no mesh filter, so each face task's `execute` hides the meshes\n * the caller rejects and shows them again, as `./render-texture.ts` does for editor-only meshes.\n * - **Blending (B1b).** `createPbrLocalEnvironmentProbeSet` (`index.d.ts` 3411) **copies** every\n * probe's cube into one cube array when it is created (`lib/material/pbr/enable-pbr-local-cubemap.js`,\n * `createProbeTexture`) and blends up to four candidates per voxel per fragment. It has no dispose:\n * its buffers and texture are destroyed only when the scene is (`scene._disposables`), so a set\n * replaced earlier is freed through its `_texture`, `_uniformBuffer` and `_gridBuffer` fields and\n * its closure is taken off `scene._disposables`, all read from the pinned source\n * ({@link releaseLiteProbeSet}). A fragment inside a probe's inner box takes\n * that probe alone; between inner and outer boxes the candidates are weighted; outside every outer\n * box the nearest probe by its normalised distance wins (`local-cubemap-fragment.js`).\n */\n\n/** The colour format of the faces and the cube. */\nconst PROBE_FORMAT: GPUTextureFormat = \"rgba16float\";\n\n/** The depth/stencil format Lite's own render tasks use. */\nconst DEPTH_STENCIL_FORMAT: GPUTextureFormat = \"depth24plus-stencil8\";\n\n/** Each face's view direction and up vector, in cube-face order +X, −X, +Y, −Y, +Z, −Z. */\nconst FACES: readonly (readonly [number, number, number, number, number, number])[] = [\n [1, 0, 0, 0, 1, 0],\n [-1, 0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, -1],\n [0, -1, 0, 0, 0, 1],\n [0, 0, 1, 0, 1, 0],\n [0, 0, -1, 0, 1, 0],\n];\n\n/** A full-screen triangle that copies, decodes, or (through a linear sampler) box-downsamples. */\nconst BLIT_WGSL = /* wgsl */ `\nstruct VsOut { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> };\n@vertex fn vs(@builtin(vertex_index) index: u32) -> VsOut {\n let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));\n var out: VsOut;\n out.position = vec4<f32>(corner * 2.0 - 1.0, 0.0, 1.0);\n out.uv = vec2<f32>(corner.x, 1.0 - corner.y);\n return out;\n}\n@group(0) @binding(0) var source: texture_2d<f32>;\n@group(0) @binding(1) var sourceSampler: sampler;\n@fragment fn copy(in: VsOut) -> @location(0) vec4<f32> {\n return vec4<f32>(textureSampleLevel(source, sourceSampler, in.uv, 0.0).rgb, 1.0);\n}\n@fragment fn decode(in: VsOut) -> @location(0) vec4<f32> {\n let colour = textureSampleLevel(source, sourceSampler, in.uv, 0.0).rgb;\n return vec4<f32>(pow(max(colour, vec3<f32>(0.0)), vec3<f32>(2.2)), 1.0);\n}\n`;\n\n/** The blit pipelines of one device. */\ninterface BlitPipelines {\n readonly copy: GPURenderPipeline;\n readonly decode: GPURenderPipeline;\n readonly sampler: GPUSampler;\n}\n\n/** Each device's pipelines, the map created on first use (coding standards §4). */\nlet pipelineCache: WeakMap<GPUDevice, BlitPipelines> | null = null;\n\n/**\n * One probe's capture passes and cube map.\n *\n * @internal\n */\nexport interface LiteReflectionProbe {\n /** The cube face size in pixels. */\n readonly size: number;\n /** The environment materials reflect, `null` until the first capture resolved. Stable afterwards. */\n readonly environment: EnvironmentTextures | null;\n /**\n * Renders the six faces in the coming frame.\n *\n * @param x - The world X of the capture point.\n * @param y - The world Y.\n * @param z - The world Z.\n * @param near - The near clip distance.\n * @param far - The far clip distance.\n * @returns `false`, rendering nothing, while the scene has no environment to borrow the lighting\n * tables from.\n */\n capture(x: number, y: number, z: number, near: number, far: number): boolean;\n /**\n * Turns the faces the last frame rendered into the cube map, when a capture ran.\n *\n * @param decodeGamma - Whether the faces hold gamma-encoded colour (`rendering.hdr` off).\n * @returns `true` when {@link LiteReflectionProbe.environment} was created by this call.\n */\n resolve(decodeGamma: boolean): boolean;\n /**\n * Removes the passes, frees the face targets, and destroys the cube map once `after` settled and\n * the GPU finished the work submitted by then. Idempotent.\n *\n * @param after - What must finish before the cube may go, such as the rebuilds of the materials\n * that reflected it; omitted (device lost, app closing) to wait for the queue only.\n */\n dispose(after?: PromiseLike<unknown>): void;\n}\n\n/**\n * Loads Lite's local-cubemap shader path. Resolve it before assigning any probe.\n *\n * @returns A promise that resolves once the path is registered.\n *\n * @internal\n */\nexport function enableReflectionProbes(): Promise<void> {\n return enablePbrLocalCubemap();\n}\n\n/**\n * Creates a probe's six face passes, switched off, at the end of the scene's frame graph.\n *\n * @param engine - The WebGPU engine.\n * @param scene - The registered render scene.\n * @param size - The face size in pixels, a power of two.\n * @param excludeKey - The `metadata` key that, set to `true` on a mesh, keeps it out of the faces.\n * @param accept - Whether a mesh's owner may be captured; `false` hides it during the faces.\n * @returns The probe.\n *\n * @internal\n */\nexport function createLiteReflectionProbe(\n engine: EngineContext,\n scene: SceneContext,\n size: number,\n excludeKey: string,\n accept: (tag: NodeTag | null) => boolean,\n): LiteReflectionProbe {\n const targets: RenderTarget[] = [];\n const tasks: RenderTask[] = [];\n const cameras: BankedFreeCamera[] = [];\n const hidden: Mesh[] = [];\n for (const face of FACES) {\n const target = createRenderTarget({\n lbl: \"ignifx:reflection-probe-face\",\n format: PROBE_FORMAT,\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: 1,\n size: { width: size, height: size },\n });\n const camera = createBankedFreeCamera(\n { x: 0, y: 0, z: 0 },\n { x: face[0], y: face[1], z: face[2] },\n {\n x: face[3],\n y: face[4],\n z: face[5],\n },\n );\n camera.fov = Math.PI / 2;\n const task = createRenderTask({ name: \"ignifx:reflection-probe\", rt: target, cam: camera }, engine, scene);\n task.executionEnabled = false;\n const execute = task.execute?.bind(task);\n if (execute === undefined) {\n throw new TypeError(\"Lite's render task has no execute(); reflection-probe.ts needs updating for this Lite.\");\n }\n task.execute = (): number => {\n for (const mesh of scene.meshes) {\n if (mesh.visible !== false && (mesh.metadata?.[excludeKey] === true || !accept(readOwnerTag(mesh)))) {\n mesh.visible = false;\n hidden.push(mesh);\n }\n }\n try {\n return execute();\n } finally {\n for (const mesh of hidden) {\n mesh.visible = true;\n }\n hidden.length = 0;\n }\n };\n addTask(scene, task);\n buildFrameGraphTask(getFrameGraph(scene), task);\n targets.push(target);\n tasks.push(task);\n cameras.push(camera);\n }\n let cube: GPUTexture | null = null;\n let environment: EnvironmentTextures | null = null;\n let isCapturing = false;\n let isDisposed = false;\n return {\n size,\n get environment(): EnvironmentTextures | null {\n return environment;\n },\n capture(x: number, y: number, z: number, near: number, far: number): boolean {\n if (isDisposed || readSceneEnvironment(scene) === null) {\n return false;\n }\n for (let index = 0; index < FACES.length; index += 1) {\n const face = FACES[index];\n const camera = cameras[index];\n const task = tasks[index];\n if (face === undefined || camera === undefined || task === undefined) {\n continue;\n }\n camera.position.set(x, y, z);\n camera.target.set(x + face[0], y + face[1], z + face[2]);\n camera.nearPlane = near;\n camera.farPlane = far;\n task.executionEnabled = true;\n }\n isCapturing = true;\n return true;\n },\n resolve(decodeGamma: boolean): boolean {\n if (isDisposed || !isCapturing) {\n return false;\n }\n isCapturing = false;\n for (const task of tasks) {\n task.executionEnabled = false;\n }\n const device = deviceOf(engine);\n const base = readSceneEnvironment(scene);\n if (device === null || base === null) {\n return false;\n }\n cube ??= device.createTexture({\n label: \"ignifx:reflection-probe\",\n size: [size, size, FACES.length],\n format: PROBE_FORMAT,\n mipLevelCount: Math.log2(size) + 1,\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,\n });\n if (!blitFaces(device, cube, targets, decodeGamma)) {\n return false;\n }\n if (environment !== null) {\n return false;\n }\n environment = {\n specularCube: cube,\n specularCubeView: cube.createView({ dimension: \"cube\" }),\n brdfLut: base.brdfLut,\n brdfLutView: base.brdfLutView,\n cubeSampler: base.cubeSampler,\n brdfSampler: base.brdfSampler,\n irradianceSH: base.irradianceSH,\n sphericalHarmonics: base.sphericalHarmonics,\n lodGenerationScale: base.lodGenerationScale,\n lodGenerationOffset: base.lodGenerationOffset ?? 0,\n };\n return true;\n },\n dispose(after?: PromiseLike<unknown>): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n for (const task of tasks) {\n task.executionEnabled = false;\n removeTask(scene, task);\n // Frees the face target too (`lib/frame-graph/render-task-base.js` 97–109).\n task.dispose();\n }\n const retired = cube;\n cube = null;\n environment = null;\n if (retired !== null) {\n destroyWhenIdle(deviceOf(engine), retired, after);\n }\n },\n };\n}\n\n/**\n * Destroys a texture once nothing in flight can name it: a material rebuild finishes asynchronously\n * (`rebuildMaterial`, `index.d.ts` 11136), and until then Lite may still draw with a bind group that\n * holds the old cube, so destruction waits for `after`, then for the queue.\n *\n * @param device - The device, or `null` when it is gone (the texture is destroyed at once).\n * @param texture - The texture.\n * @param after - What must settle first, if anything.\n */\nfunction destroyWhenIdle(device: GPUDevice | null, texture: GPUTexture, after: PromiseLike<unknown> | undefined): void {\n const destroy = (): void => {\n texture.destroy();\n };\n Promise.resolve(after)\n .catch(() => undefined)\n .then(async () => device?.queue.onSubmittedWorkDone())\n .then(destroy, destroy);\n}\n\n/**\n * Copies the six face targets into the cube's first mip and box-downsamples the rest.\n *\n * @param device - The device.\n * @param cube - The cube texture, six layers.\n * @param targets - The face targets, in cube-face order.\n * @param decodeGamma - Whether to decode gamma on the copy.\n * @returns `false` when a face target has no texture yet.\n */\nfunction blitFaces(\n device: GPUDevice,\n cube: GPUTexture,\n targets: readonly RenderTarget[],\n decodeGamma: boolean,\n): boolean {\n const pipelines = blitPipelines(device);\n const encoder = device.createCommandEncoder({ label: \"ignifx:reflection-probe-mips\" });\n for (let face = 0; face < targets.length; face += 1) {\n const target = targets[face];\n const source = target === undefined ? null : colorTextureOf(target);\n if (source === null) {\n return false;\n }\n draw(\n device,\n encoder,\n decodeGamma ? pipelines.decode : pipelines.copy,\n pipelines.sampler,\n source.createView(),\n cubeFace(cube, face, 0),\n );\n for (let mip = 1; mip < cube.mipLevelCount; mip += 1) {\n draw(\n device,\n encoder,\n pipelines.copy,\n pipelines.sampler,\n cubeFace(cube, face, mip - 1),\n cubeFace(cube, face, mip),\n );\n }\n }\n device.queue.submit([encoder.finish()]);\n return true;\n}\n\n/**\n * A 2D view of one face and mip of the cube.\n *\n * @param cube - The cube texture.\n * @param face - The layer.\n * @param mip - The mip level.\n * @returns The view.\n */\nfunction cubeFace(cube: GPUTexture, face: number, mip: number): GPUTextureView {\n return cube.createView({\n dimension: \"2d\",\n baseArrayLayer: face,\n arrayLayerCount: 1,\n baseMipLevel: mip,\n mipLevelCount: 1,\n });\n}\n\n/**\n * Encodes one full-screen blit.\n *\n * @param device - The device.\n * @param encoder - The encoder.\n * @param pipeline - The pipeline.\n * @param sampler - The linear sampler.\n * @param source - The view to read.\n * @param destination - The view to write.\n */\nfunction draw(\n device: GPUDevice,\n encoder: GPUCommandEncoder,\n pipeline: GPURenderPipeline,\n sampler: GPUSampler,\n source: GPUTextureView,\n destination: GPUTextureView,\n): void {\n const bindGroup = device.createBindGroup({\n layout: pipeline.getBindGroupLayout(0),\n entries: [\n { binding: 0, resource: source },\n { binding: 1, resource: sampler },\n ],\n });\n const pass = encoder.beginRenderPass({\n colorAttachments: [\n { view: destination, loadOp: \"clear\", storeOp: \"store\", clearValue: { r: 0, g: 0, b: 0, a: 1 } },\n ],\n });\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindGroup);\n pass.draw(3);\n pass.end();\n}\n\n/**\n * The device's blit pipelines.\n *\n * @param device - The device.\n * @returns The pipelines, created on first use.\n */\nfunction blitPipelines(device: GPUDevice): BlitPipelines {\n pipelineCache ??= new WeakMap();\n const cached = pipelineCache.get(device);\n if (cached !== undefined) {\n return cached;\n }\n const module = device.createShaderModule({ label: \"ignifx:reflection-probe-blit\", code: BLIT_WGSL });\n const pipeline = (entryPoint: string): GPURenderPipeline =>\n device.createRenderPipeline({\n label: `ignifx:reflection-probe-${entryPoint}`,\n layout: \"auto\",\n vertex: { module, entryPoint: \"vs\" },\n fragment: { module, entryPoint, targets: [{ format: PROBE_FORMAT }] },\n primitive: { topology: \"triangle-list\" },\n });\n const created: BlitPipelines = {\n copy: pipeline(\"copy\"),\n decode: pipeline(\"decode\"),\n sampler: device.createSampler({ magFilter: \"linear\", minFilter: \"linear\" }),\n };\n pipelineCache.set(device, created);\n return created;\n}\n\n/**\n * What a material reflects: a probe's environment, where it sits, and its projection box.\n *\n * @internal\n */\nexport interface LiteProbeBinding {\n /** The probe's environment. */\n readonly environment: EnvironmentTextures;\n /** The capture position. */\n readonly position: readonly [number, number, number];\n /** The full size of the projection box, or `null` for none. */\n readonly box: readonly [number, number, number] | null;\n}\n\n/**\n * One probe of a blended set, as {@link createLiteProbeSet} takes it.\n *\n * @internal\n */\nexport interface LiteProbeSetVolume {\n /** The probe's environment, copied into the set. */\n readonly environment: EnvironmentTextures;\n /** The capture position, also the centre of both boxes. */\n readonly position: readonly [number, number, number];\n /** The full size of the projection and outer influence box. */\n readonly outer: readonly [number, number, number];\n /** The full size of the inner influence box. */\n readonly inner: readonly [number, number, number];\n}\n\n/**\n * A blended probe set and its release.\n *\n * @internal\n */\nexport interface LiteProbeSet {\n /** Lite's set. */\n readonly set: PbrLocalEnvironmentProbeSet;\n /**\n * Destroys the set's GPU resources once `after` settled and the queue drained. Idempotent.\n *\n * @param after - What must finish first, such as the rebuilds of the materials that used it;\n * omitted to wait for the queue only.\n */\n dispose(after?: PromiseLike<unknown>): void;\n}\n\n/** The three GPU resources of a Lite probe set, by the field names `enable-pbr-local-cubemap.js` uses. */\nconst PROBE_SET_RESOURCE_FIELDS = [\"_texture\", \"_uniformBuffer\", \"_gridBuffer\"] as const;\n\n/**\n * Frees what a Lite probe set holds: its three GPU resources, and the cleanup closure Lite pushed\n * onto `scene._disposables`, which would otherwise keep the whole set (its 64 KiB uniform data and\n * its grid) alive until the scene is disposed.\n *\n * @remarks\n * Every field is checked before use: a Lite upgrade that renames one degrades to `warn` (a leak\n * that is logged) and never throws. Destroying twice is harmless.\n *\n * @param set - The set, as Lite returned it.\n * @param disposables - The scene's `_disposables` list, or anything else when it is not one.\n * @param cleanup - The closure Lite pushed for this set, or `undefined` when it was not found.\n * @param warn - Receives one message per missing field or list.\n *\n * @internal\n */\nexport function releaseLiteProbeSet(\n set: unknown,\n disposables: unknown,\n cleanup: unknown,\n warn: (message: string) => void,\n): void {\n // Boundary narrowing of Lite's undeclared fields (coding standards §5.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const record = typeof set === \"object\" && set !== null ? (set as Record<string, unknown>) : {};\n for (const field of PROBE_SET_RESOURCE_FIELDS) {\n const resource = record[field];\n const destroy =\n typeof resource === \"object\" && resource !== null ? (resource as { destroy?: unknown }).destroy : undefined;\n if (typeof destroy === \"function\") {\n Reflect.apply(destroy, resource, []);\n } else {\n warn(`a Babylon Lite probe set has no ${field} to destroy, so its GPU memory stays until the scene goes`);\n }\n }\n if (!Array.isArray(disposables) || cleanup === undefined) {\n warn(\"the Babylon Lite probe set's scene cleanup could not be found, so its CPU data stays until the scene goes\");\n return;\n }\n const index = disposables.indexOf(cleanup);\n if (index >= 0) {\n disposables.splice(index, 1);\n }\n}\n\n/**\n * The scene's `_disposables` list, which Lite's set pushes its cleanup onto.\n *\n * @param scene - The scene.\n * @returns The list, or `undefined` when the scene has none (a Lite change).\n */\nfunction disposablesOf(scene: SceneContext): unknown[] | undefined {\n // Lite's scene type does not declare it; read from `lib/scene/scene-core.js` and\n // `enable-pbr-local-cubemap.js` (`scene._disposables.push`).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion, no-underscore-dangle\n const list = (scene as unknown as { _disposables?: unknown })._disposables;\n return Array.isArray(list) ? list : undefined;\n}\n\n/**\n * Builds a blended set from captured probes.\n *\n * @param engine - The engine, for the queue a disposal waits on.\n * @param scene - The registered scene.\n * @param volumes - The probes, at least two.\n * @param minimum - The voxel grid's minimum corner.\n * @param maximum - The voxel grid's maximum corner.\n * @param cellSize - The voxel edge.\n * @param warn - Where a disposal that cannot free everything reports it.\n * @returns The set.\n * @throws When Lite refuses it: more than four probes in a voxel, more probes than the uniform block\n * holds, or cubes of different formats.\n *\n * @internal\n */\nexport function createLiteProbeSet(\n engine: EngineContext,\n scene: SceneContext,\n volumes: readonly LiteProbeSetVolume[],\n minimum: readonly [number, number, number],\n maximum: readonly [number, number, number],\n cellSize: number,\n warn: (message: string) => void,\n): LiteProbeSet {\n const probes: PbrLocalEnvironmentProbe[] = volumes.map((volume) => ({\n shape: \"box\",\n environment: volume.environment,\n capturePosition: volume.position,\n projectionPosition: volume.position,\n influencePosition: volume.position,\n projectionSize: volume.outer,\n influenceInnerSize: volume.inner,\n influenceOuterSize: volume.outer,\n }));\n const disposables = disposablesOf(scene);\n const before = disposables?.length ?? 0;\n const set = createPbrLocalEnvironmentProbeSet(scene, { probes, voxelGrid: { minimum, maximum, cellSize } });\n // Lite pushes exactly one cleanup closure as the set's last step.\n const cleanup = disposables !== undefined && disposables.length === before + 1 ? disposables[before] : undefined;\n let isDisposed = false;\n return {\n set,\n dispose(after?: PromiseLike<unknown>): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n const release = (): void => {\n releaseLiteProbeSet(set, disposables, cleanup, warn);\n };\n const device = deviceOf(engine);\n Promise.resolve(after)\n .catch(() => undefined)\n .then(async () => device?.queue.onSubmittedWorkDone())\n .then(release, release);\n },\n };\n}\n\n/**\n * Calls `visit` for every mesh whose material is a lit, non-skybox PBR material.\n *\n * @param scene - The scene.\n * @param visit - Receives the material and the mesh's world position.\n *\n * @internal\n */\nexport function forEachReflectiveMesh(\n scene: SceneContext,\n visit: (material: PbrMaterialProps, x: number, y: number, z: number) => void,\n): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const mesh = meshes[index];\n const material = mesh?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (mesh === undefined || material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n if (getPbrUnlit(material) !== undefined || isPbrSkybox(material)) {\n continue;\n }\n const world = mesh.worldMatrix;\n visit(material, world[12] ?? 0, world[13] ?? 0, world[14] ?? 0);\n }\n}\n\n/**\n * Points a PBR material at a probe, or back at the scene environment, and rebuilds it.\n *\n * @param scene - The registered scene, or `null` to leave the rebuild to Lite (its device-loss\n * recovery rebuilds every material).\n * @param material - The material.\n * @param binding - The probe, a blended set, or `null` for the scene environment.\n * @returns The rebuild in flight, if Lite runs it asynchronously; Lite reports its failure itself.\n *\n * @internal\n */\nexport function assignReflectionProbe(\n scene: SceneContext | null,\n material: PbrMaterialProps,\n binding: LiteProbeBinding | LiteProbeSet | null,\n): Promise<void> | undefined {\n if (binding === null) {\n clearPbrLocalEnvironment(material);\n } else if (\"set\" in binding) {\n setPbrLocalEnvironmentProbeSet(material, binding.set);\n } else if (binding.box === null) {\n setPbrEnvironment(material, binding.environment);\n } else {\n setPbrLocalEnvironment(material, binding.environment, {\n shape: \"box\",\n capturePosition: binding.position,\n projectionPosition: binding.position,\n projectionSize: binding.box,\n });\n }\n if (scene === null) {\n return undefined;\n }\n // Since 1.34 a PBR rebuild in a built scene finishes asynchronously (`../material.ts`).\n const pending = rebuildMaterial(scene, material);\n return pending instanceof Promise ? pending : undefined;\n}\n","import { toEntityHandle } from \"../../handles/handle.js\";\nimport {\n assignReflectionProbe,\n createLiteProbeSet,\n createLiteReflectionProbe,\n enableReflectionProbes,\n forEachReflectiveMesh,\n} from \"../../lite/gpu/reflection-probe.js\";\nimport {\n reflectionProbeBlendLayout,\n resolveReflectionProbeRefreshMode,\n resolveReflectionProbeSize,\n selectReflectionProbe,\n} from \"../reflection-probe.js\";\nimport { EDITOR_ONLY_METADATA_KEY } from \"../render-texture.js\";\nimport type { LiteProbeBinding, LiteProbeSet, LiteReflectionProbe } from \"../../lite/gpu/reflection-probe.js\";\nimport type { NodeTag } from \"../../lite/node.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { Vec3Like } from \"../../math/types.js\";\nimport type { World } from \"../../world/world.js\";\nimport type {\n ReflectionProbe,\n ReflectionProbeBlendCandidate,\n ReflectionProbeBlendLayout,\n} from \"../reflection-probe.js\";\nimport type { RenderingQualityPreset } from \"../rendering-settings.js\";\n\n/**\n * The render layer's half of reflection probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`,\n * step B1): which probe captures when, and which probe each PBR material reflects. Loaded with\n * `../../lite/gpu/reflection-probe.ts` as one chunk, only once a world has a `ReflectionProbe`.\n *\n * Blending (B1b): when `reflectionProbeBlendLayout` says the frame's probes blend and every box probe\n * has finished capturing (none `everyFrame`), one Lite probe set built from their cubes goes on every\n * lit PBR material. The set copies the cubes, so it is rebuilt when a probe moves, recaptures,\n * resizes its box or changes `blendDistance`, and the replaced set is freed once the material\n * rebuilds that dropped it settled. While a box probe is still capturing, the last set stays (or,\n * before the first, the nearest-probe choice applies); while one is being moved or edited (its\n * binding or `blendDistance` changed within the last {@link BLEND_STILL_FRAMES} frames) the\n * nearest-probe choice applies. A material whose nearest probe has no box keeps that probe. A set Lite refuses (more than four probes\n * overlapping in a voxel, too many probes) logs once and the nearest-probe choice applies.\n */\n\n/**\n * How many consecutive frames one capture request renders. Lite compiles material pipelines\n * asynchronously, so a single frame right after start or after a scene change can miss meshes that\n * are still compiling; repeating it for a few frames catches them.\n */\nconst CAPTURE_FRAMES = 8;\n\n/**\n * How many frames a blended probe's position, box and `blendDistance` must stay unchanged before a\n * probe set is built with it (about 250 ms at 60 Hz). A set copies every cube and rebuilds every lit\n * material, so a probe being moved, dragged or scrubbed falls back to the nearest-probe choice until\n * it rests.\n */\nconst BLEND_STILL_FRAMES = 15;\n\n/** One component's GPU probe and what it last captured with. */\ninterface ProbeState {\n /** The GPU probe. */\n lite: LiteReflectionProbe;\n /** How many more frames capture before the probe rests. */\n framesToCapture: number;\n /** The binding materials use, rebuilt when the probe moves or its box changes. */\n binding: LiteProbeBinding | null;\n /** How many captures it ran, so a blended set made before a recapture is rebuilt. */\n generation: number;\n /** The `blendDistance` seen last frame. */\n blendDistance: number;\n /** How many frames its binding and `blendDistance` have not changed. */\n stillFrames: number;\n}\n\n/** A material `forEachReflectiveMesh` hands out. */\ntype ReflectiveMaterial = Parameters<typeof assignReflectionProbe>[1];\n\n/** A candidate with the binding it stands for. */\ninterface BoundCandidate extends ReflectionProbeBlendCandidate {\n /** The binding. */\n readonly binding: LiteProbeBinding;\n /** Its capture count. */\n readonly generation: number;\n /** Whether it has capture frames left, so a set made of it now would go stale. */\n readonly isCapturing: boolean;\n /** Whether it captures every frame, so any set made of it goes stale at once. */\n readonly isEveryFrame: boolean;\n /** Whether its binding or `blendDistance` changed within {@link BLEND_STILL_FRAMES}. */\n readonly isMoving: boolean;\n}\n\n/** A blended set and what it was built from, compared to decide a rebuild. */\ninterface BlendState {\n readonly lite: LiteProbeSet;\n /** Per volume: binding, generation and blend distance, flattened. */\n readonly key: readonly unknown[];\n}\n\n/**\n * Every reflection probe of a renderer.\n *\n * @internal\n */\nexport interface ReflectionProbeRuntime {\n /**\n * Captures what is due and points each lit PBR material at its probe. Called once per frame from\n * the `PreRender` system.\n *\n * @param world - The world the probes live in.\n * @param probes - Every `ReflectionProbe` in the world.\n * @param isHdr - Whether `rendering.hdr` is on.\n * @param tier - The `rendering.quality` preset, which caps the size and `everyFrame`; `null` for\n * `\"custom\"`.\n * @param hasEnvironment - Whether the scene has an environment map. Without one every probe is\n * freed and nothing else runs, not even the mesh walk.\n */\n update(\n world: World,\n probes: readonly ReflectionProbe[],\n isHdr: boolean,\n tier: RenderingQualityPreset | null,\n hasEnvironment: boolean,\n ): void;\n /**\n * Drops every GPU probe after the device was lost, before Lite's recovery rebuilds the materials,\n * so no material still names a cube of the lost device. Until {@link handleDeviceRecovered},\n * `update` does nothing; the probes capture again on the first frame after it.\n */\n handleDeviceLost(): void;\n /** Lets `update` run again once Lite rebuilt the scene on the new device. */\n handleDeviceRecovered(): void;\n /** Frees every probe and hands every material back to the scene environment. */\n dispose(): void;\n}\n\n/**\n * Creates the runtime once Lite's local-cubemap shader path is loaded.\n *\n * @param engine - The engine.\n * @param scene - The registered render scene.\n * @param warn - Where a probe's warning goes, with the entity's name already in the message.\n * @returns The runtime.\n *\n * @internal\n */\nexport async function createReflectionProbeRuntime(\n engine: LiteEngine,\n scene: LiteScene,\n warn: (message: string) => void,\n): Promise<ReflectionProbeRuntime> {\n await enableReflectionProbes();\n const states = new Map<ReflectionProbe, ProbeState>();\n const assigned = new Map<ReflectiveMaterial, LiteProbeBinding | LiteProbeSet | null>();\n /** The blended set on every lit material, or `null` for the nearest-probe choice. */\n let blend: BlendState | null = null;\n /** The key of a set Lite refused, so it is not tried again every frame. */\n let refusedKey: readonly unknown[] | null = null;\n let hasWarnedRefusal = false;\n const warnedLeaks = new Set<string>();\n const warnLeakOnce = (message: string): void => {\n if (!warnedLeaks.has(message)) {\n warnedLeaks.add(message);\n warn(`Reflection probe blending: ${message}.`);\n }\n };\n /** Sets replaced this frame, freed with the retired cubes. */\n const retiringSets: LiteProbeSet[] = [];\n const seen = new Set<object>();\n const candidates: BoundCandidate[] = [];\n /** The cubes released this frame, freed once the materials that reflected them are rebuilt. */\n const retiring: { lite: LiteReflectionProbe; environment: LiteProbeBinding[\"environment\"] | null }[] = [];\n /**\n * Material rebuilds still in flight, whichever frame started them: a rebuild started a frame ago\n * may still draw with a cube retired now, so a retired cube waits for all of them.\n */\n const rebuilds = new Set<Promise<void>>();\n /**\n * Probes whose capture was freed while they stayed (resized, environment gone, device lost); they\n * capture again whatever their mode.\n */\n const recapture = new WeakSet<ReflectionProbe>();\n let hasWarnedEveryFrame = false;\n /** Between a device loss and Lite's recovery, nothing on the GPU may be touched. */\n let isDeviceLost = false;\n\n const assign = (material: ReflectiveMaterial, binding: LiteProbeBinding | LiteProbeSet | null): void => {\n const pending = assignReflectionProbe(scene, material, binding);\n if (pending !== undefined) {\n rebuilds.add(pending);\n const forget = (): void => {\n rebuilds.delete(pending);\n };\n pending.then(forget, forget);\n }\n };\n\n const release = (probe: ReflectionProbe, state: ProbeState): void => {\n // A capture still under way (an `onDemand` refresh whose frames are not done) counts as wanted.\n if (state.lite.environment !== null || state.framesToCapture > 0) {\n recapture.add(probe);\n }\n retiring.push({ lite: state.lite, environment: state.lite.environment });\n states.delete(probe);\n };\n\n /**\n * Frees the cubes released this frame. A material that reflected one and was not reassigned this\n * frame (its mesh left the scene) goes back to the scene environment first, so it never names a\n * destroyed cube; the cubes then wait for every rebuild still in flight, from any frame.\n */\n const retire = (): void => {\n if (retiring.length > 0) {\n for (const [material, binding] of assigned) {\n if (\n binding !== null &&\n !(\"set\" in binding) &&\n retiring.some((entry) => entry.environment === binding.environment)\n ) {\n assigned.set(material, null);\n assign(material, null);\n }\n }\n const settled = Promise.allSettled(rebuilds);\n for (const entry of retiring) {\n entry.lite.dispose(settled);\n }\n retiring.length = 0;\n }\n if (retiringSets.length > 0) {\n // A material still on a retired set was reassigned this frame or is gone from the scene.\n for (const [material, binding] of assigned) {\n if (binding !== null && \"set\" in binding && retiringSets.includes(binding)) {\n assigned.set(material, null);\n assign(material, null);\n }\n }\n const settled = Promise.allSettled(rebuilds);\n for (const set of retiringSets) {\n set.dispose(settled);\n }\n retiringSets.length = 0;\n }\n };\n\n /** Stops blending; the set goes once the materials that used it were rebuilt. */\n const dropBlend = (): void => {\n if (blend !== null) {\n retiringSets.push(blend.lite);\n blend = null;\n }\n };\n\n /**\n * Builds, keeps or drops the blended set for this frame's candidates.\n *\n * @param layout - The blend layout, or `null` when the probes do not blend.\n */\n const updateBlend = (layout: ReflectionProbeBlendLayout | null): void => {\n if (layout === null) {\n dropBlend();\n refusedKey = null;\n return;\n }\n let isCapturing = false;\n let hasEveryFrame = false;\n let isMoving = false;\n for (const volume of layout.volumes) {\n const candidate = candidates[volume.index];\n isCapturing ||= candidate?.isCapturing === true;\n hasEveryFrame ||= candidate?.isEveryFrame === true;\n isMoving ||= candidate?.isMoving === true;\n }\n if (hasEveryFrame || isMoving) {\n // A probe capturing every frame would leave any set stale at once; one being moved would\n // rebuild it every frame. Both take the nearest-probe choice until that stops.\n dropBlend();\n return;\n }\n if (isCapturing) {\n return;\n }\n const key: unknown[] = [];\n const volumes = layout.volumes.map((volume) => {\n const candidate = candidates[volume.index];\n if (candidate !== undefined) {\n key.push(candidate.binding, candidate.generation, candidate.blendDistance);\n }\n return {\n environment: candidate?.binding.environment ?? null,\n position: volume.position,\n outer: volume.outer,\n inner: volume.inner,\n };\n });\n if (sameKey(blend?.key ?? null, key) || sameKey(refusedKey, key)) {\n return;\n }\n const ready = volumes.filter(\n (volume): volume is typeof volume & { environment: NonNullable<typeof volume.environment> } =>\n volume.environment !== null,\n );\n try {\n const created = createLiteProbeSet(\n engine,\n scene,\n ready,\n layout.minimum,\n layout.maximum,\n layout.cellSize,\n warnLeakOnce,\n );\n dropBlend();\n blend = { lite: created, key };\n refusedKey = null;\n } catch (error) {\n dropBlend();\n refusedKey = key;\n if (!hasWarnedRefusal) {\n hasWarnedRefusal = true;\n warn(\n `The reflection probes cannot blend (${error instanceof Error ? error.message : String(error)}), ` +\n \"so each material reflects its nearest probe. Lite blends at most four overlapping probes.\",\n );\n }\n }\n };\n\n /** Hands every material back to the scene environment, without walking the scene. */\n const clearMaterials = (): void => {\n for (const [material, binding] of assigned) {\n if (binding !== null) {\n assign(material, null);\n }\n }\n assigned.clear();\n };\n\n const assignMaterials = (): void => {\n if (candidates.length === 0) {\n clearMaterials();\n return;\n }\n seen.clear();\n const blended = blend?.lite ?? null;\n forEachReflectiveMesh(scene, (material, x, y, z) => {\n if (seen.has(material)) {\n return;\n }\n seen.add(material);\n // A material whose nearest probe has no box keeps it: such probes are not in the set.\n const chosen = candidates[selectReflectionProbe(x, y, z, candidates)];\n const binding = blended !== null && chosen?.box !== null ? blended : (chosen?.binding ?? null);\n const current = assigned.get(material);\n if (current === binding || (current === undefined && binding === null)) {\n return;\n }\n assigned.set(material, binding);\n assign(material, binding);\n });\n };\n\n return {\n update(\n world: World,\n probes: readonly ReflectionProbe[],\n isHdr: boolean,\n tier: RenderingQualityPreset | null,\n hasEnvironment: boolean,\n ): void {\n if (isDeviceLost) {\n return;\n }\n candidates.length = 0;\n if (!hasEnvironment) {\n // A probe borrows the environment's lighting tables, so without one it holds no GPU memory\n // and costs no frame work; refresh requests stay on the component until it can capture.\n for (const [probe, state] of states) {\n release(probe, state);\n }\n dropBlend();\n clearMaterials();\n retire();\n return;\n }\n const maxSize = tier?.reflectionProbeMaxSize;\n const allowsEveryFrame = tier?.reflectionProbeEveryFrame ?? true;\n for (const [probe, state] of states) {\n if (!probes.includes(probe) || resolveReflectionProbeSize(probe.size, maxSize) !== state.lite.size) {\n release(probe, state);\n }\n }\n for (const probe of probes) {\n const wantsRefresh = probe.consumeRefreshRequest();\n if (!probe.isEnabledInHierarchy) {\n continue;\n }\n const mode = resolveReflectionProbeRefreshMode(probe.refreshMode, allowsEveryFrame);\n if (mode !== probe.refreshMode && !hasWarnedEveryFrame) {\n hasWarnedEveryFrame = true;\n warn(\n `${JSON.stringify(probe.entity.name)} asks its ReflectionProbe for refreshMode \"everyFrame\", ` +\n 'which only the \"high\" rendering.quality tier allows, so it captures as \"once\" (when ready ' +\n \"and on refresh()).\",\n );\n }\n let state = states.get(probe);\n if (state === undefined) {\n // Nothing is allocated until a capture is due: an `onDemand` probe waits for refresh().\n if (mode === \"onDemand\" && !wantsRefresh && !recapture.has(probe)) {\n continue;\n }\n recapture.delete(probe);\n state = {\n lite: createLiteReflectionProbe(\n engine,\n scene,\n resolveReflectionProbeSize(probe.size, maxSize),\n EDITOR_ONLY_METADATA_KEY,\n cullingFilter(world, probe),\n ),\n framesToCapture: CAPTURE_FRAMES,\n binding: null,\n generation: 0,\n blendDistance: probe.blendDistance,\n stillFrames: 0,\n };\n states.set(probe, state);\n }\n state.lite.resolve(!isHdr);\n const matrix = probe.entity.transform.worldMatrix;\n const x = matrix[12] ?? 0;\n const y = matrix[13] ?? 0;\n const z = matrix[14] ?? 0;\n if (wantsRefresh) {\n state.framesToCapture = CAPTURE_FRAMES;\n }\n const isCapturing = state.framesToCapture > 0 || mode === \"everyFrame\";\n if (isCapturing && state.lite.capture(x, y, z, probe.near, probe.far)) {\n state.framesToCapture = Math.max(0, state.framesToCapture - 1);\n state.generation += 1;\n }\n const environment = state.lite.environment;\n if (environment === null) {\n continue;\n }\n const box = probe.boxProjection;\n const binding = bindingFor(state.binding, environment, x, y, z, box);\n state.stillFrames =\n binding === state.binding && probe.blendDistance === state.blendDistance ? state.stillFrames + 1 : 0;\n state.binding = binding;\n state.blendDistance = probe.blendDistance;\n candidates.push({\n x,\n y,\n z,\n box,\n binding,\n blendDistance: probe.blendDistance,\n generation: state.generation,\n isCapturing: state.framesToCapture > 0,\n isEveryFrame: mode === \"everyFrame\",\n isMoving: state.stillFrames < BLEND_STILL_FRAMES,\n });\n }\n updateBlend(mayBlend(candidates) ? reflectionProbeBlendLayout(candidates) : null);\n assignMaterials();\n retire();\n },\n handleDeviceLost(): void {\n isDeviceLost = true;\n // The set's copies belong to the lost device; Lite would otherwise recopy from dead cubes.\n blend?.lite.dispose();\n blend = null;\n refusedKey = null;\n for (const set of retiringSets) {\n set.dispose();\n }\n retiringSets.length = 0;\n // Lite's recovery rebuilds every material against the new device, so only the bindings are\n // cleared here; the cubes belong to the lost device and go at once.\n for (const [material, binding] of assigned) {\n if (binding !== null) {\n void assignReflectionProbe(null, material, null);\n }\n }\n assigned.clear();\n for (const [probe, state] of states) {\n if (state.lite.environment !== null || state.framesToCapture > 0) {\n recapture.add(probe);\n }\n state.lite.dispose();\n }\n states.clear();\n // The retired cubes belonged to the lost device too.\n for (const entry of retiring) {\n entry.lite.dispose();\n }\n retiring.length = 0;\n rebuilds.clear();\n },\n handleDeviceRecovered(): void {\n isDeviceLost = false;\n },\n dispose(): void {\n for (const [probe, state] of states) {\n release(probe, state);\n }\n dropBlend();\n clearMaterials();\n const settled = Promise.allSettled(rebuilds);\n for (const entry of retiring) {\n entry.lite.dispose(settled);\n }\n retiring.length = 0;\n for (const set of retiringSets) {\n set.dispose(settled);\n }\n retiringSets.length = 0;\n rebuilds.clear();\n },\n };\n}\n\n/**\n * Whether a frame's probes can blend at all, checked without allocating: two box probes, one with a\n * `blendDistance`.\n *\n * @param candidates - The frame's candidates.\n * @returns `true` when {@link reflectionProbeBlendLayout} is worth calling.\n */\nfunction mayBlend(candidates: readonly BoundCandidate[]): boolean {\n let boxes = 0;\n let blends = false;\n for (const candidate of candidates) {\n if (candidate.box !== null) {\n boxes += 1;\n blends ||= candidate.blendDistance > 0;\n }\n }\n return boxes >= 2 && blends;\n}\n\n/**\n * Whether two set keys are equal, element by element.\n *\n * @param a - A key, or `null`.\n * @param b - Another key.\n * @returns `true` when both have the same elements.\n */\nfunction sameKey(a: readonly unknown[] | null, b: readonly unknown[]): boolean {\n return a !== null && a.length === b.length && a.every((value, index) => value === b[index]);\n}\n\n/**\n * Builds the mesh filter of a probe's capture: with a non-empty `cullingMask`, only meshes whose\n * entity is on one of its layers.\n *\n * @param world - The world, for the handle and layer tables.\n * @param probe - The probe; its mask is read on every call, so edits apply to the next capture.\n * @returns The filter.\n */\nfunction cullingFilter(world: World, probe: ReflectionProbe): (tag: NodeTag | null) => boolean {\n return (tag): boolean => {\n const mask = probe.cullingMask;\n if (mask.length === 0) {\n return true;\n }\n const entity = tag === null ? null : world.getEntityByHandle(toEntityHandle(tag.entity));\n if (entity === null) {\n return false;\n }\n for (const name of mask) {\n if (world.layers.indexOf(name) === entity.layer) {\n return true;\n }\n }\n return false;\n };\n}\n\n/**\n * The binding a probe's materials use: the previous one while nothing it holds changed, so a still\n * probe never rebuilds its materials.\n *\n * @param previous - The binding last used, or `null`.\n * @param environment - The probe's environment.\n * @param x - The probe's world X.\n * @param y - The probe's world Y.\n * @param z - The probe's world Z.\n * @param box - The projection box size, or `null`.\n * @returns The binding.\n */\nfunction bindingFor(\n previous: LiteProbeBinding | null,\n environment: LiteProbeBinding[\"environment\"],\n x: number,\n y: number,\n z: number,\n box: Vec3Like | null,\n): LiteProbeBinding {\n if (\n previous !== null &&\n previous.environment === environment &&\n previous.position[0] === x &&\n previous.position[1] === y &&\n previous.position[2] === z &&\n (box === null\n ? previous.box === null\n : previous.box !== null && previous.box[0] === box.x && previous.box[1] === box.y && previous.box[2] === box.z)\n ) {\n return previous;\n }\n return { environment, position: [x, y, z], box: box === null ? null : [box.x, box.y, box.z] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,MAAM,eAAiC;;AAGvC,MAAM,uBAAyC;;AAG/C,MA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MAAM,OAAO,MAAM;EACnB,IAAI,KAAK,WAAW,GAClB,OAAO;EAET,MAAM,SAAS,QAAQ,OAAO,OAAO,MAAM,kBAAkB,eAAe,IAAI,MAAM,CAAC;EACvF,IAAI,WAAW,MACb,OAAO;EAET,KAAK,MAAM,QAAQ,MACjB,IAAI,MAAM,OAAO,QAAQ,IAAI,MAAM,OAAO,OACxC,OAAO;EAGX,OAAO;CACT;AACF;;;;;;;;;;;;;AAcA,SAAS,WACP,UACA,aACA,GACA,GACA,GACA,KACkB;CAClB,IACE,aAAa,QACb,SAAS,gBAAgB,eACzB,SAAS,SAAS,OAAO,KACzB,SAAS,SAAS,OAAO,KACzB,SAAS,SAAS,OAAO,MACxB,QAAQ,OACL,SAAS,QAAQ,OACjB,SAAS,QAAQ,QAAQ,SAAS,IAAI,OAAO,IAAI,KAAK,SAAS,IAAI,OAAO,IAAI,KAAK,SAAS,IAAI,OAAO,IAAI,IAE/G,OAAO;CAET,OAAO;EAAE;EAAa,UAAU;GAAC;GAAG;GAAG;EAAC;EAAG,KAAK,QAAQ,OAAO,OAAO;GAAC,IAAI;GAAG,IAAI;GAAG,IAAI;EAAC;CAAE;AAC9F"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"render-path-D11i_7X8.js","names":[],"sources":["../src/lite/gpu/render-path.ts"],"sourcesContent":["import { addTask, createCopyToTextureTask, createRenderTarget, createRenderTask } from \"@babylonjs/lite\";\nimport type {\n EngineContext,\n RenderTarget,\n RenderTargetTextureResult,\n SceneContext,\n Task,\n Texture2D,\n} 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/**\n * The depth/stencil format Lite's own default render task uses (`lib/scene/scene-core.js` 76-77).\n *\n * @internal\n */\nexport const DEPTH_STENCIL_FORMAT: GPUTextureFormat = \"depth24plus-stencil8\";\n\n/**\n * The HDR half of a presenter, when `rendering.hdr` built one (`./hdr-output.ts`).\n *\n * @internal\n */\nexport interface HdrOutputHandle {\n /** The scene's linear `rgba16float` colour, as a sampled texture. Values may exceed 1. */\n readonly sceneTexture: Texture2D;\n /** The render target behind {@link HdrOutputHandle.sceneTexture}, for a pass that writes it back (TAA). */\n readonly sceneTarget: RenderTarget;\n /** The `\"scene\"` render task, whose scene uniforms the TAA jitter offsets. */\n readonly sceneTask: Task;\n /**\n * The auto exposure result, a 1×1 `r32float` texture holding `log2` of the multiplier the output\n * pass applies (`./auto-exposure.ts`); `null` when `rendering.autoExposure` is off.\n */\n readonly exposureTexture: Texture2D | null;\n /**\n * The same target with its sampled facade and resize hook: what HDR bloom (step G12) samples,\n * writes back into, and rebinds on resize.\n */\n readonly sceneTargetTexture: RenderTargetTextureResult;\n /**\n * The per-frame work: uploads the scene's exposure, contrast and curve when they changed, and\n * gives every new PBR material the linear-output plugin.\n *\n * @param isSceneRegistered - Whether Lite has built the scene, so a patched material needs a\n * rebuild.\n */\n update(isSceneRegistered: boolean): void;\n /**\n * Puts a task between the scene pass and the output pass, where it reads and writes linear\n * colour: a `PostProcessStack`'s custom effects ordered before any built-in one (GI plan G3).\n *\n * @param task - The task; it must write an `rgba16float` target.\n * @param isFrameGraphBuilt - Whether the scene is registered, so the task has to be recorded now.\n */\n insertLinearTask(task: Task, isFrameGraphBuilt: boolean): void;\n /**\n * Points the output pass at another linear texture, or back at the scene's.\n *\n * @param texture - The last linear effect's output, or `null` for {@link HdrOutputHandle.sceneTexture}.\n */\n setOutputSource(texture: Texture2D | null): void;\n}\n\n/** The scenes `rendering.hdr` built, created on first use so the module has no import-time work. */\nlet hdrScenes: WeakSet<SceneContext> | null = null;\n\n/**\n * Records that a scene renders through the HDR path, so code outside the HDR chunk (a custom\n * shader's build) can ask without importing it.\n *\n * @param scene - The scene `./hdr-output.ts` built a render path for.\n *\n * @internal\n */\nexport function markHdrScene(scene: SceneContext): void {\n hdrScenes ??= new WeakSet();\n hdrScenes.add(scene);\n}\n\n/**\n * Whether a scene renders through the HDR path, where every colour writer must write linear colour.\n *\n * @param scene - The scene.\n * @returns `true` once `./hdr-output.ts` has built the scene's render path.\n *\n * @internal\n */\nexport function isHdrScene(scene: SceneContext): boolean {\n return hdrScenes?.has(scene) === true;\n}\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 /** The HDR output pass, when `rendering.hdr` is on; `null` for the plain offscreen path. */\n readonly hdr: HdrOutputHandle | null;\n /**\n * The scene's render task and the single-sample colour target it ends in: {@link\n * ScenePresenter.sceneColor} on the plain path, the `rgba16float` target under `rendering.hdr`.\n * Scene-colour effects (contact shadows, SSGI) insert their tasks right after `task` and write their\n * result back into `target`, so everything downstream reads it.\n */\n readonly scenePass: ScenePass;\n}\n\n/**\n * The scene's render task and its resolved colour target.\n *\n * @internal\n */\nexport interface ScenePass {\n /** The task named `\"scene\"`. */\n readonly task: Task;\n /** The single-sample colour target the scene ends in; it carries `TEXTURE_BINDING` and `COPY_DST`. */\n readonly target: RenderTarget;\n /** That target's colour format. */\n readonly format: GPUTextureFormat;\n /**\n * Whether a post-process task may write {@link ScenePass.target} directly. `false` on the plain\n * path: its target is allocated lazily, and a post-process task that writes it reallocates it in\n * `record()` (Lite's `buildRenderTarget`, `lib/engine/render-target.js`), destroying the texture\n * the scene task and every pass recorded before it hold, so the frame is rejected and presents\n * black. The HDR target is eager and survives that.\n */\n readonly isTargetWritable: 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 const sceneTask: Task = createRenderTask(config, engine, scene);\n addTask(scene, sceneTask);\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 hdr: null,\n scenePass: { task: sceneTask, target: sceneColor, format: engine.format, isTargetWritable: false },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,uBAAyC;;AAiDtD,IAAI,YAA0C;;;;;;;;;AAU9C,SAAgB,aAAa,OAA2B;CACtD,8BAAc,IAAI,QAAQ;CAC1B,UAAU,IAAI,KAAK;AACrB;;;;;;;;;AAUA,SAAgB,WAAW,OAA8B;CACvD,OAAO,WAAW,IAAI,KAAK,MAAM;AACnC;;;;;;;;;;;;;;;;;;;;;;;AA+EA,SAAgB,2BAA2B,QAAuB,OAAqC;CACrG,MAAM,iBAAiB,OAAO,cAAc;CAC5C,MAAM,aAAa,mBAAmB;EACpC,KAAK;EACL,QAAQ,OAAO;EACf,SAAS;EACT,MAAM;CACR,CAAC;CAUD,MAAM,SAKF;EAAE,MAAM;EAAS,IAdD,iBAChB,mBAAmB;GACjB,KAAK;GACL,QAAQ,OAAO;GACf,SAAS;GACT,SAAS,OAAO;GAChB,MAAM;EACR,CAAC,IACD;CAMiC;CACrC,IAAI,gBACF,OAAO,MAAM;MAIb,OAAO,QAAQ,mBAAmB;EAChC,KAAK;EACL,SAAS;EACT,SAAS;EACT,MAAM;CACR,CAAC;CAEH,MAAM,YAAkB,iBAAiB,QAAQ,QAAQ,KAAK;CAC9D,QAAQ,OAAO,SAAS;CAExB,MAAM,UAAgB,wBACpB;EAAE,MAAM;EAAkB,eAAe;EAAY,eAAe,OAAO;CAAK,GAChF,QACA,KACF;CACA,QAAQ,OAAO,OAAO;CAEtB,IAAI,mBAAmB;CACvB,OAAO;EACL;EACA,WAAW,OAAO;EAClB,kBAAkB,SAAwB;GACxC,mBAAmB;GACnB,QAAQ,mBAAmB;EAC7B;EACA,IAAI,mBAA4B;GAC9B,OAAO;EACT;EACA,KAAK;EACL,WAAW;GAAE,MAAM;GAAW,QAAQ;GAAY,QAAQ,OAAO;GAAQ,kBAAkB;EAAM;CACnG;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scene-color-passes-B93qTOka.js","names":[],"sources":["../src/lite/gpu/scene-color-passes.ts"],"sourcesContent":["import {\n addTaskAfter,\n buildFrameGraphTask,\n createCopyToTextureTask,\n createRenderTarget,\n disposeRenderTarget,\n getFrameGraph,\n} from \"@babylonjs/lite\";\nimport { frameGraphTasks } from \"./scene-inputs.js\";\nimport type { ScenePresenter } from \"./render-path.js\";\nimport type { EngineContext, RenderTarget, SceneContext, Task } from \"@babylonjs/lite\";\n\n/**\n * Scene-colour passes (`docs/architecture/07-rendering.md` §2.7, GI plan steps G10 and G11): Lite\n * screen-space effects that read the lit scene colour and the shared scene-input depth, and whose\n * result replaces the scene colour before anything else reads it. Its own chunk, loaded with the\n * first such effect (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * scene ─→ S ─ pass 1 ─→ scratch ─ pass 2 ─→ S ─ … [─ copy ─→ S] ─→ present / output pass / chain\n * ```\n *\n * `S` is the presenter's {@link ScenePresenter.scenePass} target: `sceneColor` on the plain path,\n * the linear `rgba16float` target under `rendering.hdr`, so the passes see linear colour ahead of\n * the output pass there. Lite's composite cannot write its own source, so under HDR the passes\n * ping-pong between `S` and one scratch target of the same format, and a copy brings an odd count\n * back into `S`. On the plain path no pass may write `S` (`ScenePass.isTargetWritable` in `./render-path.ts`): the\n * passes ping-pong between two scratch targets and the copy always runs. Every task sits right after\n * the scene task, ahead of the present blit, the HDR output pass and a `PostProcessStack` chain\n * alike, which therefore need no change.\n */\n\n/**\n * One scene-colour effect, as the installer sees it.\n *\n * @internal\n */\nexport interface SceneColorPass {\n /**\n * Creates the effect's task.\n *\n * @param source - The colour it reads.\n * @param target - The colour it writes; never `source`.\n * @returns The task.\n */\n create(source: RenderTarget, target: RenderTarget): Task;\n}\n\n/**\n * The installed passes.\n *\n * @internal\n */\nexport interface InstalledSceneColorPasses {\n /** How many tasks were added, copy included. */\n readonly taskCount: number;\n /** Removes and disposes every task and the scratch target. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Inserts the passes after the scene task, in order.\n *\n * @param engine - The engine; also the surface the scratch target is sized by.\n * @param scene - The scene.\n * @param presenter - The offscreen render path.\n * @param passes - The effects, first to last.\n * @param isFrameGraphBuilt - Whether the scene is registered, so each task is recorded now.\n * @returns The handle that takes them out again.\n *\n * @internal\n */\nexport function installSceneColorPasses(\n engine: EngineContext,\n scene: SceneContext,\n presenter: ScenePresenter,\n passes: readonly SceneColorPass[],\n isFrameGraphBuilt: boolean,\n): InstalledSceneColorPasses {\n const { task: sceneTask, target: sceneTarget, format, isTargetWritable } = presenter.scenePass;\n const scratches: RenderTarget[] = [];\n const tasks: Task[] = [];\n let source = sceneTarget;\n for (const pass of passes) {\n const target = sceneColorPassTarget(source, sceneTarget, isTargetWritable, scratches, (index) =>\n createRenderTarget({\n lbl: index === 0 ? \"ignifx:scene-color-scratch\" : \"ignifx:scene-color-scratch-2\",\n format,\n samples: 1,\n size: engine,\n }),\n );\n tasks.push(pass.create(source, target));\n source = target;\n }\n if (source !== sceneTarget) {\n tasks.push(\n createCopyToTextureTask(\n { name: \"ignifx:scene-color-copy\", sourceTexture: source, targetTexture: sceneTarget },\n engine,\n scene,\n ),\n );\n }\n let after = sceneTask;\n for (const task of tasks) {\n addTaskAfter(scene, task, after);\n after = task;\n }\n if (isFrameGraphBuilt) {\n const graph = getFrameGraph(scene);\n for (const task of tasks) {\n buildFrameGraphTask(graph, task);\n }\n }\n let isDisposed = false;\n return {\n taskCount: tasks.length,\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n const list = frameGraphTasks(scene);\n for (const task of tasks) {\n // Disable first: a disposed task that still executes is a use-after-free.\n task.executionEnabled = false;\n const index = list?.indexOf(task) ?? -1;\n if (list !== null && index >= 0) {\n list.splice(index, 1);\n }\n task.dispose();\n }\n for (const scratch of scratches) {\n disposeRenderTarget(scratch);\n }\n },\n };\n}\n\n/**\n * Picks where the next scene-colour pass writes: back into the scene target when that is allowed\n * and the pass does not read it, otherwise the scratch target the pass does not read.\n *\n * @param source - What the pass reads.\n * @param sceneTarget - The scene's colour target.\n * @param isTargetWritable - Whether a pass may write `sceneTarget` (`ScenePass.isTargetWritable` in `./render-path.ts`).\n * @param scratches - The scratch targets made so far; a new one is appended when needed.\n * @param createScratch - Makes the scratch target at an index, 0 or 1.\n * @returns The target, never `source`.\n *\n * @internal\n */\nexport function sceneColorPassTarget<T>(\n source: T,\n sceneTarget: T,\n isTargetWritable: boolean,\n scratches: T[],\n createScratch: (index: number) => T,\n): T {\n if (source !== sceneTarget && isTargetWritable) {\n return sceneTarget;\n }\n const index = source === scratches[0] ? 1 : 0;\n let scratch = scratches[index];\n if (scratch === undefined) {\n scratch = createScratch(index);\n scratches[index] = scratch;\n }\n return scratch;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwEA,SAAgB,wBACd,QACA,OACA,WACA,QACA,mBAC2B;CAC3B,MAAM,EAAE,MAAM,WAAW,QAAQ,aAAa,QAAQ,qBAAqB,UAAU;CACrF,MAAM,YAA4B,CAAC;CACnC,MAAM,QAAgB,CAAC;CACvB,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,SAAS,qBAAqB,QAAQ,aAAa,kBAAkB,YAAY,UACrF,mBAAmB;GACjB,KAAK,UAAU,IAAI,+BAA+B;GAClD;GACA,SAAS;GACT,MAAM;EACR,CAAC,CACH;EACA,MAAM,KAAK,KAAK,OAAO,QAAQ,MAAM,CAAC;EACtC,SAAS;CACX;CACA,IAAI,WAAW,aACb,MAAM,KACJ,wBACE;EAAE,MAAM;EAA2B,eAAe;EAAQ,eAAe;CAAY,GACrF,QACA,KACF,CACF;CAEF,IAAI,QAAQ;CACZ,KAAK,MAAM,QAAQ,OAAO;EACxB,aAAa,OAAO,MAAM,KAAK;EAC/B,QAAQ;CACV;CACA,IAAI,mBAAmB;EACrB,MAAM,QAAQ,cAAc,KAAK;EACjC,KAAK,MAAM,QAAQ,OACjB,oBAAoB,OAAO,IAAI;CAEnC;CACA,IAAI,aAAa;CACjB,OAAO;EACL,WAAW,MAAM;EACjB,UAAgB;GACd,IAAI,YACF;GAEF,aAAa;GACb,MAAM,OAAO,gBAAgB,KAAK;GAClC,KAAK,MAAM,QAAQ,OAAO;IAExB,KAAK,mBAAmB;IACxB,MAAM,QAAQ,MAAM,QAAQ,IAAI,KAAK;IACrC,IAAI,SAAS,QAAQ,SAAS,GAC5B,KAAK,OAAO,OAAO,CAAC;IAEtB,KAAK,QAAQ;GACf;GACA,KAAK,MAAM,WAAW,WACpB,oBAAoB,OAAO;EAE/B;CACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,qBACd,QACA,aACA,kBACA,WACA,eACG;CACH,IAAI,WAAW,eAAe,kBAC5B,OAAO;CAET,MAAM,QAAQ,WAAW,UAAU,KAAK,IAAI;CAC5C,IAAI,UAAU,UAAU;CACxB,IAAI,YAAY,KAAA,GAAW;EACzB,UAAU,cAAc,KAAK;EAC7B,UAAU,SAAS;CACrB;CACA,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scene-inputs-BxGOsnIZ.js","names":[],"sources":["../src/lite/gpu/scene-inputs.ts"],"sourcesContent":["import {\n addTaskAfter,\n addTaskAtStart,\n buildFrameGraphTask,\n createCopyToTextureTask,\n createDepthPyramid,\n createDepthPyramidTask,\n createGeometryRendererTask,\n createSurfaceRenderTargetTexture,\n disposeRenderTargetTexture,\n GeometryTextureType,\n getFrameGraph,\n onRenderTargetTextureResize,\n withSampledDepthTexture,\n} from \"@babylonjs/lite\";\nimport type {\n DepthPyramid,\n EngineContext,\n RenderTarget,\n RenderTargetTextureResult,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * Shared scene inputs (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G4;\n * `docs/architecture/07-rendering.md` §2.12): one geometry pass that screen-space effects (TAA, GTAO,\n * contact shadows, SSGI) read instead of each drawing the scene again. Its own chunk: the renderer\n * imports it only when an effect asks for it, so a project with no such effect loads none of it and\n * its frame graph has none of these tasks (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * [shadow] → geometry ─→ normals copy ─→ velocity copy ─→ depth pyramid → scene → …\n * ├ depth (depth32float, sampled)\n * ├ world normal ─(copy)─→ normals\n * └ velocity ─(copy)─→ velocity\n * ```\n *\n * - **Depth** is a surface-sized `depth32float` target with a sampled facade\n * (`withSampledDepthTexture`) handed to the geometry task as its depth (spike S2). Reverse-Z: 0 is\n * the far plane. `depth24plus-stencil8`, the main pass's format, cannot be bound in compute.\n * - **Normals and velocity** are geometry attachments, which Lite exposes only as task-owned\n * `RenderTarget`s; compute and effect bindings take a `Texture2D`, so each is copied into a target\n * that has one (spike S2, upstream ask 3).\n * - **The depth pyramid** is Lite's `createDepthPyramid`: an `r32float` mip chain where each level\n * keeps the `max` (in reverse-Z, the nearest surface) of its four children.\n * - **Ref-counted.** {@link SceneInputsHost.acquire} adds the tasks for the first user;\n * {@link SceneInputs.release} by the last one removes and disposes them.\n * - **Resize and device loss.** The targets are sized by the surface, so `frameGraph.build()`\n * reallocates them, on a resize and on a recovered device alike. The depth target's resize\n * callback rebuilds the pyramid (its pipelines belong to one device) and tells every user through\n * {@link SceneInputs.onChange}, so they can rebind.\n */\n\n/**\n * The frame-graph task names, in the order they run.\n *\n * @internal\n */\nexport const SCENE_INPUT_TASK_NAMES = {\n geometry: \"ignifx:scene-inputs\",\n normals: \"ignifx:scene-inputs-normals\",\n velocity: \"ignifx:scene-inputs-velocity\",\n depthPyramid: \"ignifx:scene-inputs-depth-pyramid\",\n} as const;\n\n/**\n * The texture format of each input.\n *\n * @internal\n */\nexport const SCENE_INPUT_FORMATS: {\n readonly depth: \"depth32float\";\n readonly normals: \"rgba16float\";\n readonly velocity: \"rgba16float\";\n readonly depthPyramid: \"r32float\";\n} = { depth: \"depth32float\", normals: \"rgba16float\", velocity: \"rgba16float\", depthPyramid: \"r32float\" };\n\n/**\n * One user's lease on the shared scene inputs.\n *\n * @remarks\n * Every texture is sized like the surface (backing-store pixels) and holds this frame's values for\n * any task that runs after the inputs' tasks, which sit at the start of the frame graph. A resize or\n * a recovered device swaps the GPU textures behind the same objects; bind groups that captured a\n * view must be rebuilt in {@link SceneInputs.onChange}.\n *\n * @internal\n */\nexport interface SceneInputs {\n /** Scene depth, `depth32float`, reverse-Z (1 near, 0 far). Bind with `sampleType: \"depth\"`. */\n readonly depth: Texture2D;\n /**\n * The same depth as the single-sample `RenderTarget` it lives in, for Lite tasks that take a\n * `depthTexture` target (contact shadows, SSGI).\n */\n readonly depthTarget: RenderTarget;\n /** World-space normals, `rgba16float`, stored as `n * 0.5 + 0.5`; 0 where nothing was drawn. */\n readonly normals: Texture2D;\n /**\n * Screen-space motion, `rgba16float`: `xy = 0.5 * (previousNdc - currentNdc)`, so UV units with Y\n * up, pointing from where a pixel is now to where it was last frame; 0 where nothing was drawn.\n * Camera motion always counts. Object motion counts for Standard materials only: Lite 1.34's PBR\n * geometry view reprojects the current world position (`pbr-geometry-output-shader.js` line 41),\n * so a moving PBR mesh under a still camera reads 0.\n */\n readonly velocity: Texture2D;\n /**\n * The depth pyramid, `r32float`, every mip level; level `n` is the `max` of its four children in\n * level `n - 1`. Read with `textureLoad(tex, coord, mip)`. A resize or recovered device replaces\n * this object, so read it again after {@link SceneInputs.onChange}.\n */\n readonly depthPyramid: Texture2D;\n /** How many mip levels {@link SceneInputs.depthPyramid} has. */\n readonly depthPyramidMipCount: number;\n /** `true` once {@link SceneInputs.release} ran. */\n readonly isReleased: boolean;\n /**\n * Registers a callback for when the textures were reallocated (resize, recovered device).\n *\n * @param callback - Runs during the frame graph rebuild, before the next frame is recorded.\n * @returns A function that unregisters it.\n */\n onChange(callback: () => void): () => void;\n /** Ends this lease. The last release removes and disposes the tasks and targets. Idempotent. */\n release(): void;\n}\n\n/**\n * The per-scene owner of the shared inputs: one per renderer.\n *\n * @internal\n */\nexport interface SceneInputsHost {\n /**\n * Leases the inputs, creating the geometry pass for the first user.\n *\n * @param isFrameGraphBuilt - Whether the scene is registered, so new tasks must be recorded now;\n * before registration `registerScene` records them.\n * @returns A lease; call its `release()` when done. `null` once the host is disposed.\n */\n acquire(isFrameGraphBuilt: boolean): SceneInputs | null;\n /** How many leases are live. */\n readonly userCount: number;\n /** Ends every lease and frees everything. Idempotent. */\n dispose(): void;\n}\n\n/** What the first acquire builds and the last release frees. */\ninterface SharedInputs {\n readonly depth: RenderTargetTextureResult;\n readonly normals: RenderTargetTextureResult;\n readonly velocity: RenderTargetTextureResult;\n readonly tasks: readonly Task[];\n readonly pyramid: { current: DepthPyramid };\n readonly listeners: Set<() => void>;\n readonly stopResizeWatch: () => void;\n}\n\n/**\n * Creates the scene-inputs owner for one scene. It adds nothing to the frame graph until the first\n * {@link SceneInputsHost.acquire}.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The render scene.\n * @returns The host.\n *\n * @internal\n */\nexport function createSceneInputsHost(engine: EngineContext, scene: SceneContext): SceneInputsHost {\n let shared: SharedInputs | null = null;\n const leases = new Set<SceneInputs>();\n let isDisposed = false;\n\n const releaseLease = (lease: SceneInputs): void => {\n if (!leases.delete(lease) || leases.size > 0 || shared === null) {\n return;\n }\n teardown(scene, shared);\n shared = null;\n };\n\n return {\n acquire(isFrameGraphBuilt: boolean): SceneInputs | null {\n if (isDisposed) {\n return null;\n }\n shared ??= buildSharedInputs(engine, scene, isFrameGraphBuilt);\n const inputs = shared;\n let isReleased = false;\n const own = new Set<() => void>();\n const lease: SceneInputs = {\n depth: requireDepthFacade(inputs.depth),\n depthTarget: inputs.depth.rt,\n normals: inputs.normals.texture,\n velocity: inputs.velocity.texture,\n get depthPyramid(): Texture2D {\n return inputs.pyramid.current.texture;\n },\n get depthPyramidMipCount(): number {\n return inputs.pyramid.current.mipCount;\n },\n get isReleased(): boolean {\n return isReleased;\n },\n onChange(callback: () => void): () => void {\n inputs.listeners.add(callback);\n own.add(callback);\n return (): void => {\n inputs.listeners.delete(callback);\n own.delete(callback);\n };\n },\n release(): void {\n if (isReleased) {\n return;\n }\n isReleased = true;\n for (const callback of own) {\n inputs.listeners.delete(callback);\n }\n own.clear();\n releaseLease(lease);\n },\n };\n leases.add(lease);\n return lease;\n },\n get userCount(): number {\n return leases.size;\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n for (const lease of leases) {\n lease.release();\n }\n },\n };\n}\n\n/**\n * Builds the targets and tasks, and splices the tasks into the frame graph ahead of the scene pass.\n *\n * @param engine - The engine.\n * @param scene - The scene.\n * @param isFrameGraphBuilt - Whether each task must be recorded now.\n * @returns The shared state.\n */\nfunction buildSharedInputs(engine: EngineContext, scene: SceneContext, isFrameGraphBuilt: boolean): SharedInputs {\n const depth = createSurfaceRenderTargetTexture(\n engine,\n { lbl: \"ignifx:scene-inputs-depth\", dFormat: SCENE_INPUT_FORMATS.depth, samples: 1, size: engine },\n withSampledDepthTexture,\n );\n const normals = createSurfaceRenderTargetTexture(engine, {\n lbl: \"ignifx:scene-inputs-normals\",\n format: SCENE_INPUT_FORMATS.normals,\n samples: 1,\n size: engine,\n });\n const velocity = createSurfaceRenderTargetTexture(engine, {\n lbl: \"ignifx:scene-inputs-velocity\",\n format: SCENE_INPUT_FORMATS.velocity,\n samples: 1,\n size: engine,\n });\n const geometry = createGeometryRendererTask(\n {\n name: SCENE_INPUT_TASK_NAMES.geometry,\n size: engine,\n depthTexture: depth.rt,\n textureDescriptions: [\n { type: GeometryTextureType.WORLD_NORMAL, format: SCENE_INPUT_FORMATS.normals },\n { type: GeometryTextureType.LINEAR_VELOCITY, format: SCENE_INPUT_FORMATS.velocity },\n ],\n },\n engine,\n scene,\n );\n const copyNormals = createCopyToTextureTask(\n {\n name: SCENE_INPUT_TASK_NAMES.normals,\n sourceTexture: requireAttachment(geometry.geometryWorldNormalTexture, \"world normal\"),\n targetTexture: normals.rt,\n },\n engine,\n scene,\n );\n const copyVelocity = createCopyToTextureTask(\n {\n name: SCENE_INPUT_TASK_NAMES.velocity,\n sourceTexture: requireAttachment(geometry.geometryLinearVelocityTexture, \"linear velocity\"),\n targetTexture: velocity.rt,\n },\n engine,\n scene,\n );\n const depthFacade = requireDepthFacade(depth);\n const pyramid = { current: newPyramid(engine, depthFacade) };\n // The pyramid task adopts what it is given and disposes it with the graph; a forwarding object\n // lets the inner pyramid be replaced after a resize or a recovered device.\n const forward: DepthPyramid = {\n get texture(): Texture2D {\n return pyramid.current.texture;\n },\n get mipCount(): number {\n return pyramid.current.mipCount;\n },\n build(source: Texture2D, encoder?: GPUCommandEncoder): void {\n pyramid.current.build(source, encoder);\n },\n resize(width: number, height: number): void {\n pyramid.current.resize(width, height);\n },\n dispose(): void {\n pyramid.current.dispose();\n },\n };\n const buildPyramid = createDepthPyramidTask(engine, scene, { pyramid: forward, source: () => depthFacade });\n Reflect.set(buildPyramid, \"name\", SCENE_INPUT_TASK_NAMES.depthPyramid);\n\n const tasks: readonly Task[] = [geometry, copyNormals, copyVelocity, buildPyramid];\n addTaskAtStart(scene, geometry);\n addTaskAfter(scene, copyNormals, geometry);\n addTaskAfter(scene, copyVelocity, copyNormals);\n addTaskAfter(scene, buildPyramid, copyVelocity);\n if (isFrameGraphBuilt) {\n const graph = getFrameGraph(scene);\n for (const task of tasks) {\n buildFrameGraphTask(graph, task);\n }\n }\n\n const listeners = new Set<() => void>();\n const stopResizeWatch = onRenderTargetTextureResize(depth, () => {\n pyramid.current.dispose();\n pyramid.current = newPyramid(engine, depthFacade);\n for (const listener of listeners) {\n listener();\n }\n });\n return { depth, normals, velocity, tasks, pyramid, listeners, stopResizeWatch };\n}\n\n/**\n * Removes the tasks from the frame graph and frees every task and target.\n *\n * @param scene - The scene.\n * @param shared - What {@link buildSharedInputs} built.\n */\nfunction teardown(scene: SceneContext, shared: SharedInputs): void {\n shared.stopResizeWatch();\n shared.listeners.clear();\n for (const task of shared.tasks) {\n // Disable first: a disposed task that still executes is a use-after-free.\n task.executionEnabled = false;\n removeFrameGraphTask(scene, task);\n task.dispose();\n }\n disposeRenderTargetTexture(shared.depth);\n disposeRenderTargetTexture(shared.normals);\n disposeRenderTargetTexture(shared.velocity);\n}\n\n/**\n * Takes a task out of the scene's frame graph.\n *\n * @remarks\n * Lite 1.34 has no public remove (`index.d.ts` 206–217 add only), and a disposed task left in the\n * graph is recorded again by the next `frameGraph.build()` against freed targets. The task list is\n * the private `_tasks` array every `addTask*` splices (`lib/frame-graph/frame-graph-actions.js`).\n * If a later Lite renames it, the task stays in, disabled.\n *\n * @param scene - The scene.\n * @param task - The task to remove.\n */\nfunction removeFrameGraphTask(scene: SceneContext, task: Task): void {\n const tasks = frameGraphTasks(scene);\n const index = tasks?.indexOf(task) ?? -1;\n if (tasks !== null && index >= 0) {\n tasks.splice(index, 1);\n }\n}\n\n/**\n * The scene's frame-graph task list, or `null` when Lite no longer exposes it.\n *\n * @param scene - The scene.\n * @returns The live array (Lite's own), or `null`.\n *\n * @internal\n */\nexport function frameGraphTasks(scene: SceneContext): Task[] | null {\n const tasks: unknown = Reflect.get(getFrameGraph(scene), \"_tasks\");\n return isTaskList(tasks) ? tasks : null;\n}\n\n/**\n * Whether a value is Lite's task array.\n *\n * @param value - The value read from the frame graph.\n * @returns `true` for an array.\n */\nfunction isTaskList(value: unknown): value is Task[] {\n return Array.isArray(value);\n}\n\n/**\n * Creates a depth pyramid the size of the depth facade's current texture.\n *\n * @param engine - The engine, whose current device owns the pipelines.\n * @param depth - The depth facade.\n * @returns The pyramid.\n */\nfunction newPyramid(engine: EngineContext, depth: Texture2D): DepthPyramid {\n return createDepthPyramid(engine, { width: depth.width, height: depth.height, reduce: \"max\" });\n}\n\n/**\n * The sampled depth facade of the depth target.\n *\n * @param depth - The depth target, created with `withSampledDepthTexture`.\n * @returns The facade.\n */\nfunction requireDepthFacade(depth: RenderTargetTextureResult): Texture2D {\n if (depth.depthTexture === null) {\n throw new Error(\"Lite built the scene-inputs depth target without a sampled depth facade.\");\n }\n return depth.depthTexture;\n}\n\n/**\n * A geometry attachment the task was asked for.\n *\n * @param target - The accessor's value.\n * @param what - The attachment, for the error.\n * @returns The attachment.\n */\nfunction requireAttachment(target: RenderTarget | null, what: string): RenderTarget {\n if (target === null) {\n throw new Error(`Lite's geometry task built no ${what} attachment.`);\n }\n return target;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAa,yBAAyB;CACpC,UAAU;CACV,SAAS;CACT,UAAU;CACV,cAAc;AAChB;;;;;;AAOA,MAAa,sBAKT;CAAE,OAAO;CAAgB,SAAS;CAAe,UAAU;CAAe,cAAc;AAAW;;;;;;;;;;;AA6FvG,SAAgB,sBAAsB,QAAuB,OAAsC;CACjG,IAAI,SAA8B;CAClC,MAAM,yBAAS,IAAI,IAAiB;CACpC,IAAI,aAAa;CAEjB,MAAM,gBAAgB,UAA6B;EACjD,IAAI,CAAC,OAAO,OAAO,KAAK,KAAK,OAAO,OAAO,KAAK,WAAW,MACzD;EAEF,SAAS,OAAO,MAAM;EACtB,SAAS;CACX;CAEA,OAAO;EACL,QAAQ,mBAAgD;GACtD,IAAI,YACF,OAAO;GAET,WAAW,kBAAkB,QAAQ,OAAO,iBAAiB;GAC7D,MAAM,SAAS;GACf,IAAI,aAAa;GACjB,MAAM,sBAAM,IAAI,IAAgB;GACh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