@ignifx/core 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/agx-tone-mapping-Cgt844j6.js +53 -0
  2. package/dist/agx-tone-mapping-Cgt844j6.js.map +1 -0
  3. package/dist/auto-exposure-uzPn0beO.js +246 -0
  4. package/dist/auto-exposure-uzPn0beO.js.map +1 -0
  5. package/dist/bloom-hdr-CLtQj-oY.js +315 -0
  6. package/dist/bloom-hdr-CLtQj-oY.js.map +1 -0
  7. package/dist/contact-shadows-T523EXaP.js +84 -0
  8. package/dist/contact-shadows-T523EXaP.js.map +1 -0
  9. package/dist/{environment-C9AjYJgV.js → environment-DPi0_0SP.js} +19 -5
  10. package/dist/environment-DPi0_0SP.js.map +1 -0
  11. package/dist/gtao-_nr0b6-E.js +630 -0
  12. package/dist/gtao-_nr0b6-E.js.map +1 -0
  13. package/dist/hdr-output-BrUvpAsE.js +525 -0
  14. package/dist/hdr-output-BrUvpAsE.js.map +1 -0
  15. package/dist/{ignifx-error-Dq2qJMkZ.js → ignifx-error-oYdVnT1S.js} +16 -1
  16. package/dist/ignifx-error-oYdVnT1S.js.map +1 -0
  17. package/dist/index.d.ts +753 -18
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1679 -183
  20. package/dist/index.js.map +1 -1
  21. package/dist/{instanced-mesh-instance-DYwH0vLi.js → instanced-mesh-instance-NnODkvqK.js} +2 -2
  22. package/dist/{instanced-mesh-instance-DYwH0vLi.js.map → instanced-mesh-instance-NnODkvqK.js.map} +1 -1
  23. package/dist/mat4-D6exvAuO.js +949 -0
  24. package/dist/mat4-D6exvAuO.js.map +1 -0
  25. package/dist/material-CGk5mAah.js +204 -0
  26. package/dist/material-CGk5mAah.js.map +1 -0
  27. package/dist/{material-plugin-BOCB7Stt.js → material-plugin-BUlqLsap.js} +3 -204
  28. package/dist/material-plugin-BUlqLsap.js.map +1 -0
  29. package/dist/{post-effect-compiler-Dw6zW2cG.js → post-effect-compiler-CRek8VxQ.js} +2 -2
  30. package/dist/{post-effect-compiler-Dw6zW2cG.js.map → post-effect-compiler-CRek8VxQ.js.map} +1 -1
  31. package/dist/render-path-Be7WgN7r.js +166 -0
  32. package/dist/render-path-Be7WgN7r.js.map +1 -0
  33. package/dist/render-texture-C_TnaSz2.js +200 -0
  34. package/dist/render-texture-C_TnaSz2.js.map +1 -0
  35. package/dist/scene-color-passes-DlNr-qyZ.js +65 -0
  36. package/dist/scene-color-passes-DlNr-qyZ.js.map +1 -0
  37. package/dist/scene-inputs-BxGOsnIZ.js +318 -0
  38. package/dist/scene-inputs-BxGOsnIZ.js.map +1 -0
  39. package/dist/{shader-material-DRZmqA_S.js → shader-material-B6p66wB8.js} +18 -7
  40. package/dist/shader-material-B6p66wB8.js.map +1 -0
  41. package/dist/{shader-material-BxQn9FT4.js → shader-material-C0TAUr4t.js} +102 -4
  42. package/dist/shader-material-C0TAUr4t.js.map +1 -0
  43. package/dist/{shader-pragma-DrFm5f5m.js → shader-pragma-BKCoZTTA.js} +2 -2
  44. package/dist/{shader-pragma-DrFm5f5m.js.map → shader-pragma-BKCoZTTA.js.map} +1 -1
  45. package/dist/ssgi-Dm-maZrc.js +113 -0
  46. package/dist/ssgi-Dm-maZrc.js.map +1 -0
  47. package/dist/{surface-shader-BgZchRBe.js → surface-shader-BaK0kvBB.js} +5 -4
  48. package/dist/{surface-shader-BgZchRBe.js.map → surface-shader-BaK0kvBB.js.map} +1 -1
  49. package/dist/taa-BwBZLy11.js +480 -0
  50. package/dist/taa-BwBZLy11.js.map +1 -0
  51. package/dist/{vec3-T2PasQZv.js → vec3-D-0Y2mzE.js} +4 -948
  52. package/dist/vec3-D-0Y2mzE.js.map +1 -0
  53. package/package.json +1 -1
  54. package/dist/environment-C9AjYJgV.js.map +0 -1
  55. package/dist/ignifx-error-Dq2qJMkZ.js.map +0 -1
  56. package/dist/material-plugin-BOCB7Stt.js.map +0 -1
  57. package/dist/shader-material-BxQn9FT4.js.map +0 -1
  58. package/dist/shader-material-DRZmqA_S.js.map +0 -1
  59. package/dist/vec3-T2PasQZv.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"post-effect-compiler-Dw6zW2cG.js","names":[],"sources":["../src/render/post-effect-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n // Lite's effect vertex puts uv (0, 0) at the bottom-left, but a texture's origin is the top-left,\n // so an unflipped uv mirrors the frame on every pass (`lib/effect/effect-renderer.js` 7).\n \"ignifxPostInput.uv=vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,kBAAkB,QAAyC;CACzE,IAAI,OAAO,YAAY,SAAS,QAC9B,MAAM,IAAI,YACR,cAAc,kBACd,GAAG,OAAO,QAAQ,oBAAoB,OAAO,YAAY,KAAK,sBAC9D;EACE,SAAS;GAAE,MAAM,OAAO;GAAS,QAAQ;GAAgB,MAAM,OAAO,YAAY;EAAK;EACvF,MAAM;CACR,CACF;CAEF,IAAI,CAAC,IAAI,OAAO,gCAA2C,GAAG,CAAC,CAAC,KAAK,OAAO,MAAM,GAChF,MAAM,IAAI,YACR,cAAc,oBACd,GAAG,OAAO,QAAQ,eAAe,qBAAqB,aACtD;EACE,SAAS;GAAE,OAAO,OAAO;GAAS,MAAM;EAAqB;EAC7D,MAAM,UAAU,qBAAqB;CACvC,CACF;CAEF,MAAM,WAAW,OAAO,YAAY,SAAS,QAAQ,YAAY,CAAC,qBAAqB,QAAQ,IAAI,CAAC;CACpG,MAAM,SAAS,eAAe,CAC5B,GAAG,8BACH,GAAG,SAAS,KAAK,aAAa;EAAE,MAAM,QAAQ;EAAM,MAAM,QAAQ;CAAK,EAAE,CAC3E,CAAC;CACD,MAAM,yBAAS,IAAI,IAAoC;CACvD,KAAK,MAAM,SAAS,OAAO,QACzB,OAAO,IAAI,MAAM,MAAM,KAAK;CAE9B,OAAO;EACL,SAAS,OAAO;EAChB,cAAc,oBAAoB,QAAQ,OAAO,MAAM;EACvD,UAAU,OAAO;EACjB;EACA,mBAAmB,OAAO;EAC1B,UAAU,OAAO,YAAY;CAC/B;AACF;;AAGA,IAAI,WAA4D;;;;;;;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-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n // Lite's effect vertex puts uv (0, 0) at the bottom-left, but a texture's origin is the top-left,\n // so an unflipped uv mirrors the frame on every pass (`lib/effect/effect-renderer.js` 7).\n \"ignifxPostInput.uv=vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;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,KAAK,GAAG,KAAK,IACrE,qBAAqB,OAAO,UAAU,CAAC,EAAE,OAAO,YAAY,KAAK,iBACnE;CACF;CACA,MAAM,KACJ,sDACA,OAAO,QACP,oFACA,kCAGA,kEACA,kDACA,UAAU,qBAAqB,qBAC/B,GACF;CACA,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;;;;;AAWA,SAAS,WACP,OACA,OACA,OACA,KACM;CACN,MAAM,QAAQ,MAAM,aAAa;CACjC,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,MAAM,eAAe,GACvB,MAAM,SAAS,OAAO,OAAO,iBAAiB;EAEhD,IAAI,SAAS;EACb;CACF;CACA,IAAI,MAAM,WAAW,MAAM,YACzB,MAAM,SAAS,OAAO,OAAO,GAAG,OAAO,MAAM,MAAM,EAAE,QAAQ;CAE/D,IAAI,IAAI,iBAAiB,eAAe,QAAQ,aAAa,KAAK,KAAK,GAAG,KAAK;AACjF;;;;;;;;;AAUA,SAAS,SAAS,OAA+B,OAAe,QAA6B;CAC3F,OAAO,IAAI,YACT,cAAc,qBACd,GAAG,MAAM,KAAK,MAAM,MAAM,WAAW,MAAM,KAAK,IAAI,OAAO,MAAM,UAAU,EAAE,gBAAgB,OAAO,IACpG;EACE,SAAS;GAAE,MAAM,MAAM;GAAM,UAAU;GAAO,UAAU,MAAM;GAAM;EAAO;EAC3E,MAAM;CACR,CACF;AACF;;;;;;;AAQA,SAAS,qBAAqB,MAAuB;CACnD,KAAK,MAAM,WAAW,8BACpB,IAAI,QAAQ,SAAS,MACnB,OAAO;CAGX,OAAO;AACT"}
@@ -0,0 +1,166 @@
1
+ import { addTask, createCopyToTextureTask, createRenderTarget, createRenderTask } from "@babylonjs/lite";
2
+ //#region src/lite/gpu/render-path.ts
3
+ /**
4
+ * The offscreen render path (`docs/architecture/07-rendering.md` §2.7): the frame graph a scene gets
5
+ * when the project declares `rendering.features.postProcessing`.
6
+ *
7
+ * Everything here needs a device.
8
+ *
9
+ * ## Why the default render task is not good enough
10
+ *
11
+ * `createSceneContext` appends a task named `"scene"` that draws straight into the surface's
12
+ * swapchain target — `surface.scRT` for a single-sample surface, or an MSAA colour target that
13
+ * resolves into `scRT` (`lib/scene/scene-core.js` 74-79). Either way the scene's colour ends up in
14
+ * the swapchain texture, and a post-process pass cannot read it: `createSurface` configures the
15
+ * canvas context with no `usage` (`lib/engine/surface.js` 30), so the swapchain texture is
16
+ * `RENDER_ATTACHMENT` only. Binding it as a sampled texture fails WebGPU validation, the whole
17
+ * frame's command buffer is rejected, and the page presents black. That is exactly what the Phase 2
18
+ * visual suite measured, and it is why this module exists.
19
+ *
20
+ * Lite offers no way to retarget the default task after the fact — `RenderTaskConfig.rt` is read
21
+ * when the task is created, and `FrameGraph`'s public surface is only `build`/`execute`/`dispose`
22
+ * (`index.d.ts` 5367). So the scene is created with `defaultRenderTask: false` and this module
23
+ * builds the replacement.
24
+ *
25
+ * ## The graph it builds
26
+ *
27
+ * ```text
28
+ * [shadow] → scene ──→ sceneColor ──→ present ──→ swapchain
29
+ * └─ (a PostProcessStack appends its effects here, and disables present)
30
+ * ```
31
+ *
32
+ * - `scene` is a normal `createRenderTask`. With MSAA it draws into a multisampled colour target
33
+ * that owns its depth and resolves into `sceneColor` through `rst`; without MSAA it draws into
34
+ * `sceneColor` directly with a separate depth target, which is the same split Lite's own default
35
+ * uses (`RenderTaskConfig.depth`, `index.d.ts` 9782).
36
+ * - `sceneColor` is an ordinary `createRenderTarget`, so `buildRenderTarget` allocates it with
37
+ * `RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC | COPY_DST` (`lib/engine/render-target.js`) —
38
+ * the `TEXTURE_BINDING` the swapchain lacks.
39
+ * - `present` is a `createCopyToTextureTask` from `sceneColor` to the swapchain. Copying *into* the
40
+ * swapchain is supported and takes the blit path (`lib/frame-graph/copy-to-texture-task.js`,
41
+ * `swapAsView`); copying *out of* it is refused (Lite error 80), which is the same limit stated
42
+ * from the other side.
43
+ * - The swapchain is written every frame whatever else happens: with no chain, `present` does it;
44
+ * with a chain, the chain's last effect does it and `present` is switched off
45
+ * ({@link ScenePresenter.setPresentEnabled}).
46
+ *
47
+ * ## Resize
48
+ *
49
+ * Every target here is sized by passing the **surface** as `RenderTargetDescriptor.size`, which
50
+ * `resolveSize` re-reads from `canvas.width`/`canvas.height` on every `buildRenderTarget`
51
+ * (`lib/engine/render-target.js`). A surface resize calls the scene's `_resize`, which is
52
+ * `frameGraph.build()` (`lib/scene/scene-core.js` 67-68): every target is reallocated at the new
53
+ * size and every task re-records, which is also what refreshes the bind groups that captured the old
54
+ * texture views. Nothing here has to observe the canvas itself, and nothing is eagerly allocated —
55
+ * `createRenderTargetTexture` would be, and Lite rejects a surface as its size for exactly that
56
+ * reason.
57
+ */
58
+ /**
59
+ * The depth/stencil format Lite's own default render task uses (`lib/scene/scene-core.js` 76-77).
60
+ *
61
+ * @internal
62
+ */
63
+ const DEPTH_STENCIL_FORMAT = "depth24plus-stencil8";
64
+ /** The scenes `rendering.hdr` built, created on first use so the module has no import-time work. */
65
+ let hdrScenes = null;
66
+ /**
67
+ * Records that a scene renders through the HDR path, so code outside the HDR chunk (a custom
68
+ * shader's build) can ask without importing it.
69
+ *
70
+ * @param scene - The scene `./hdr-output.ts` built a render path for.
71
+ *
72
+ * @internal
73
+ */
74
+ function markHdrScene(scene) {
75
+ hdrScenes ??= /* @__PURE__ */ new WeakSet();
76
+ hdrScenes.add(scene);
77
+ }
78
+ /**
79
+ * Whether a scene renders through the HDR path, where every colour writer must write linear colour.
80
+ *
81
+ * @param scene - The scene.
82
+ * @returns `true` once `./hdr-output.ts` has built the scene's render path.
83
+ *
84
+ * @internal
85
+ */
86
+ function isHdrScene(scene) {
87
+ return hdrScenes?.has(scene) === true;
88
+ }
89
+ /**
90
+ * Builds the scene's render task into an offscreen target and the blit that composites it, and
91
+ * appends both to the scene's frame graph.
92
+ *
93
+ * @remarks
94
+ * Call it immediately after `createSceneContext(engine, { defaultRenderTask: false })` and before
95
+ * `registerScene`: `addTask` appends, so calling it first is what puts `"scene"` ahead of everything
96
+ * a feature adds later, and `registerSceneWithShadowSupport` still unshifts its own `"shadow"` task
97
+ * in front of both.
98
+ *
99
+ * @param engine - The engine, which is also the primary surface.
100
+ * @param scene - The scene created with no default render task.
101
+ * @returns The presenter a `PostProcessStack` builds its chain against.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * const scene = createSceneContext(engine, { defaultRenderTask: false });
106
+ * const presenter = installOffscreenRenderPath(engine, scene);
107
+ * ```
108
+ *
109
+ * @internal
110
+ */
111
+ function installOffscreenRenderPath(engine, scene) {
112
+ const isMultisampled = engine.msaaSamples > 1;
113
+ const sceneColor = createRenderTarget({
114
+ lbl: "ignifx:scene-color",
115
+ format: engine.format,
116
+ samples: 1,
117
+ size: engine
118
+ });
119
+ const config = {
120
+ name: "scene",
121
+ rt: isMultisampled ? createRenderTarget({
122
+ lbl: "ignifx:scene-color-msaa",
123
+ format: engine.format,
124
+ dFormat: DEPTH_STENCIL_FORMAT,
125
+ samples: engine.msaaSamples,
126
+ size: engine
127
+ }) : sceneColor
128
+ };
129
+ if (isMultisampled) config.rst = sceneColor;
130
+ else config.depth = createRenderTarget({
131
+ lbl: "ignifx:scene-depth",
132
+ dFormat: DEPTH_STENCIL_FORMAT,
133
+ samples: 1,
134
+ size: engine
135
+ });
136
+ const sceneTask = createRenderTask(config, engine, scene);
137
+ addTask(scene, sceneTask);
138
+ const present = createCopyToTextureTask({
139
+ name: "ignifx:present",
140
+ sourceTexture: sceneColor,
141
+ targetTexture: engine.scRT
142
+ }, engine, scene);
143
+ addTask(scene, present);
144
+ let isPresentEnabled = true;
145
+ return {
146
+ sceneColor,
147
+ swapchain: engine.scRT,
148
+ setPresentEnabled(enabled) {
149
+ isPresentEnabled = enabled;
150
+ present.executionEnabled = enabled;
151
+ },
152
+ get isPresentEnabled() {
153
+ return isPresentEnabled;
154
+ },
155
+ hdr: null,
156
+ scenePass: {
157
+ task: sceneTask,
158
+ target: sceneColor,
159
+ format: engine.format
160
+ }
161
+ };
162
+ }
163
+ //#endregion
164
+ export { markHdrScene as i, installOffscreenRenderPath as n, isHdrScene as r, DEPTH_STENCIL_FORMAT as t };
165
+
166
+ //# sourceMappingURL=render-path-Be7WgN7r.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-path-Be7WgN7r.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\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 },\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;;;;;;;;;;;;;;;;;;;;;;;AAuEA,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;EAAO;CAC1E;AACF"}
@@ -0,0 +1,200 @@
1
+ import { addTask, buildFrameGraphTask, createRenderTarget, createRenderTask, getFrameGraph } from "@babylonjs/lite";
2
+ //#region src/lite/gpu/render-texture.ts
3
+ /**
4
+ * Render-to-texture (`docs/architecture/07-rendering.md` §2.11): a second pass of the render scene,
5
+ * through another camera, into an offscreen colour target that can be read back.
6
+ *
7
+ * Everything here needs a device, and every Lite claim was read from `@babylonjs/lite@1.34.0`.
8
+ *
9
+ * ## The pass
10
+ *
11
+ * One `createRenderTask` per texture, appended to the render scene's frame graph. Its target is an
12
+ * ordinary `createRenderTarget` of a fixed `{ width, height }`, in the surface's colour format with
13
+ * a depth/stencil attachment of its own, single-sample. The task owns it: `record()` allocates it
14
+ * (`buildRenderTarget`, `RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC | COPY_DST`,
15
+ * `lib/engine/render-target.js` 59) and `dispose()` frees it. The task auto-mirrors the scene's
16
+ * renderables, builds its own pipelines for its target signature, and writes a scene UBO of its own
17
+ * (`_sceneUBO`, `lib/frame-graph/render-task-base.js` 85), so its camera never disturbs the main
18
+ * pass.
19
+ *
20
+ * ## The camera
21
+ *
22
+ * `RenderTaskConfig.cam` is read on every execute (`task._config.cam ?? scene.camera`,
23
+ * `render-task-base.js` 236, 279) from the config object the task keeps by reference (line 77), so
24
+ * re-pointing the pass is one assignment. A `null` camera would fall back to the scene's main
25
+ * camera, so the pass is switched off with `Task.executionEnabled` instead.
26
+ *
27
+ * ## Editor-only meshes
28
+ *
29
+ * A render task draws every visible mesh of its scene; `RenderTaskConfig` has no mesh filter. So
30
+ * the task's `execute` (the frame graph calls it, `lib/frame-graph/frame-graph.js` 16) is wrapped:
31
+ * it hides each visible mesh whose `metadata[excludeKey]` is `true`, runs, and shows them again.
32
+ * The main pass has already drawn the frame by then (the task is appended after it), so the main
33
+ * view never sees them hidden and does not flicker. `drawList` reads `visible` as it encodes
34
+ * (`render-task-base.js` 354), and this task's opaque bundle is only ever encoded inside the
35
+ * wrapper, so it never holds them either.
36
+ *
37
+ * ## Gaps in Lite's public surface
38
+ *
39
+ * - **No task removal.** `FrameGraph` exposes only `build`/`execute`/`dispose`, and a disposed
40
+ * render task throws from `record()` on the next `frameGraph.build()` (a canvas resize). So the
41
+ * task is spliced out of `_tasks`, the array `addTask` appends to (`lib/frame-graph/frame-graph.js`),
42
+ * before it is disposed.
43
+ * - **No texture readback.** Lite reads back only the swapchain (`captureScreenshot`). The read here
44
+ * copies the target's `_colorTexture` into a mapped buffer through `engine._device`. Queue order
45
+ * makes it read the last frame submitted before the call.
46
+ */
47
+ /** The depth/stencil format Lite's own render tasks use. */
48
+ const DEPTH_STENCIL_FORMAT = "depth24plus-stencil8";
49
+ /** WebGPU's `bytesPerRow` alignment for a texture-to-buffer copy. */
50
+ const ROW_ALIGNMENT = 256;
51
+ /** RGBA8 bytes per pixel. */
52
+ const BYTES_PER_PIXEL = 4;
53
+ /**
54
+ * Creates a texture's render pass, switched off, at the end of the render scene's frame graph.
55
+ *
56
+ * @remarks
57
+ * Call it only once the scene is registered: the task is recorded at once, which allocates its
58
+ * target.
59
+ *
60
+ * @param engine - The WebGPU engine.
61
+ * @param scene - The registered render scene.
62
+ * @param width - The width in pixels.
63
+ * @param height - The height in pixels.
64
+ * @param excludeKey - The `metadata` key that, set to `true` on a mesh, keeps it out of the pass.
65
+ * @returns The pass.
66
+ *
67
+ * @internal
68
+ */
69
+ function createLiteRenderTexture(engine, scene, width, height, excludeKey) {
70
+ const target = createRenderTarget({
71
+ lbl: "ignifx:render-texture",
72
+ format: engine.format,
73
+ dFormat: DEPTH_STENCIL_FORMAT,
74
+ samples: 1,
75
+ size: {
76
+ width,
77
+ height
78
+ }
79
+ });
80
+ const config = {
81
+ name: "ignifx:render-texture",
82
+ rt: target,
83
+ cam: null
84
+ };
85
+ const task = createRenderTask(config, engine, scene);
86
+ task.executionEnabled = false;
87
+ const execute = task.execute?.bind(task);
88
+ if (execute === void 0) throw new TypeError("Lite's render task has no execute(); render-texture.ts needs updating for this Lite.");
89
+ const hidden = [];
90
+ task.execute = () => {
91
+ for (const mesh of scene.meshes) if (mesh.visible !== false && mesh.metadata?.[excludeKey] === true) {
92
+ mesh.visible = false;
93
+ hidden.push(mesh);
94
+ }
95
+ try {
96
+ return execute();
97
+ } finally {
98
+ for (const mesh of hidden) mesh.visible = true;
99
+ hidden.length = 0;
100
+ }
101
+ };
102
+ addTask(scene, task);
103
+ buildFrameGraphTask(getFrameGraph(scene), task);
104
+ let isDisposed = false;
105
+ return {
106
+ setCamera(camera) {
107
+ if (isDisposed) return;
108
+ config.cam = camera;
109
+ task.executionEnabled = camera !== null;
110
+ },
111
+ async read() {
112
+ const texture = isDisposed ? null : colorTextureOf(target);
113
+ const device = deviceOf(engine);
114
+ if (texture === null || device === null) throw new Error("The render texture has no GPU texture to read.");
115
+ return readTexture(device, texture, width, height);
116
+ },
117
+ dispose() {
118
+ if (isDisposed) return;
119
+ isDisposed = true;
120
+ task.executionEnabled = false;
121
+ removeTask(scene, task);
122
+ task.dispose();
123
+ }
124
+ };
125
+ }
126
+ /**
127
+ * A render target's live colour texture.
128
+ *
129
+ * @param target - The target.
130
+ * @returns The texture, or `null` before the owning task has recorded.
131
+ */
132
+ function colorTextureOf(target) {
133
+ return target._colorTexture ?? null;
134
+ }
135
+ /**
136
+ * An engine's current device.
137
+ *
138
+ * @param engine - The engine.
139
+ * @returns The device, or `null` for an engine without one.
140
+ */
141
+ function deviceOf(engine) {
142
+ return engine._device ?? null;
143
+ }
144
+ /**
145
+ * Takes a task out of a scene's frame graph, so the next rebuild does not record it.
146
+ *
147
+ * @param scene - The scene.
148
+ * @param task - The task.
149
+ */
150
+ function removeTask(scene, task) {
151
+ const tasks = getFrameGraph(scene)._tasks;
152
+ if (!Array.isArray(tasks)) throw new TypeError("Lite's FrameGraph has no _tasks array; render-texture.ts needs updating for this Lite.");
153
+ const index = tasks.indexOf(task);
154
+ if (index >= 0) tasks.splice(index, 1);
155
+ }
156
+ /**
157
+ * Copies a colour texture into tightly packed RGBA8.
158
+ *
159
+ * @param device - The device that owns the texture.
160
+ * @param texture - An 8-bit RGBA or BGRA texture with `COPY_SRC`.
161
+ * @param width - The width to read.
162
+ * @param height - The height to read.
163
+ * @returns The pixels, top row first, red first.
164
+ */
165
+ async function readTexture(device, texture, width, height) {
166
+ const rowBytes = width * BYTES_PER_PIXEL;
167
+ const bytesPerRow = Math.ceil(rowBytes / ROW_ALIGNMENT) * ROW_ALIGNMENT;
168
+ const buffer = device.createBuffer({
169
+ label: "ignifx:render-texture-read",
170
+ size: bytesPerRow * height,
171
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
172
+ });
173
+ try {
174
+ const encoder = device.createCommandEncoder({ label: "ignifx:render-texture-read" });
175
+ encoder.copyTextureToBuffer({ texture }, {
176
+ buffer,
177
+ bytesPerRow
178
+ }, {
179
+ width,
180
+ height
181
+ });
182
+ device.queue.submit([encoder.finish()]);
183
+ await buffer.mapAsync(GPUMapMode.READ);
184
+ const mapped = new Uint8Array(buffer.getMappedRange());
185
+ const out = new Uint8ClampedArray(rowBytes * height);
186
+ for (let row = 0; row < height; row += 1) out.set(mapped.subarray(row * bytesPerRow, row * bytesPerRow + rowBytes), row * rowBytes);
187
+ if (texture.format.startsWith("bgra")) for (let index = 0; index < out.length; index += BYTES_PER_PIXEL) {
188
+ const blue = out[index] ?? 0;
189
+ out[index] = out[index + 2] ?? 0;
190
+ out[index + 2] = blue;
191
+ }
192
+ return out;
193
+ } finally {
194
+ buffer.destroy();
195
+ }
196
+ }
197
+ //#endregion
198
+ export { createLiteRenderTexture };
199
+
200
+ //# sourceMappingURL=render-texture-C_TnaSz2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-texture-C_TnaSz2.js","names":["internals"],"sources":["../src/lite/gpu/render-texture.ts"],"sourcesContent":["import { addTask, buildFrameGraphTask, createRenderTarget, createRenderTask, getFrameGraph } from \"@babylonjs/lite\";\nimport type { Camera, EngineContext, Mesh, RenderTarget, RenderTaskConfig, SceneContext, Task } from \"@babylonjs/lite\";\n\n/**\n * Render-to-texture (`docs/architecture/07-rendering.md` §2.11): a second pass of the render scene,\n * through another camera, into an offscreen colour target that can be read back.\n *\n * Everything here needs a device, and every Lite claim was read from `@babylonjs/lite@1.34.0`.\n *\n * ## The pass\n *\n * One `createRenderTask` per texture, appended to the render scene's frame graph. Its target is an\n * ordinary `createRenderTarget` of a fixed `{ width, height }`, in the surface's colour format with\n * a depth/stencil attachment of its own, single-sample. The task owns it: `record()` allocates it\n * (`buildRenderTarget`, `RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC | COPY_DST`,\n * `lib/engine/render-target.js` 59) and `dispose()` frees it. The task auto-mirrors the scene's\n * renderables, builds its own pipelines for its target signature, and writes a scene UBO of its own\n * (`_sceneUBO`, `lib/frame-graph/render-task-base.js` 85), so its camera never disturbs the main\n * pass.\n *\n * ## The camera\n *\n * `RenderTaskConfig.cam` is read on every execute (`task._config.cam ?? scene.camera`,\n * `render-task-base.js` 236, 279) from the config object the task keeps by reference (line 77), so\n * re-pointing the pass is one assignment. A `null` camera would fall back to the scene's main\n * camera, so the pass is switched off with `Task.executionEnabled` instead.\n *\n * ## Editor-only meshes\n *\n * A render task draws every visible mesh of its scene; `RenderTaskConfig` has no mesh filter. So\n * the task's `execute` (the frame graph calls it, `lib/frame-graph/frame-graph.js` 16) is wrapped:\n * it hides each visible mesh whose `metadata[excludeKey]` is `true`, runs, and shows them again.\n * The main pass has already drawn the frame by then (the task is appended after it), so the main\n * view never sees them hidden and does not flicker. `drawList` reads `visible` as it encodes\n * (`render-task-base.js` 354), and this task's opaque bundle is only ever encoded inside the\n * wrapper, so it never holds them either.\n *\n * ## Gaps in Lite's public surface\n *\n * - **No task removal.** `FrameGraph` exposes only `build`/`execute`/`dispose`, and a disposed\n * render task throws from `record()` on the next `frameGraph.build()` (a canvas resize). So the\n * task is spliced out of `_tasks`, the array `addTask` appends to (`lib/frame-graph/frame-graph.js`),\n * before it is disposed.\n * - **No texture readback.** Lite reads back only the swapchain (`captureScreenshot`). The read here\n * copies the target's `_colorTexture` into a mapped buffer through `engine._device`. Queue order\n * makes it read the last frame submitted before the call.\n */\n\n/** The depth/stencil format Lite's own render tasks use. */\nconst DEPTH_STENCIL_FORMAT: GPUTextureFormat = \"depth24plus-stencil8\";\n\n/** WebGPU's `bytesPerRow` alignment for a texture-to-buffer copy. */\nconst ROW_ALIGNMENT = 256;\n\n/** RGBA8 bytes per pixel. */\nconst BYTES_PER_PIXEL = 4;\n\n/** The fields of a Lite 1.34 render target that hold its live GPU texture. */\ninterface TargetInternals {\n /** The colour texture, `null` until the owning task has recorded. */\n _colorTexture?: GPUTexture | null;\n}\n\n/** The field of a Lite 1.34 engine that holds its device. */\ninterface EngineInternals {\n /** The device; replaced after a device-loss recovery, so read on every use. */\n _device?: GPUDevice;\n}\n\n/** The field of a Lite 1.34 frame graph that holds its tasks. */\ninterface FrameGraphInternals {\n /** The tasks, in execute order. */\n _tasks?: Task[];\n}\n\n/**\n * One texture's render pass.\n *\n * @internal\n */\nexport interface LiteRenderTexture {\n /**\n * Points the pass at a camera, or switches it off.\n *\n * @param camera - The camera to render through from the next frame, or `null` to stop.\n */\n setCamera(camera: Camera | null): void;\n /**\n * Reads the texture as it is after the last submitted frame.\n *\n * @returns `width * height * 4` bytes of RGBA8, top row first.\n * @throws Error when the pass has not recorded yet or the engine has no device.\n */\n read(): Promise<Uint8ClampedArray>;\n /** Removes the pass from the frame graph and frees its target. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Creates a texture's render pass, switched off, at the end of the render scene's frame graph.\n *\n * @remarks\n * Call it only once the scene is registered: the task is recorded at once, which allocates its\n * target.\n *\n * @param engine - The WebGPU engine.\n * @param scene - The registered render scene.\n * @param width - The width in pixels.\n * @param height - The height in pixels.\n * @param excludeKey - The `metadata` key that, set to `true` on a mesh, keeps it out of the pass.\n * @returns The pass.\n *\n * @internal\n */\nexport function createLiteRenderTexture(\n engine: EngineContext,\n scene: SceneContext,\n width: number,\n height: number,\n excludeKey: string,\n): LiteRenderTexture {\n const target: RenderTarget = createRenderTarget({\n lbl: \"ignifx:render-texture\",\n format: engine.format,\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: 1,\n size: { width, height },\n });\n const config: RenderTaskConfig = { name: \"ignifx:render-texture\", rt: target, cam: null };\n const task = createRenderTask(config, 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(); render-texture.ts needs updating for this Lite.\");\n }\n const hidden: Mesh[] = [];\n task.execute = (): number => {\n for (const mesh of scene.meshes) {\n if (mesh.visible !== false && mesh.metadata?.[excludeKey] === true) {\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 let isDisposed = false;\n return {\n setCamera(camera: Camera | null): void {\n if (isDisposed) {\n return;\n }\n config.cam = camera;\n task.executionEnabled = camera !== null;\n },\n async read(): Promise<Uint8ClampedArray> {\n const texture = isDisposed ? null : colorTextureOf(target);\n const device = deviceOf(engine);\n if (texture === null || device === null) {\n throw new Error(\"The render texture has no GPU texture to read.\");\n }\n return readTexture(device, texture, width, height);\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n task.executionEnabled = false;\n removeTask(scene, task);\n task.dispose();\n },\n };\n}\n\n/**\n * A render target's live colour texture.\n *\n * @param target - The target.\n * @returns The texture, or `null` before the owning task has recorded.\n */\nfunction colorTextureOf(target: RenderTarget): GPUTexture | null {\n // Boundary assertion (coding standards §5.2): the field Lite 1.34 keeps, documented above.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const internals = target as RenderTarget & TargetInternals;\n // oxlint-disable-next-line no-underscore-dangle\n return internals._colorTexture ?? null;\n}\n\n/**\n * An engine's current device.\n *\n * @param engine - The engine.\n * @returns The device, or `null` for an engine without one.\n */\nfunction deviceOf(engine: EngineContext): GPUDevice | null {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const internals = engine as EngineContext & EngineInternals;\n // oxlint-disable-next-line no-underscore-dangle\n return internals._device ?? null;\n}\n\n/**\n * Takes a task out of a scene's frame graph, so the next rebuild does not record it.\n *\n * @param scene - The scene.\n * @param task - The task.\n */\nfunction removeTask(scene: SceneContext, task: Task): void {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const graph = getFrameGraph(scene) as ReturnType<typeof getFrameGraph> & FrameGraphInternals;\n // oxlint-disable-next-line no-underscore-dangle\n const tasks = graph._tasks;\n if (!Array.isArray(tasks)) {\n // A Lite upgrade renamed the field: fail here, not on the next rebuild (07-rendering §2.11).\n throw new TypeError(\"Lite's FrameGraph has no _tasks array; render-texture.ts needs updating for this Lite.\");\n }\n const index = tasks.indexOf(task);\n if (index >= 0) {\n tasks.splice(index, 1);\n }\n}\n\n/**\n * Copies a colour texture into tightly packed RGBA8.\n *\n * @param device - The device that owns the texture.\n * @param texture - An 8-bit RGBA or BGRA texture with `COPY_SRC`.\n * @param width - The width to read.\n * @param height - The height to read.\n * @returns The pixels, top row first, red first.\n */\nasync function readTexture(\n device: GPUDevice,\n texture: GPUTexture,\n width: number,\n height: number,\n): Promise<Uint8ClampedArray> {\n const rowBytes = width * BYTES_PER_PIXEL;\n const bytesPerRow = Math.ceil(rowBytes / ROW_ALIGNMENT) * ROW_ALIGNMENT;\n const buffer = device.createBuffer({\n label: \"ignifx:render-texture-read\",\n size: bytesPerRow * height,\n usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,\n });\n try {\n const encoder = device.createCommandEncoder({ label: \"ignifx:render-texture-read\" });\n encoder.copyTextureToBuffer({ texture }, { buffer, bytesPerRow }, { width, height });\n device.queue.submit([encoder.finish()]);\n await buffer.mapAsync(GPUMapMode.READ);\n const mapped = new Uint8Array(buffer.getMappedRange());\n const out = new Uint8ClampedArray(rowBytes * height);\n for (let row = 0; row < height; row += 1) {\n out.set(mapped.subarray(row * bytesPerRow, row * bytesPerRow + rowBytes), row * rowBytes);\n }\n if (texture.format.startsWith(\"bgra\")) {\n for (let index = 0; index < out.length; index += BYTES_PER_PIXEL) {\n const blue = out[index] ?? 0;\n out[index] = out[index + 2] ?? 0;\n out[index + 2] = blue;\n }\n }\n return out;\n } finally {\n buffer.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,uBAAyC;;AAG/C,MAAM,g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,IAAI,SAAS,IAAI,QAAQ,MAAM;GAC/B,IAAI,QAAQ,KAAK;EACnB;EAEF,OAAO;CACT,UAAU;EACR,OAAO,QAAQ;CACjB;AACF"}
@@ -0,0 +1,65 @@
1
+ import { frameGraphTasks } from "./scene-inputs-BxGOsnIZ.js";
2
+ import { addTaskAfter, buildFrameGraphTask, createCopyToTextureTask, createRenderTarget, disposeRenderTarget, getFrameGraph } from "@babylonjs/lite";
3
+ //#region src/lite/gpu/scene-color-passes.ts
4
+ /**
5
+ * Inserts the passes after the scene task, in order.
6
+ *
7
+ * @param engine - The engine; also the surface the scratch target is sized by.
8
+ * @param scene - The scene.
9
+ * @param presenter - The offscreen render path.
10
+ * @param passes - The effects, first to last.
11
+ * @param isFrameGraphBuilt - Whether the scene is registered, so each task is recorded now.
12
+ * @returns The handle that takes them out again.
13
+ *
14
+ * @internal
15
+ */
16
+ function installSceneColorPasses(engine, scene, presenter, passes, isFrameGraphBuilt) {
17
+ const { task: sceneTask, target: sceneTarget, format } = presenter.scenePass;
18
+ const scratch = createRenderTarget({
19
+ lbl: "ignifx:scene-color-scratch",
20
+ format,
21
+ samples: 1,
22
+ size: engine
23
+ });
24
+ const tasks = [];
25
+ let source = sceneTarget;
26
+ for (const pass of passes) {
27
+ const target = source === sceneTarget ? scratch : sceneTarget;
28
+ tasks.push(pass.create(source, target));
29
+ source = target;
30
+ }
31
+ if (source !== sceneTarget) tasks.push(createCopyToTextureTask({
32
+ name: "ignifx:scene-color-copy",
33
+ sourceTexture: scratch,
34
+ targetTexture: sceneTarget
35
+ }, engine, scene));
36
+ let after = sceneTask;
37
+ for (const task of tasks) {
38
+ addTaskAfter(scene, task, after);
39
+ after = task;
40
+ }
41
+ if (isFrameGraphBuilt) {
42
+ const graph = getFrameGraph(scene);
43
+ for (const task of tasks) buildFrameGraphTask(graph, task);
44
+ }
45
+ let isDisposed = false;
46
+ return {
47
+ taskCount: tasks.length,
48
+ dispose() {
49
+ if (isDisposed) return;
50
+ isDisposed = true;
51
+ const list = frameGraphTasks(scene);
52
+ for (const task of tasks) {
53
+ task.executionEnabled = false;
54
+ const index = list?.indexOf(task) ?? -1;
55
+ if (list !== null && index >= 0) list.splice(index, 1);
56
+ task.dispose();
57
+ }
58
+ disposeRenderTarget(scratch);
59
+ }
60
+ };
61
+ }
62
+ //#endregion
63
+ export { installSceneColorPasses };
64
+
65
+ //# sourceMappingURL=scene-color-passes-DlNr-qyZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scene-color-passes-DlNr-qyZ.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 the passes ping-pong\n * between `S` and one scratch target of the same format, and a copy brings an odd count back into\n * `S`. Every task sits right after the scene task, ahead of the present blit, the HDR output pass\n * and a `PostProcessStack` chain 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 } = presenter.scenePass;\n const scratch = createRenderTarget({ lbl: \"ignifx:scene-color-scratch\", format, samples: 1, size: engine });\n const tasks: Task[] = [];\n let source = sceneTarget;\n for (const pass of passes) {\n const target = source === sceneTarget ? scratch : sceneTarget;\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: scratch, 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 disposeRenderTarget(scratch);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsEA,SAAgB,wBACd,QACA,OACA,WACA,QACA,mBAC2B;CAC3B,MAAM,EAAE,MAAM,WAAW,QAAQ,aAAa,WAAW,UAAU;CACnE,MAAM,UAAU,mBAAmB;EAAE,KAAK;EAA8B;EAAQ,SAAS;EAAG,MAAM;CAAO,CAAC;CAC1G,MAAM,QAAgB,CAAC;CACvB,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,SAAS,WAAW,cAAc,UAAU;EAClD,MAAM,KAAK,KAAK,OAAO,QAAQ,MAAM,CAAC;EACtC,SAAS;CACX;CACA,IAAI,WAAW,aACb,MAAM,KACJ,wBACE;EAAE,MAAM;EAA2B,eAAe;EAAS,eAAe;CAAY,GACtF,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,oBAAoB,OAAO;EAC7B;CACF;AACF"}