@zephyr3d/scene 0.9.18 → 0.9.19

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 (53) hide show
  1. package/dist/app/scriptregistry.js +124 -6
  2. package/dist/app/scriptregistry.js.map +1 -1
  3. package/dist/index.d.ts +270 -7
  4. package/dist/index.js +2 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/material/mixins/lightmodel/pbrblueprintmixin.js +11 -5
  7. package/dist/material/mixins/lightmodel/pbrblueprintmixin.js.map +1 -1
  8. package/dist/material/shader/helper.js +21 -8
  9. package/dist/material/shader/helper.js.map +1 -1
  10. package/dist/material/skin.js +4 -6
  11. package/dist/material/skin.js.map +1 -1
  12. package/dist/material/water.js +1 -1
  13. package/dist/material/water.js.map +1 -1
  14. package/dist/posteffect/bloom.js +177 -29
  15. package/dist/posteffect/bloom.js.map +1 -1
  16. package/dist/posteffect/compositor.js +111 -204
  17. package/dist/posteffect/compositor.js.map +1 -1
  18. package/dist/posteffect/motionblur.js +3 -0
  19. package/dist/posteffect/motionblur.js.map +1 -1
  20. package/dist/posteffect/posteffect.js +79 -0
  21. package/dist/posteffect/posteffect.js.map +1 -1
  22. package/dist/posteffect/skinsss.js +10 -10
  23. package/dist/posteffect/skinsss.js.map +1 -1
  24. package/dist/posteffect/ssr.js +247 -16
  25. package/dist/posteffect/ssr.js.map +1 -1
  26. package/dist/posteffect/taa.js +121 -19
  27. package/dist/posteffect/taa.js.map +1 -1
  28. package/dist/posteffect/tonemap.js +6 -6
  29. package/dist/posteffect/tonemap.js.map +1 -1
  30. package/dist/render/abuffer_oit.js +2 -1
  31. package/dist/render/abuffer_oit.js.map +1 -1
  32. package/dist/render/envlight.js +6 -3
  33. package/dist/render/envlight.js.map +1 -1
  34. package/dist/render/hzb.js +11 -4
  35. package/dist/render/hzb.js.map +1 -1
  36. package/dist/render/lightpass.js +7 -15
  37. package/dist/render/lightpass.js.map +1 -1
  38. package/dist/render/renderer.js +4 -3
  39. package/dist/render/renderer.js.map +1 -1
  40. package/dist/render/rendergraph/blackboard.js +78 -0
  41. package/dist/render/rendergraph/blackboard.js.map +1 -0
  42. package/dist/render/rendergraph/executor.js +41 -11
  43. package/dist/render/rendergraph/executor.js.map +1 -1
  44. package/dist/render/rendergraph/forward_plus_builder.js +495 -201
  45. package/dist/render/rendergraph/forward_plus_builder.js.map +1 -1
  46. package/dist/render/rendergraph/rendergraph.js +29 -0
  47. package/dist/render/rendergraph/rendergraph.js.map +1 -1
  48. package/dist/render/rendergraph/types.js.map +1 -1
  49. package/dist/shaders/ssr.js +52 -21
  50. package/dist/shaders/ssr.js.map +1 -1
  51. package/dist/utility/misc.js +10 -1
  52. package/dist/utility/misc.js.map +1 -1
  53. package/package.json +2 -2
@@ -436,6 +436,35 @@ import { RGHandle, RGPass, RGResource, RGSubpass } from './types.js';
436
436
  });
437
437
  }
438
438
  }
439
+ // A pass that reads a framebuffer implicitly reads its attachment textures:
440
+ // extend each RGHandle attachment's lifetime to cover the framebuffer's
441
+ // lifetime so the executor never releases a backing texture while a later
442
+ // pass can still render through the framebuffer. Framebuffers cannot be
443
+ // attachments of other framebuffers, so a single propagation pass suffices.
444
+ for (const lifetime of lifetimes.values()){
445
+ const res = lifetime.resource;
446
+ if (res.kind !== 'framebuffer' || !res.desc) {
447
+ continue;
448
+ }
449
+ const desc = res.desc;
450
+ const extend = (attachment)=>{
451
+ if (!(attachment instanceof RGHandle)) {
452
+ return;
453
+ }
454
+ const attachmentLifetime = lifetimes.get(attachment._id);
455
+ if (attachmentLifetime) {
456
+ attachmentLifetime.firstUse = Math.min(attachmentLifetime.firstUse, lifetime.firstUse);
457
+ attachmentLifetime.lastUse = Math.max(attachmentLifetime.lastUse, lifetime.lastUse);
458
+ }
459
+ };
460
+ const colors = Array.isArray(desc.colorAttachments) ? desc.colorAttachments : desc.colorAttachments ? [
461
+ desc.colorAttachments
462
+ ] : [];
463
+ for (const attachment of colors){
464
+ extend(attachment);
465
+ }
466
+ extend(desc.depthAttachment);
467
+ }
439
468
  return lifetimes;
440
469
  }
441
470
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rendergraph.js","sources":["../../../src/render/rendergraph/rendergraph.ts"],"sourcesContent":["import {\r\n RGHandle,\r\n RGResource,\r\n RGPass,\r\n RGSubpass,\r\n type RGTextureDesc,\r\n type RGPassBuilder,\r\n type RGExecuteFn,\r\n type RGExecuteContext,\r\n type CompiledRenderGraph,\r\n type RGResourceLifetime\r\n} from './types';\r\n\r\n/**\r\n * Render Graph — declarative, configurable render pipeline.\r\n *\r\n * Usage:\r\n * ```ts\r\n * const graph = new RenderGraph();\r\n * let backbuffer = graph.importTexture('backbuffer');\r\n *\r\n * let linearDepth: RGHandle;\r\n * graph.addPass('DepthPrepass', (builder) => {\r\n * linearDepth = builder.createTexture({ format: 'r32f', label: 'linearDepth' });\r\n * builder.setExecute(() => { ... });\r\n * });\r\n *\r\n * graph.addPass('LightPass', (builder) => {\r\n * builder.read(linearDepth);\r\n * backbuffer = builder.write(backbuffer);\r\n * builder.setExecute(() => { ... });\r\n * });\r\n *\r\n * const compiled = graph.compile([backbuffer]);\r\n * graph.execute(compiled);\r\n * graph.reset();\r\n * ```\r\n *\r\n * @public\r\n */\r\nexport class RenderGraph {\r\n /** @internal */\r\n private _nextResourceId = 0;\r\n /** @internal */\r\n private _resources: Map<number, RGResource> = new Map();\r\n /** @internal */\r\n private _passes: RGPass[] = [];\r\n /** @internal */\r\n private _compiled: CompiledRenderGraph | null = null;\r\n\r\n // ─── Graph Building ─────────────────────────────────────────────────\r\n\r\n /**\r\n * Import an external (persistent) texture into the graph.\r\n *\r\n * Imported resources are not allocated or released by the graph.\r\n * Typically used for the backbuffer or any texture that outlives a single frame.\r\n *\r\n * @param name - Debug label for the imported resource.\r\n * @returns A handle referencing the imported resource.\r\n */\r\n importTexture(name: string): RGHandle {\r\n const id = this._nextResourceId++;\r\n const resource = new RGResource(id, name, 'imported', null);\r\n this._resources.set(id, resource);\r\n this._compiled = null;\r\n return new RGHandle(id, name);\r\n }\r\n\r\n /**\r\n * Add a render pass to the graph.\r\n *\r\n * The setup callback receives a {@link RGPassBuilder} to declare resource\r\n * dependencies. Call `builder.setExecute(fn)` inside setup to provide the\r\n * execution callback.\r\n *\r\n * @param name - Debug label for the pass.\r\n * @param setup - Setup callback that declares resources and sets the execute function.\r\n */\r\n addPass<T = void>(name: string, setup: (builder: RGPassBuilder) => T): T {\r\n const pass = new RGPass(this._passes.length, name);\r\n const builder = this._createBuilder(pass);\r\n const data = setup(builder);\r\n pass.data = data;\r\n this._passes.push(pass);\r\n this._compiled = null;\r\n return data;\r\n }\r\n\r\n // ─── Compilation ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Compile the render graph.\r\n *\r\n * Performs dead-pass culling, topological sorting, and resource lifetime analysis.\r\n *\r\n * @param outputs - Handles of resources that must be produced (graph sinks).\r\n * If a resource was passed to {@link RGPassBuilder.write}, use the returned\r\n * post-write handle here, not the original handle.\r\n * Passes that do not contribute to these outputs (directly or transitively)\r\n * are culled, unless marked as side-effect passes.\r\n * @returns The compiled graph ready for execution.\r\n */\r\n compile(outputs: RGHandle[]): CompiledRenderGraph {\r\n this._validateOutputs(outputs);\r\n // 1. Mark alive passes via backward traversal from outputs + side-effect passes\r\n this._cullDeadPasses(outputs);\r\n // 2. Topological sort of alive passes\r\n const ordered = this._topologicalSort();\r\n // 3. Resource lifetime analysis\r\n const lifetimes = this._analyzeLifetimes(ordered);\r\n\r\n this._compiled = { orderedPasses: ordered, lifetimes };\r\n return this._compiled;\r\n }\r\n\r\n /**\r\n * Execute a compiled render graph (simple mode, no resource management).\r\n *\r\n * For automatic resource allocation/release, use {@link RenderGraphExecutor} instead.\r\n *\r\n * @param compiled - The compiled graph from {@link RenderGraph.compile}.\r\n */\r\n execute(compiled: CompiledRenderGraph): void {\r\n const noopCtx: RGExecuteContext = {\r\n getTexture() {\r\n throw new Error(\r\n 'RenderGraph.execute(): resource resolution not available. Use RenderGraphExecutor for managed execution.'\r\n );\r\n },\r\n getFramebuffer() {\r\n throw new Error(\r\n 'RenderGraph.execute(): framebuffer resolution not available. Use RenderGraphExecutor for managed execution.'\r\n );\r\n },\r\n createFramebuffer() {\r\n throw new Error(\r\n 'RenderGraph.execute(): framebuffer allocation not available. Use RenderGraphExecutor for managed execution.'\r\n );\r\n },\r\n deferCleanup() {\r\n // No-op in unmanaged execution mode.\r\n }\r\n };\r\n for (const pass of compiled.orderedPasses) {\r\n if (pass.subpasses.length > 0) {\r\n for (const subpass of pass.subpasses) {\r\n (subpass.executeFn as RGExecuteFn<unknown>)(noopCtx, pass.data);\r\n }\r\n } else if (pass.executeFn) {\r\n (pass.executeFn as RGExecuteFn<unknown>)(noopCtx, pass.data);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Reset the graph for the next frame.\r\n *\r\n * Clears all passes, transient resources, and compiled state.\r\n * Imported resources are also cleared — re-import them each frame.\r\n */\r\n reset(): void {\r\n this._passes.length = 0;\r\n this._resources.clear();\r\n this._nextResourceId = 0;\r\n this._compiled = null;\r\n }\r\n\r\n // ─── Accessors (for testing / debugging) ────────────────────────────\r\n\r\n /** @internal */\r\n getResource(handle: RGHandle): RGResource | undefined {\r\n return this._resources.get(handle._id);\r\n }\r\n\r\n /** @internal */\r\n get passes(): ReadonlyArray<RGPass> {\r\n return this._passes;\r\n }\r\n\r\n /** @internal */\r\n get resources(): ReadonlyMap<number, RGResource> {\r\n return this._resources;\r\n }\r\n\r\n // ─── Private: Builder ───────────────────────────────────────────────\r\n\r\n /** @internal */\r\n private _createBuilder(pass: RGPass): RGPassBuilder {\r\n const graph = this;\r\n return {\r\n read(handle: RGHandle): void {\r\n const res = graph._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n // Validate that transient resources have a producer\r\n if (res.kind === 'transient' && !res.producer) {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" attempts to read transient resource \"${res.name}\" ` +\r\n `which has no producer. Ensure the resource is created before being read.`\r\n );\r\n }\r\n if (!pass.reads.includes(res)) {\r\n pass.reads.push(res);\r\n }\r\n if (!res.consumers.includes(pass)) {\r\n res.consumers.push(pass);\r\n }\r\n },\r\n write(handle: RGHandle): RGHandle {\r\n const res = graph._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n if (res.kind === 'token') {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" attempts to write token \"${res.name}\". ` +\r\n `Use createToken() to produce ordering tokens.`\r\n );\r\n }\r\n if (res.kind === 'framebuffer') {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" attempts to write framebuffer \"${res.name}\". ` +\r\n `Create a new framebuffer view instead.`\r\n );\r\n }\r\n for (const consumer of res.consumers) {\r\n if (consumer !== pass && !pass.dependencies.includes(consumer)) {\r\n pass.dependencies.push(consumer);\r\n }\r\n }\r\n if (res.producer && res.producer !== pass && !pass.dependencies.includes(res.producer)) {\r\n pass.dependencies.push(res.producer);\r\n }\r\n const id = graph._nextResourceId++;\r\n const versionName = `${res.name}@${pass.name}`;\r\n const version = new RGResource(id, versionName, res.kind, res.desc, res.physicalId);\r\n version.producer = pass;\r\n graph._resources.set(id, version);\r\n if (!pass.writes.includes(version)) {\r\n pass.writes.push(version);\r\n }\r\n return new RGHandle(id, versionName);\r\n },\r\n createTexture(desc: RGTextureDesc): RGHandle {\r\n const id = graph._nextResourceId++;\r\n const name = desc.label ?? `_tex_${id}`;\r\n const res = new RGResource(id, name, 'transient', desc);\r\n res.producer = pass;\r\n graph._resources.set(id, res);\r\n pass.writes.push(res);\r\n return new RGHandle(id, name);\r\n },\r\n createToken(name?: string): RGHandle {\r\n const id = graph._nextResourceId++;\r\n const tokenName = name ?? `_token_${id}`;\r\n const res = new RGResource(id, tokenName, 'token', null);\r\n res.producer = pass;\r\n graph._resources.set(id, res);\r\n pass.writes.push(res);\r\n return new RGHandle(id, tokenName);\r\n },\r\n createFramebuffer(desc): RGHandle {\r\n const id = graph._nextResourceId++;\r\n const name = desc.label ?? `_fb_${id}`;\r\n const res = new RGResource(id, name, 'framebuffer', desc);\r\n res.producer = pass;\r\n graph._resources.set(id, res);\r\n pass.writes.push(res);\r\n graph._declareFramebufferAttachmentDeps(pass, desc);\r\n return new RGHandle(id, name);\r\n },\r\n sideEffect(): void {\r\n pass.hasSideEffect = true;\r\n },\r\n addSubpass<D>(name: string, fn: RGExecuteFn<D>): void {\r\n if (pass.executeFn) {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" cannot use addSubpass() after setExecute(). ` +\r\n `Use either subpasses or a single execute callback.`\r\n );\r\n }\r\n pass.subpasses.push(new RGSubpass(name, fn as RGExecuteFn<unknown>));\r\n },\r\n setExecute<D>(fn: RGExecuteFn<D>): void {\r\n if (pass.subpasses.length > 0) {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" cannot use setExecute() after addSubpass(). ` +\r\n `Use either subpasses or a single execute callback.`\r\n );\r\n }\r\n pass.executeFn = fn as RGExecuteFn<unknown>;\r\n }\r\n };\r\n }\r\n\r\n // ─── Private: Dead Pass Culling ─────────────────────────────────────\r\n\r\n /** @internal */\r\n private _validateOutputs(outputs: RGHandle[]): void {\r\n const latestVersions = new Map<number, RGResource>();\r\n for (const res of this._resources.values()) {\r\n const current = latestVersions.get(res.physicalId);\r\n if (!current || res.id > current.id) {\r\n latestVersions.set(res.physicalId, res);\r\n }\r\n }\r\n\r\n for (const handle of outputs) {\r\n const res = this._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown output resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n const latest = latestVersions.get(res.physicalId);\r\n if (latest && latest.id !== res.id) {\r\n throw new Error(\r\n `RenderGraph: output resource \"${res.name}\" (id=${res.id}) is not the latest version. ` +\r\n `Use the handle returned by builder.write(); latest is \"${latest.name}\" (id=${latest.id}).`\r\n );\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n private _cullDeadPasses(outputs: RGHandle[]): void {\r\n // Start with all passes marked dead\r\n for (const pass of this._passes) {\r\n pass.alive = false;\r\n }\r\n\r\n // Seed: resources that are requested outputs\r\n const neededResources = new Set<number>();\r\n const stack: RGResource[] = [];\r\n const markResourceNeeded = (res: RGResource) => {\r\n if (!neededResources.has(res.id)) {\r\n neededResources.add(res.id);\r\n stack.push(res);\r\n }\r\n };\r\n const markPassAlive = (pass: RGPass) => {\r\n if (pass.alive) {\r\n return;\r\n }\r\n pass.alive = true;\r\n for (const dep of pass.reads) {\r\n markResourceNeeded(dep);\r\n }\r\n for (const dependency of pass.dependencies) {\r\n markPassAlive(dependency);\r\n }\r\n };\r\n\r\n for (const handle of outputs) {\r\n const res = this._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown output resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n markResourceNeeded(res);\r\n }\r\n\r\n // Seed: side-effect passes (always alive) — push their read dependencies\r\n for (const pass of this._passes) {\r\n if (pass.hasSideEffect) {\r\n markPassAlive(pass);\r\n }\r\n }\r\n\r\n // Backward traversal: for each needed resource, mark its producer alive\r\n // and recursively mark the producer's read dependencies as needed\r\n while (stack.length > 0) {\r\n const res = stack.pop()!;\r\n const producer = res.producer;\r\n if (producer) {\r\n markPassAlive(producer);\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n private _declareFramebufferAttachmentDeps(\r\n pass: RGPass,\r\n desc: { colorAttachments: unknown | unknown[] | null; depthAttachment?: unknown | null }\r\n ): void {\r\n const declare = (attachment: unknown) => {\r\n if (attachment instanceof RGHandle) {\r\n const res = this._resources.get(attachment._id);\r\n if (!res) {\r\n throw new Error(\r\n `RenderGraph: unknown framebuffer attachment \"${attachment.name}\" (id=${attachment._id})`\r\n );\r\n }\r\n if (res.kind !== 'transient' && res.kind !== 'imported') {\r\n throw new Error(\r\n `RenderGraph: framebuffer attachment \"${res.name}\" must be a texture resource, got ${res.kind}.`\r\n );\r\n }\r\n if (res.producer !== pass) {\r\n if (!pass.reads.includes(res)) {\r\n pass.reads.push(res);\r\n }\r\n if (!res.consumers.includes(pass)) {\r\n res.consumers.push(pass);\r\n }\r\n }\r\n }\r\n };\r\n const colors = Array.isArray(desc.colorAttachments)\r\n ? desc.colorAttachments\r\n : desc.colorAttachments\r\n ? [desc.colorAttachments]\r\n : [];\r\n for (const attachment of colors) {\r\n declare(attachment);\r\n }\r\n declare(desc.depthAttachment);\r\n }\r\n\r\n // ─── Private: Topological Sort (Kahn's Algorithm) ───────────────────\r\n\r\n /** @internal */\r\n private _topologicalSort(): RGPass[] {\r\n const alivePasses = this._passes.filter((p) => p.alive);\r\n if (alivePasses.length === 0) {\r\n return [];\r\n }\r\n\r\n // Build adjacency: producer -> consumers (only among alive passes)\r\n const aliveSet = new Set(alivePasses);\r\n const inDegree = new Map<RGPass, number>();\r\n const adjacency = new Map<RGPass, RGPass[]>();\r\n\r\n for (const pass of alivePasses) {\r\n inDegree.set(pass, 0);\r\n adjacency.set(pass, []);\r\n }\r\n\r\n const addEdge = (from: RGPass, to: RGPass) => {\r\n if (from === to || !aliveSet.has(from) || !aliveSet.has(to)) {\r\n return;\r\n }\r\n const neighbors = adjacency.get(from)!;\r\n if (!neighbors.includes(to)) {\r\n neighbors.push(to);\r\n inDegree.set(to, inDegree.get(to)! + 1);\r\n }\r\n };\r\n\r\n for (const pass of alivePasses) {\r\n for (const dependency of pass.dependencies) {\r\n addEdge(dependency, pass);\r\n }\r\n }\r\n\r\n // For each resource, its producer has an edge to each of its consumers\r\n for (const res of this._resources.values()) {\r\n if (!res.producer || !aliveSet.has(res.producer)) {\r\n continue;\r\n }\r\n for (const consumer of res.consumers) {\r\n addEdge(res.producer, consumer);\r\n }\r\n }\r\n\r\n // Kahn's algorithm\r\n const queue: RGPass[] = [];\r\n for (const pass of alivePasses) {\r\n if (inDegree.get(pass) === 0) {\r\n queue.push(pass);\r\n }\r\n }\r\n\r\n const result: RGPass[] = [];\r\n while (queue.length > 0) {\r\n const pass = queue.shift()!;\r\n result.push(pass);\r\n for (const neighbor of adjacency.get(pass)!) {\r\n const deg = inDegree.get(neighbor)! - 1;\r\n inDegree.set(neighbor, deg);\r\n if (deg === 0) {\r\n queue.push(neighbor);\r\n }\r\n }\r\n }\r\n\r\n if (result.length !== alivePasses.length) {\r\n // Find passes that are part of the cycle (those with non-zero in-degree)\r\n const cycleParticipants: string[] = [];\r\n for (const [pass, degree] of inDegree) {\r\n if (degree > 0) {\r\n cycleParticipants.push(pass.name);\r\n }\r\n }\r\n throw new Error(\r\n `RenderGraph: circular dependency detected. ` +\r\n `Sorted ${result.length} of ${alivePasses.length} alive passes. ` +\r\n `Passes in cycle: [${cycleParticipants.join(', ')}]`\r\n );\r\n }\r\n\r\n return result;\r\n }\r\n\r\n // ─── Private: Resource Lifetime Analysis ────────────────────────────\r\n\r\n /** @internal */\r\n private _analyzeLifetimes(orderedPasses: RGPass[]): Map<number, RGResourceLifetime> {\r\n const lifetimes = new Map<number, RGResourceLifetime>();\r\n\r\n // Build pass -> order index map\r\n const orderMap = new Map<RGPass, number>();\r\n for (let i = 0; i < orderedPasses.length; i++) {\r\n orderMap.set(orderedPasses[i], i);\r\n }\r\n\r\n for (const res of this._resources.values()) {\r\n let first = Infinity;\r\n let last = -Infinity;\r\n\r\n // Producer\r\n if (res.producer && orderMap.has(res.producer)) {\r\n const idx = orderMap.get(res.producer)!;\r\n first = Math.min(first, idx);\r\n last = Math.max(last, idx);\r\n }\r\n\r\n // Consumers\r\n for (const consumer of res.consumers) {\r\n if (orderMap.has(consumer)) {\r\n const idx = orderMap.get(consumer)!;\r\n first = Math.min(first, idx);\r\n last = Math.max(last, idx);\r\n }\r\n }\r\n\r\n if (first !== Infinity) {\r\n lifetimes.set(res.id, { resource: res, firstUse: first, lastUse: last });\r\n }\r\n }\r\n\r\n return lifetimes;\r\n }\r\n}\r\n"],"names":["RenderGraph","_nextResourceId","_resources","Map","_passes","_compiled","importTexture","name","id","resource","RGResource","set","RGHandle","addPass","setup","pass","RGPass","length","builder","_createBuilder","data","push","compile","outputs","_validateOutputs","_cullDeadPasses","ordered","_topologicalSort","lifetimes","_analyzeLifetimes","orderedPasses","execute","compiled","noopCtx","getTexture","Error","getFramebuffer","createFramebuffer","deferCleanup","subpasses","subpass","executeFn","reset","clear","getResource","handle","get","_id","passes","resources","graph","read","res","kind","producer","reads","includes","consumers","write","consumer","dependencies","versionName","version","desc","physicalId","writes","createTexture","label","createToken","tokenName","_declareFramebufferAttachmentDeps","sideEffect","hasSideEffect","addSubpass","fn","RGSubpass","setExecute","latestVersions","values","current","latest","alive","neededResources","Set","stack","markResourceNeeded","has","add","markPassAlive","dep","dependency","pop","declare","attachment","colors","Array","isArray","colorAttachments","depthAttachment","alivePasses","filter","p","aliveSet","inDegree","adjacency","addEdge","from","to","neighbors","queue","result","shift","neighbor","deg","cycleParticipants","degree","join","orderMap","i","first","Infinity","last","idx","Math","min","max","firstUse","lastUse"],"mappings":";;AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BC,IACM,MAAMA,WAAAA,CAAAA;qBAEX,eAAQC,GAAkB,CAAE;AAC5B,qBACQC,UAAsC,GAAA,IAAIC,GAAM,EAAA;AACxD,qBACQC,OAAoB,GAAA,EAAE;qBAE9B,SAAQC,GAAwC,IAAK;;AAIrD;;;;;;;;MASAC,aAAAA,CAAcC,IAAY,EAAY;QACpC,MAAMC,EAAAA,GAAK,IAAI,CAACP,eAAe,EAAA;AAC/B,QAAA,MAAMQ,QAAW,GAAA,IAAIC,UAAWF,CAAAA,EAAAA,EAAID,MAAM,UAAY,EAAA,IAAA,CAAA;AACtD,QAAA,IAAI,CAACL,UAAU,CAACS,GAAG,CAACH,EAAIC,EAAAA,QAAAA,CAAAA;QACxB,IAAI,CAACJ,SAAS,GAAG,IAAA;QACjB,OAAO,IAAIO,SAASJ,EAAID,EAAAA,IAAAA,CAAAA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AAA;gBACxBD,IAAOE,GAAAA,IAAAA,CAAKE,GAAG,CAACJ,IAAMC,EAAAA,GAAAA,CAAAA;AACxB;;AAGA,YAAA,KAAK,MAAM/D,QAAAA,IAAYP,GAAIK,CAAAA,SAAS,CAAE;gBACpC,IAAI4D,QAAAA,CAAS/B,GAAG,CAAC3B,QAAW,CAAA,EAAA;oBAC1B,MAAM+D,GAAAA,GAAML,QAASvE,CAAAA,GAAG,CAACa,QAAAA,CAAAA;oBACzB4D,KAAQI,GAAAA,IAAAA,CAAKC,GAAG,CAACL,KAAOG,EAAAA,GAAAA,CAAAA;oBACxBD,IAAOE,GAAAA,IAAAA,CAAKE,GAAG,CAACJ,IAAMC,EAAAA,GAAAA,CAAAA;AACxB;AACF;AAEA,YAAA,IAAIH,UAAUC,QAAU,EAAA;AACtB5F,gBAAAA,SAAAA,CAAUjB,GAAG,CAACyC,GAAI5C,CAAAA,EAAE,EAAE;oBAAEC,QAAU2C,EAAAA,GAAAA;oBAAK0E,QAAUP,EAAAA,KAAAA;oBAAOQ,OAASN,EAAAA;AAAK,iBAAA,CAAA;AACxE;AACF;QAEA,OAAO7F,SAAAA;AACT;AACF;;;;"}
1
+ {"version":3,"file":"rendergraph.js","sources":["../../../src/render/rendergraph/rendergraph.ts"],"sourcesContent":["import {\r\n RGHandle,\r\n RGResource,\r\n RGPass,\r\n RGSubpass,\r\n type RGTextureDesc,\r\n type RGFramebufferDesc,\r\n type RGPassBuilder,\r\n type RGExecuteFn,\r\n type RGExecuteContext,\r\n type CompiledRenderGraph,\r\n type RGResourceLifetime\r\n} from './types';\r\n\r\n/**\r\n * Render Graph — declarative, configurable render pipeline.\r\n *\r\n * Usage:\r\n * ```ts\r\n * const graph = new RenderGraph();\r\n * let backbuffer = graph.importTexture('backbuffer');\r\n *\r\n * let linearDepth: RGHandle;\r\n * graph.addPass('DepthPrepass', (builder) => {\r\n * linearDepth = builder.createTexture({ format: 'r32f', label: 'linearDepth' });\r\n * builder.setExecute(() => { ... });\r\n * });\r\n *\r\n * graph.addPass('LightPass', (builder) => {\r\n * builder.read(linearDepth);\r\n * backbuffer = builder.write(backbuffer);\r\n * builder.setExecute(() => { ... });\r\n * });\r\n *\r\n * const compiled = graph.compile([backbuffer]);\r\n * graph.execute(compiled);\r\n * graph.reset();\r\n * ```\r\n *\r\n * @public\r\n */\r\nexport class RenderGraph {\r\n /** @internal */\r\n private _nextResourceId = 0;\r\n /** @internal */\r\n private _resources: Map<number, RGResource> = new Map();\r\n /** @internal */\r\n private _passes: RGPass[] = [];\r\n /** @internal */\r\n private _compiled: CompiledRenderGraph | null = null;\r\n\r\n // ─── Graph Building ─────────────────────────────────────────────────\r\n\r\n /**\r\n * Import an external (persistent) texture into the graph.\r\n *\r\n * Imported resources are not allocated or released by the graph.\r\n * Typically used for the backbuffer or any texture that outlives a single frame.\r\n *\r\n * @param name - Debug label for the imported resource.\r\n * @returns A handle referencing the imported resource.\r\n */\r\n importTexture(name: string): RGHandle {\r\n const id = this._nextResourceId++;\r\n const resource = new RGResource(id, name, 'imported', null);\r\n this._resources.set(id, resource);\r\n this._compiled = null;\r\n return new RGHandle(id, name);\r\n }\r\n\r\n /**\r\n * Add a render pass to the graph.\r\n *\r\n * The setup callback receives a {@link RGPassBuilder} to declare resource\r\n * dependencies. Call `builder.setExecute(fn)` inside setup to provide the\r\n * execution callback.\r\n *\r\n * @param name - Debug label for the pass.\r\n * @param setup - Setup callback that declares resources and sets the execute function.\r\n */\r\n addPass<T = void>(name: string, setup: (builder: RGPassBuilder) => T): T {\r\n const pass = new RGPass(this._passes.length, name);\r\n const builder = this._createBuilder(pass);\r\n const data = setup(builder);\r\n pass.data = data;\r\n this._passes.push(pass);\r\n this._compiled = null;\r\n return data;\r\n }\r\n\r\n // ─── Compilation ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Compile the render graph.\r\n *\r\n * Performs dead-pass culling, topological sorting, and resource lifetime analysis.\r\n *\r\n * @param outputs - Handles of resources that must be produced (graph sinks).\r\n * If a resource was passed to {@link RGPassBuilder.write}, use the returned\r\n * post-write handle here, not the original handle.\r\n * Passes that do not contribute to these outputs (directly or transitively)\r\n * are culled, unless marked as side-effect passes.\r\n * @returns The compiled graph ready for execution.\r\n */\r\n compile(outputs: RGHandle[]): CompiledRenderGraph {\r\n this._validateOutputs(outputs);\r\n // 1. Mark alive passes via backward traversal from outputs + side-effect passes\r\n this._cullDeadPasses(outputs);\r\n // 2. Topological sort of alive passes\r\n const ordered = this._topologicalSort();\r\n // 3. Resource lifetime analysis\r\n const lifetimes = this._analyzeLifetimes(ordered);\r\n\r\n this._compiled = { orderedPasses: ordered, lifetimes };\r\n return this._compiled;\r\n }\r\n\r\n /**\r\n * Execute a compiled render graph (simple mode, no resource management).\r\n *\r\n * For automatic resource allocation/release, use {@link RenderGraphExecutor} instead.\r\n *\r\n * @param compiled - The compiled graph from {@link RenderGraph.compile}.\r\n */\r\n execute(compiled: CompiledRenderGraph): void {\r\n const noopCtx: RGExecuteContext = {\r\n getTexture() {\r\n throw new Error(\r\n 'RenderGraph.execute(): resource resolution not available. Use RenderGraphExecutor for managed execution.'\r\n );\r\n },\r\n getFramebuffer() {\r\n throw new Error(\r\n 'RenderGraph.execute(): framebuffer resolution not available. Use RenderGraphExecutor for managed execution.'\r\n );\r\n },\r\n createFramebuffer() {\r\n throw new Error(\r\n 'RenderGraph.execute(): framebuffer allocation not available. Use RenderGraphExecutor for managed execution.'\r\n );\r\n },\r\n deferCleanup() {\r\n // No-op in unmanaged execution mode.\r\n }\r\n };\r\n for (const pass of compiled.orderedPasses) {\r\n if (pass.subpasses.length > 0) {\r\n for (const subpass of pass.subpasses) {\r\n (subpass.executeFn as RGExecuteFn<unknown>)(noopCtx, pass.data);\r\n }\r\n } else if (pass.executeFn) {\r\n (pass.executeFn as RGExecuteFn<unknown>)(noopCtx, pass.data);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Reset the graph for the next frame.\r\n *\r\n * Clears all passes, transient resources, and compiled state.\r\n * Imported resources are also cleared — re-import them each frame.\r\n */\r\n reset(): void {\r\n this._passes.length = 0;\r\n this._resources.clear();\r\n this._nextResourceId = 0;\r\n this._compiled = null;\r\n }\r\n\r\n // ─── Accessors (for testing / debugging) ────────────────────────────\r\n\r\n /** @internal */\r\n getResource(handle: RGHandle): RGResource | undefined {\r\n return this._resources.get(handle._id);\r\n }\r\n\r\n /** @internal */\r\n get passes(): ReadonlyArray<RGPass> {\r\n return this._passes;\r\n }\r\n\r\n /** @internal */\r\n get resources(): ReadonlyMap<number, RGResource> {\r\n return this._resources;\r\n }\r\n\r\n // ─── Private: Builder ───────────────────────────────────────────────\r\n\r\n /** @internal */\r\n private _createBuilder(pass: RGPass): RGPassBuilder {\r\n const graph = this;\r\n return {\r\n read(handle: RGHandle): void {\r\n const res = graph._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n // Validate that transient resources have a producer\r\n if (res.kind === 'transient' && !res.producer) {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" attempts to read transient resource \"${res.name}\" ` +\r\n `which has no producer. Ensure the resource is created before being read.`\r\n );\r\n }\r\n if (!pass.reads.includes(res)) {\r\n pass.reads.push(res);\r\n }\r\n if (!res.consumers.includes(pass)) {\r\n res.consumers.push(pass);\r\n }\r\n },\r\n write(handle: RGHandle): RGHandle {\r\n const res = graph._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n if (res.kind === 'token') {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" attempts to write token \"${res.name}\". ` +\r\n `Use createToken() to produce ordering tokens.`\r\n );\r\n }\r\n if (res.kind === 'framebuffer') {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" attempts to write framebuffer \"${res.name}\". ` +\r\n `Create a new framebuffer view instead.`\r\n );\r\n }\r\n for (const consumer of res.consumers) {\r\n if (consumer !== pass && !pass.dependencies.includes(consumer)) {\r\n pass.dependencies.push(consumer);\r\n }\r\n }\r\n if (res.producer && res.producer !== pass && !pass.dependencies.includes(res.producer)) {\r\n pass.dependencies.push(res.producer);\r\n }\r\n const id = graph._nextResourceId++;\r\n const versionName = `${res.name}@${pass.name}`;\r\n const version = new RGResource(id, versionName, res.kind, res.desc, res.physicalId);\r\n version.producer = pass;\r\n graph._resources.set(id, version);\r\n if (!pass.writes.includes(version)) {\r\n pass.writes.push(version);\r\n }\r\n return new RGHandle(id, versionName);\r\n },\r\n createTexture(desc: RGTextureDesc): RGHandle {\r\n const id = graph._nextResourceId++;\r\n const name = desc.label ?? `_tex_${id}`;\r\n const res = new RGResource(id, name, 'transient', desc);\r\n res.producer = pass;\r\n graph._resources.set(id, res);\r\n pass.writes.push(res);\r\n return new RGHandle(id, name);\r\n },\r\n createToken(name?: string): RGHandle {\r\n const id = graph._nextResourceId++;\r\n const tokenName = name ?? `_token_${id}`;\r\n const res = new RGResource(id, tokenName, 'token', null);\r\n res.producer = pass;\r\n graph._resources.set(id, res);\r\n pass.writes.push(res);\r\n return new RGHandle(id, tokenName);\r\n },\r\n createFramebuffer(desc): RGHandle {\r\n const id = graph._nextResourceId++;\r\n const name = desc.label ?? `_fb_${id}`;\r\n const res = new RGResource(id, name, 'framebuffer', desc);\r\n res.producer = pass;\r\n graph._resources.set(id, res);\r\n pass.writes.push(res);\r\n graph._declareFramebufferAttachmentDeps(pass, desc);\r\n return new RGHandle(id, name);\r\n },\r\n sideEffect(): void {\r\n pass.hasSideEffect = true;\r\n },\r\n addSubpass<D>(name: string, fn: RGExecuteFn<D>): void {\r\n if (pass.executeFn) {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" cannot use addSubpass() after setExecute(). ` +\r\n `Use either subpasses or a single execute callback.`\r\n );\r\n }\r\n pass.subpasses.push(new RGSubpass(name, fn as RGExecuteFn<unknown>));\r\n },\r\n setExecute<D>(fn: RGExecuteFn<D>): void {\r\n if (pass.subpasses.length > 0) {\r\n throw new Error(\r\n `RenderGraph: pass \"${pass.name}\" cannot use setExecute() after addSubpass(). ` +\r\n `Use either subpasses or a single execute callback.`\r\n );\r\n }\r\n pass.executeFn = fn as RGExecuteFn<unknown>;\r\n }\r\n };\r\n }\r\n\r\n // ─── Private: Dead Pass Culling ─────────────────────────────────────\r\n\r\n /** @internal */\r\n private _validateOutputs(outputs: RGHandle[]): void {\r\n const latestVersions = new Map<number, RGResource>();\r\n for (const res of this._resources.values()) {\r\n const current = latestVersions.get(res.physicalId);\r\n if (!current || res.id > current.id) {\r\n latestVersions.set(res.physicalId, res);\r\n }\r\n }\r\n\r\n for (const handle of outputs) {\r\n const res = this._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown output resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n const latest = latestVersions.get(res.physicalId);\r\n if (latest && latest.id !== res.id) {\r\n throw new Error(\r\n `RenderGraph: output resource \"${res.name}\" (id=${res.id}) is not the latest version. ` +\r\n `Use the handle returned by builder.write(); latest is \"${latest.name}\" (id=${latest.id}).`\r\n );\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n private _cullDeadPasses(outputs: RGHandle[]): void {\r\n // Start with all passes marked dead\r\n for (const pass of this._passes) {\r\n pass.alive = false;\r\n }\r\n\r\n // Seed: resources that are requested outputs\r\n const neededResources = new Set<number>();\r\n const stack: RGResource[] = [];\r\n const markResourceNeeded = (res: RGResource) => {\r\n if (!neededResources.has(res.id)) {\r\n neededResources.add(res.id);\r\n stack.push(res);\r\n }\r\n };\r\n const markPassAlive = (pass: RGPass) => {\r\n if (pass.alive) {\r\n return;\r\n }\r\n pass.alive = true;\r\n for (const dep of pass.reads) {\r\n markResourceNeeded(dep);\r\n }\r\n for (const dependency of pass.dependencies) {\r\n markPassAlive(dependency);\r\n }\r\n };\r\n\r\n for (const handle of outputs) {\r\n const res = this._resources.get(handle._id);\r\n if (!res) {\r\n throw new Error(`RenderGraph: unknown output resource \"${handle.name}\" (id=${handle._id})`);\r\n }\r\n markResourceNeeded(res);\r\n }\r\n\r\n // Seed: side-effect passes (always alive) — push their read dependencies\r\n for (const pass of this._passes) {\r\n if (pass.hasSideEffect) {\r\n markPassAlive(pass);\r\n }\r\n }\r\n\r\n // Backward traversal: for each needed resource, mark its producer alive\r\n // and recursively mark the producer's read dependencies as needed\r\n while (stack.length > 0) {\r\n const res = stack.pop()!;\r\n const producer = res.producer;\r\n if (producer) {\r\n markPassAlive(producer);\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n private _declareFramebufferAttachmentDeps(\r\n pass: RGPass,\r\n desc: { colorAttachments: unknown | unknown[] | null; depthAttachment?: unknown | null }\r\n ): void {\r\n const declare = (attachment: unknown) => {\r\n if (attachment instanceof RGHandle) {\r\n const res = this._resources.get(attachment._id);\r\n if (!res) {\r\n throw new Error(\r\n `RenderGraph: unknown framebuffer attachment \"${attachment.name}\" (id=${attachment._id})`\r\n );\r\n }\r\n if (res.kind !== 'transient' && res.kind !== 'imported') {\r\n throw new Error(\r\n `RenderGraph: framebuffer attachment \"${res.name}\" must be a texture resource, got ${res.kind}.`\r\n );\r\n }\r\n if (res.producer !== pass) {\r\n if (!pass.reads.includes(res)) {\r\n pass.reads.push(res);\r\n }\r\n if (!res.consumers.includes(pass)) {\r\n res.consumers.push(pass);\r\n }\r\n }\r\n }\r\n };\r\n const colors = Array.isArray(desc.colorAttachments)\r\n ? desc.colorAttachments\r\n : desc.colorAttachments\r\n ? [desc.colorAttachments]\r\n : [];\r\n for (const attachment of colors) {\r\n declare(attachment);\r\n }\r\n declare(desc.depthAttachment);\r\n }\r\n\r\n // ─── Private: Topological Sort (Kahn's Algorithm) ───────────────────\r\n\r\n /** @internal */\r\n private _topologicalSort(): RGPass[] {\r\n const alivePasses = this._passes.filter((p) => p.alive);\r\n if (alivePasses.length === 0) {\r\n return [];\r\n }\r\n\r\n // Build adjacency: producer -> consumers (only among alive passes)\r\n const aliveSet = new Set(alivePasses);\r\n const inDegree = new Map<RGPass, number>();\r\n const adjacency = new Map<RGPass, RGPass[]>();\r\n\r\n for (const pass of alivePasses) {\r\n inDegree.set(pass, 0);\r\n adjacency.set(pass, []);\r\n }\r\n\r\n const addEdge = (from: RGPass, to: RGPass) => {\r\n if (from === to || !aliveSet.has(from) || !aliveSet.has(to)) {\r\n return;\r\n }\r\n const neighbors = adjacency.get(from)!;\r\n if (!neighbors.includes(to)) {\r\n neighbors.push(to);\r\n inDegree.set(to, inDegree.get(to)! + 1);\r\n }\r\n };\r\n\r\n for (const pass of alivePasses) {\r\n for (const dependency of pass.dependencies) {\r\n addEdge(dependency, pass);\r\n }\r\n }\r\n\r\n // For each resource, its producer has an edge to each of its consumers\r\n for (const res of this._resources.values()) {\r\n if (!res.producer || !aliveSet.has(res.producer)) {\r\n continue;\r\n }\r\n for (const consumer of res.consumers) {\r\n addEdge(res.producer, consumer);\r\n }\r\n }\r\n\r\n // Kahn's algorithm\r\n const queue: RGPass[] = [];\r\n for (const pass of alivePasses) {\r\n if (inDegree.get(pass) === 0) {\r\n queue.push(pass);\r\n }\r\n }\r\n\r\n const result: RGPass[] = [];\r\n while (queue.length > 0) {\r\n const pass = queue.shift()!;\r\n result.push(pass);\r\n for (const neighbor of adjacency.get(pass)!) {\r\n const deg = inDegree.get(neighbor)! - 1;\r\n inDegree.set(neighbor, deg);\r\n if (deg === 0) {\r\n queue.push(neighbor);\r\n }\r\n }\r\n }\r\n\r\n if (result.length !== alivePasses.length) {\r\n // Find passes that are part of the cycle (those with non-zero in-degree)\r\n const cycleParticipants: string[] = [];\r\n for (const [pass, degree] of inDegree) {\r\n if (degree > 0) {\r\n cycleParticipants.push(pass.name);\r\n }\r\n }\r\n throw new Error(\r\n `RenderGraph: circular dependency detected. ` +\r\n `Sorted ${result.length} of ${alivePasses.length} alive passes. ` +\r\n `Passes in cycle: [${cycleParticipants.join(', ')}]`\r\n );\r\n }\r\n\r\n return result;\r\n }\r\n\r\n // ─── Private: Resource Lifetime Analysis ────────────────────────────\r\n\r\n /** @internal */\r\n private _analyzeLifetimes(orderedPasses: RGPass[]): Map<number, RGResourceLifetime> {\r\n const lifetimes = new Map<number, { resource: RGResource; firstUse: number; lastUse: number }>();\r\n\r\n // Build pass -> order index map\r\n const orderMap = new Map<RGPass, number>();\r\n for (let i = 0; i < orderedPasses.length; i++) {\r\n orderMap.set(orderedPasses[i], i);\r\n }\r\n\r\n for (const res of this._resources.values()) {\r\n let first = Infinity;\r\n let last = -Infinity;\r\n\r\n // Producer\r\n if (res.producer && orderMap.has(res.producer)) {\r\n const idx = orderMap.get(res.producer)!;\r\n first = Math.min(first, idx);\r\n last = Math.max(last, idx);\r\n }\r\n\r\n // Consumers\r\n for (const consumer of res.consumers) {\r\n if (orderMap.has(consumer)) {\r\n const idx = orderMap.get(consumer)!;\r\n first = Math.min(first, idx);\r\n last = Math.max(last, idx);\r\n }\r\n }\r\n\r\n if (first !== Infinity) {\r\n lifetimes.set(res.id, { resource: res, firstUse: first, lastUse: last });\r\n }\r\n }\r\n\r\n // A pass that reads a framebuffer implicitly reads its attachment textures:\r\n // extend each RGHandle attachment's lifetime to cover the framebuffer's\r\n // lifetime so the executor never releases a backing texture while a later\r\n // pass can still render through the framebuffer. Framebuffers cannot be\r\n // attachments of other framebuffers, so a single propagation pass suffices.\r\n for (const lifetime of lifetimes.values()) {\r\n const res = lifetime.resource;\r\n if (res.kind !== 'framebuffer' || !res.desc) {\r\n continue;\r\n }\r\n const desc = res.desc as RGFramebufferDesc;\r\n const extend = (attachment: unknown) => {\r\n if (!(attachment instanceof RGHandle)) {\r\n return;\r\n }\r\n const attachmentLifetime = lifetimes.get(attachment._id);\r\n if (attachmentLifetime) {\r\n attachmentLifetime.firstUse = Math.min(attachmentLifetime.firstUse, lifetime.firstUse);\r\n attachmentLifetime.lastUse = Math.max(attachmentLifetime.lastUse, lifetime.lastUse);\r\n }\r\n };\r\n const colors = Array.isArray(desc.colorAttachments)\r\n ? desc.colorAttachments\r\n : desc.colorAttachments\r\n ? [desc.colorAttachments]\r\n : [];\r\n for (const attachment of colors) {\r\n extend(attachment);\r\n }\r\n extend(desc.depthAttachment);\r\n }\r\n\r\n return lifetimes;\r\n }\r\n}\r\n"],"names":["RenderGraph","_nextResourceId","_resources","Map","_passes","_compiled","importTexture","name","id","resource","RGResource","set","RGHandle","addPass","setup","pass","RGPass","length","builder","_createBuilder","data","push","compile","outputs","_validateOutputs","_cullDeadPasses","ordered","_topologicalSort","lifetimes","_analyzeLifetimes","orderedPasses","execute","compiled","noopCtx","getTexture","Error","getFramebuffer","createFramebuffer","deferCleanup","subpasses","subpass","executeFn","reset","clear","getResource","handle","get","_id","passes","resources","graph","read","res","kind","producer","reads","includes","consumers","write","consumer","dependencies","versionName","version","desc","physicalId","writes","createTexture","label","createToken","tokenName","_declareFramebufferAttachmentDeps","sideEffect","hasSideEffect","addSubpass","fn","RGSubpass","setExecute","latestVersions","values","current","latest","alive","neededResources","Set","stack","markResourceNeeded","has","add","markPassAlive","dep","dependency","pop","declare","attachment","colors","Array","isArray","colorAttachments","depthAttachment","alivePasses","filter","p","aliveSet","inDegree","adjacency","addEdge","from","to","neighbors","queue","result","shift","neighbor","deg","cycleParticipants","degree","join","orderMap","i","first","Infinity","last","idx","Math","min","max","firstUse","lastUse","lifetime","extend","attachmentLifetime"],"mappings":";;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BC,IACM,MAAMA,WAAAA,CAAAA;qBAEX,eAAQC,GAAkB,CAAE;AAC5B,qBACQC,UAAsC,GAAA,IAAIC,GAAM,EAAA;AACxD,qBACQC,OAAoB,GAAA,EAAE;qBAE9B,SAAQC,GAAwC,IAAK;;AAIrD;;;;;;;;MASAC,aAAAA,CAAcC,IAAY,EAAY;QACpC,MAAMC,EAAAA,GAAK,IAAI,CAACP,eAAe,EAAA;AAC/B,QAAA,MAAMQ,QAAW,GAAA,IAAIC,UAAWF,CAAAA,EAAAA,EAAID,MAAM,UAAY,EAAA,IAAA,CA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AA;AACrC,oBAAA;AACF;AACA,gBAAA,MAAMsH,kBAAqBtG,GAAAA,SAAAA,CAAUkB,GAAG,CAAC+C,WAAW9C,GAAG,CAAA;AACvD,gBAAA,IAAImF,kBAAoB,EAAA;oBACtBA,kBAAmBJ,CAAAA,QAAQ,GAAGH,IAAKC,CAAAA,GAAG,CAACM,kBAAmBJ,CAAAA,QAAQ,EAAEE,QAAAA,CAASF,QAAQ,CAAA;oBACrFI,kBAAmBH,CAAAA,OAAO,GAAGJ,IAAKE,CAAAA,GAAG,CAACK,kBAAmBH,CAAAA,OAAO,EAAEC,QAAAA,CAASD,OAAO,CAAA;AACpF;AACF,aAAA;AACA,YAAA,MAAMjC,MAASC,GAAAA,KAAAA,CAAMC,OAAO,CAACjC,IAAKkC,CAAAA,gBAAgB,CAC9ClC,GAAAA,IAAAA,CAAKkC,gBAAgB,GACrBlC,IAAKkC,CAAAA,gBAAgB,GACnB;AAAClC,gBAAAA,IAAAA,CAAKkC;AAAiB,aAAA,GACvB,EAAE;YACR,KAAK,MAAMJ,cAAcC,MAAQ,CAAA;gBAC/BmC,MAAOpC,CAAAA,UAAAA,CAAAA;AACT;AACAoC,YAAAA,MAAAA,CAAOlE,KAAKmC,eAAe,CAAA;AAC7B;QAEA,OAAOtE,SAAAA;AACT;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../../src/render/rendergraph/types.ts"],"sourcesContent":["import type { AbstractDevice, TextureFormat, TimestampQueryStatus } from '@zephyr3d/device';\r\n\r\n// ─── Resource Descriptors ───────────────────────────────────────────────\r\n\r\n/**\r\n * Sizing mode for render graph textures.\r\n *\r\n * - 'absolute': fixed pixel dimensions\r\n * - 'backbuffer-relative': scaled relative to the backbuffer size\r\n *\r\n * @public\r\n */\r\nexport type RGSizeMode = 'absolute' | 'backbuffer-relative';\r\n\r\n/**\r\n * Descriptor for a transient texture resource within the render graph.\r\n *\r\n * Transient textures are allocated and released automatically by the graph compiler.\r\n *\r\n * @public\r\n */\r\nexport interface RGTextureDesc {\r\n /** Debug label for this resource. */\r\n label?: string;\r\n /** Texture format (e.g. 'rgba8unorm', 'r32f', 'rgba16f'). */\r\n format: TextureFormat;\r\n /** Sizing mode. Default 'backbuffer-relative'. */\r\n sizeMode?: RGSizeMode;\r\n /** Width in pixels (absolute) or scale factor (backbuffer-relative, default 1.0). */\r\n width?: number;\r\n /** Height in pixels (absolute) or scale factor (backbuffer-relative, default 1.0). */\r\n height?: number;\r\n /** Number of mip levels. Default 1. */\r\n mipLevels?: number;\r\n}\r\n\r\n// ─── Handles ────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Opaque handle referencing a resource within the render graph.\r\n *\r\n * Handles are obtained from {@link RGPassBuilder.createTexture}, {@link RGPassBuilder.createFramebuffer},\r\n * {@link RenderGraph.importTexture}, or {@link RGPassBuilder.write}. They are lightweight identifiers\r\n * used to declare dependencies between passes.\r\n *\r\n * @public\r\n */\r\nexport class RGHandle {\r\n /** @internal */\r\n readonly _id: number;\r\n /** @internal */\r\n readonly _name: string;\r\n\r\n /** @internal */\r\n constructor(id: number, name: string) {\r\n this._id = id;\r\n this._name = name;\r\n }\r\n\r\n /** Debug-friendly name of the referenced resource. */\r\n get name(): string {\r\n return this._name;\r\n }\r\n}\r\n\r\n// ─── Internal Resource Tracking ─────────────────────────────────────────\r\n\r\n/** @public */\r\nexport type RGResourceKind = 'transient' | 'imported' | 'token' | 'framebuffer';\r\n\r\n/**\r\n * Internal bookkeeping for a resource within the render graph.\r\n * @public\r\n */\r\nexport class RGResource {\r\n readonly id: number;\r\n readonly name: string;\r\n readonly kind: RGResourceKind;\r\n readonly desc: RGTextureDesc | RGFramebufferDesc | null;\r\n /** Resource ID of the physical backing resource used by imported versions. */\r\n readonly physicalId: number;\r\n /** The pass that creates / writes this resource (null for imported until written). */\r\n producer: RGPass | null = null;\r\n /** Passes that read this resource. */\r\n readonly consumers: RGPass[] = [];\r\n\r\n constructor(\r\n id: number,\r\n name: string,\r\n kind: RGResourceKind,\r\n desc: RGTextureDesc | RGFramebufferDesc | null,\r\n physicalId = id\r\n ) {\r\n this.id = id;\r\n this.name = name;\r\n this.kind = kind;\r\n this.desc = desc;\r\n this.physicalId = physicalId;\r\n }\r\n}\r\n\r\n// ─── Internal Pass Tracking ─────────────────────────────────────────────\r\n\r\n// ─── Execution Context ──────────────────────────────────────────────\r\n\r\n/**\r\n * Context passed to pass execute callbacks during graph execution.\r\n *\r\n * Provides access to resolved GPU resources by their handles.\r\n *\r\n * @public\r\n */\r\nexport interface RGExecuteContext {\r\n /**\r\n * Resolve a handle to the actual GPU texture object.\r\n *\r\n * For transient resources, this returns the texture allocated by the executor.\r\n * For imported resources, this returns the texture registered via\r\n * {@link RenderGraphExecutor.setImportedTexture}. The handle must be declared\r\n * by the current pass with {@link RGPassBuilder.read} or {@link RGPassBuilder.write}.\r\n *\r\n * @param handle - Handle of the resource to resolve.\r\n * @returns The resolved texture object (type depends on the allocator).\r\n */\r\n getTexture<TTexture = unknown>(handle: RGHandle): TTexture;\r\n\r\n /**\r\n * Resolve a framebuffer handle to the actual backend framebuffer object.\r\n *\r\n * The handle must be declared by the current pass with {@link RGPassBuilder.read}\r\n * or created by the same pass with {@link RGPassBuilder.createFramebuffer}.\r\n *\r\n * @param handle - Handle returned from {@link RGPassBuilder.createFramebuffer}.\r\n * @returns The resolved framebuffer object (type depends on the allocator).\r\n */\r\n getFramebuffer<TFramebuffer = unknown>(handle: RGHandle): TFramebuffer;\r\n\r\n /**\r\n * Create a temporary framebuffer managed by the graph executor.\r\n *\r\n * The framebuffer is released automatically when graph execution finishes or\r\n * aborts. Attachments may be actual backend resources or texture formats,\r\n * depending on the allocator implementation. If an attachment is an\r\n * {@link RGHandle}, the current pass must declare it with\r\n * {@link RGPassBuilder.read} or {@link RGPassBuilder.write}.\r\n *\r\n * @param desc - Framebuffer descriptor.\r\n * @returns The allocated framebuffer object (type depends on the allocator).\r\n */\r\n createFramebuffer<TFramebuffer = unknown>(desc: RGFramebufferDesc): TFramebuffer;\r\n\r\n /**\r\n * Register a cleanup callback to run when graph execution finishes or aborts.\r\n *\r\n * Callbacks run in reverse registration order. Use this for temporary objects\r\n * created inside pass execution that are not graph resources, such as pooled\r\n * framebuffers wrapping graph-managed textures. If pass execution throws, the\r\n * executor still runs cleanup callbacks and preserves the original pass error\r\n * ahead of cleanup errors.\r\n *\r\n * @param callback - Cleanup function to invoke after execution.\r\n */\r\n deferCleanup(callback: () => void): void;\r\n}\r\n\r\n/**\r\n * Execute callback signature.\r\n *\r\n * The callback receives a context for resolving handles to GPU resources,\r\n * plus the user data returned from the setup function.\r\n *\r\n * @public\r\n */\r\nexport type RGExecuteFn<T = void> = (ctx: RGExecuteContext, data: T) => void;\r\n\r\n/**\r\n * Ordered execution step inside a render graph pass.\r\n *\r\n * Subpasses share the parent pass's resource declarations, lifetime, culling,\r\n * and access validation. They are intended to make multi-step pass bodies\r\n * explicit without splitting graph-level resource dependencies.\r\n *\r\n * @public\r\n */\r\nexport class RGSubpass<T = unknown> {\r\n readonly name: string;\r\n readonly executeFn: RGExecuteFn<T>;\r\n\r\n constructor(name: string, executeFn: RGExecuteFn<T>) {\r\n this.name = name;\r\n this.executeFn = executeFn;\r\n }\r\n}\r\n\r\n/**\r\n * Internal bookkeeping for a pass within the render graph.\r\n * @public\r\n */\r\nexport class RGPass<T = unknown> {\r\n readonly index: number;\r\n readonly name: string;\r\n /** Resources this pass reads (dependencies). */\r\n readonly reads: RGResource[] = [];\r\n /** Resources this pass creates or writes. */\r\n readonly writes: RGResource[] = [];\r\n /** Passes that must complete before this pass due to non-resource hazards. */\r\n readonly dependencies: RGPass[] = [];\r\n /** Whether this pass has side effects and must not be culled. */\r\n hasSideEffect = false;\r\n /** User data returned from the setup function. */\r\n data: T | null = null;\r\n /** Execute callback. */\r\n executeFn: RGExecuteFn<T> | null = null;\r\n /** Ordered subpasses for passes with multiple logical execution steps. */\r\n readonly subpasses: RGSubpass<T>[] = [];\r\n /** Set during compilation: true if this pass is needed. */\r\n alive = true;\r\n\r\n constructor(index: number, name: string) {\r\n this.index = index;\r\n this.name = name;\r\n }\r\n}\r\n\r\n// ─── Pass Builder ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * Builder interface used within the setup callback of {@link RenderGraph.addPass}\r\n * to declare a pass's resource requirements.\r\n *\r\n * @public\r\n */\r\nexport interface RGPassBuilder {\r\n /**\r\n * Declare a read dependency on an existing resource.\r\n *\r\n * The resource must have been created by a prior pass or imported into the graph.\r\n *\r\n * @param handle - Handle of the resource to read.\r\n */\r\n read(handle: RGHandle): void;\r\n\r\n /**\r\n * Declare that this pass writes a new version of an existing resource.\r\n *\r\n * The returned handle represents the post-write version. Use it for subsequent\r\n * reads and as the graph output passed to {@link RenderGraph.compile}. Passing\r\n * an older version of the same resource to `compile()` is rejected because it\r\n * usually means the caller ignored the handle returned by `write()`. If the pass\r\n * needs the previous contents, call {@link RGPassBuilder.read} on the input handle explicitly\r\n * before writing.\r\n *\r\n * @param handle - Handle of the resource to write to.\r\n * @returns A handle referencing the newly written version.\r\n */\r\n write(handle: RGHandle): RGHandle;\r\n\r\n /**\r\n * Create a new transient texture resource that this pass will produce.\r\n *\r\n * @param desc - Texture descriptor.\r\n * @returns A handle referencing the newly created resource.\r\n */\r\n createTexture(desc: RGTextureDesc): RGHandle;\r\n\r\n /**\r\n * Create a logical dependency token produced by this pass.\r\n *\r\n * Tokens do not resolve to GPU resources and are not allocated by the executor.\r\n * They are useful for ordering passes whose dependencies are side effects rather\r\n * than texture reads/writes.\r\n *\r\n * @param name - Debug label for this token.\r\n * @returns A handle referencing the newly created token.\r\n */\r\n createToken(name?: string): RGHandle;\r\n\r\n /**\r\n * Create a graph-managed framebuffer view.\r\n *\r\n * The graph compiler infers dependencies from any attachment handles in the\r\n * descriptor. The executor creates and releases the framebuffer automatically.\r\n *\r\n * @param desc - Framebuffer descriptor.\r\n * @returns A handle referencing the framebuffer view.\r\n */\r\n createFramebuffer(desc: RGFramebufferDesc): RGHandle;\r\n\r\n /**\r\n * Mark this pass as having side effects.\r\n *\r\n * Side-effect passes are never culled by the graph compiler, regardless of\r\n * whether their outputs are consumed. Use this for GPU readback, picking,\r\n * debug overlays, etc.\r\n */\r\n sideEffect(): void;\r\n\r\n /**\r\n * Add an ordered logical subpass to this pass.\r\n *\r\n * Subpasses execute in registration order and share the parent pass's declared\r\n * reads, writes, framebuffer views, and user data. A pass may use either\r\n * subpasses or {@link RGPassBuilder.setExecute}, but not both.\r\n *\r\n * @param name - Debug label for the subpass.\r\n * @param fn - Callback invoked when this subpass executes.\r\n */\r\n addSubpass<D>(name: string, fn: RGExecuteFn<D>): void;\r\n\r\n /**\r\n * Set the execution callback for this pass.\r\n *\r\n * A pass may use either this method or {@link RGPassBuilder.addSubpass}, but not both.\r\n *\r\n * @param fn - Callback invoked during graph execution.\r\n */\r\n setExecute<D>(fn: RGExecuteFn<D>): void;\r\n}\r\n\r\n// ─── Compiled Graph ─────────────────────────────────────────────────────\r\n\r\n/**\r\n * Lifetime information for a resource within the compiled graph.\r\n *\r\n * @public\r\n */\r\nexport interface RGResourceLifetime {\r\n /** The resource. */\r\n readonly resource: RGResource;\r\n /** Index of the first pass that uses (produces or reads) this resource. */\r\n readonly firstUse: number;\r\n /** Index of the last pass that uses this resource. */\r\n readonly lastUse: number;\r\n}\r\n\r\n/**\r\n * Result of compiling a render graph.\r\n *\r\n * Contains the ordered list of passes to execute and lifetime information\r\n * for automatic resource management.\r\n *\r\n * @public\r\n */\r\nexport interface CompiledRenderGraph {\r\n /** Topologically sorted passes (only non-culled passes). */\r\n readonly orderedPasses: ReadonlyArray<RGPass>;\r\n /** Resource lifetime information keyed by resource ID. */\r\n readonly lifetimes: ReadonlyMap<number, RGResourceLifetime>;\r\n}\r\n\r\n/**\r\n * Profiling scope type in a render graph timing tree.\r\n * @public\r\n */\r\nexport type RGProfileScopeType = 'graph' | 'pass' | 'subpass';\r\n\r\n/**\r\n * Render graph GPU timestamp profiling options.\r\n * @public\r\n */\r\nexport interface RGProfilingOptions {\r\n /** Enable render graph timestamp profiling. Default true when an options object is provided. */\r\n enabled?: boolean;\r\n /** Measure the whole graph execution. Default true. */\r\n graph?: boolean;\r\n /** Measure every render graph pass. Default true. */\r\n pass?: boolean;\r\n /** Measure every subpass and expose it as a child scope. Default true. */\r\n subpass?: boolean;\r\n /** Include pending upload/copy commands at timestamp boundaries. Default true. */\r\n includePendingUploads?: boolean;\r\n /** Allow graph profile scopes to remain open across frame boundaries. Default false. */\r\n allowCrossFrame?: boolean;\r\n /** Maximum unresolved profile frames kept by the executor. Default 3. */\r\n maxPendingFrames?: number;\r\n /** Root graph profile label. Default 'RenderGraph'. */\r\n label?: string;\r\n /** Device used for timestamp queries. If omitted, the scene global getDevice() is used. */\r\n device?: AbstractDevice;\r\n}\r\n\r\n/**\r\n * Render graph executor construction options.\r\n * @public\r\n */\r\nexport interface RenderGraphExecutorOptions {\r\n /** Device used for timestamp queries. If omitted, the scene global getDevice() is used. */\r\n device?: AbstractDevice;\r\n /** Render graph timestamp profiling options. Default false. */\r\n profiling?: boolean | RGProfilingOptions;\r\n}\r\n\r\n/**\r\n * Resolved GPU timing for one graph/pass/subpass scope.\r\n * @public\r\n */\r\nexport interface RGProfileScopeResult {\r\n /** Scope label. */\r\n name: string;\r\n /** Scope type. */\r\n type: RGProfileScopeType;\r\n /** Timestamp query id used by the device, or 0 for synthetic/unsupported scopes. */\r\n queryId: number;\r\n /** GPU duration in milliseconds. */\r\n durationMs: number;\r\n /** Timestamp result status. */\r\n status: TimestampQueryStatus;\r\n /** Child scopes. */\r\n children: RGProfileScopeResult[];\r\n /** Optional diagnostic message. */\r\n message?: string;\r\n}\r\n\r\n/**\r\n * Resolved GPU timing tree for one render graph execution.\r\n * @public\r\n */\r\nexport interface RGProfileResult {\r\n /** Render frame id when profiling began. */\r\n frameId: number;\r\n /** Aggregate profile status. */\r\n status: TimestampQueryStatus;\r\n /** Root graph scope. */\r\n graph: RGProfileScopeResult;\r\n /** Top-level pass scopes. Same objects as graph.children. */\r\n passes: RGProfileScopeResult[];\r\n}\r\n\r\n// ─── Texture Allocator ──────────────────────────────────────────────\r\n\r\n/**\r\n * Resolved dimensions for a texture allocation.\r\n * @public\r\n */\r\nexport interface RGResolvedSize {\r\n width: number;\r\n height: number;\r\n}\r\n\r\n/**\r\n * Descriptor for a framebuffer view managed by the graph or created temporarily during pass execution.\r\n *\r\n * This is intentionally backend-agnostic: graph-managed descriptors may use\r\n * {@link RGHandle} attachments, and executor-created descriptors use resolved\r\n * resources or texture formats understood by the allocator.\r\n *\r\n * @public\r\n */\r\nexport interface RGFramebufferDesc {\r\n /** Debug label for this framebuffer. */\r\n label?: string;\r\n /** Framebuffer width. Required when attachments are formats. */\r\n width?: number;\r\n /** Framebuffer height. Required when attachments are formats. */\r\n height?: number;\r\n /** Color attachments or formats. */\r\n colorAttachments: unknown | unknown[] | null;\r\n /** Depth/stencil attachment or format. */\r\n depthAttachment?: unknown | null;\r\n /** Whether color attachments created from formats should support mipmapping. */\r\n mipmapping?: boolean;\r\n /** Framebuffer sample count. */\r\n sampleCount?: number;\r\n /** Whether to ignore depth/stencil during MSAA resolve. */\r\n ignoreDepthStencil?: boolean;\r\n /** Attachment mip level. */\r\n attachmentMipLevel?: number;\r\n /** Attachment cubemap face. */\r\n attachmentCubeface?: number;\r\n /** Attachment array layer. */\r\n attachmentLayer?: number;\r\n}\r\n\r\n/**\r\n * Interface for allocating and releasing transient textures.\r\n *\r\n * Implement this to bridge the render graph with your GPU device's resource pool.\r\n * The executor calls `allocate()` before a resource's first use and\r\n * `release()` after its last use.\r\n *\r\n * @typeParam TTexture - The concrete texture type (e.g. `Texture2D`).\r\n * @public\r\n */\r\nexport interface RGTextureAllocator<TTexture = unknown, TFramebuffer = unknown> {\r\n /**\r\n * Allocate a transient texture matching the given descriptor and resolved size.\r\n *\r\n * @param desc - The texture descriptor from the pass builder.\r\n * @param size - The resolved pixel dimensions.\r\n * @returns The allocated texture object.\r\n */\r\n allocate(desc: RGTextureDesc, size: RGResolvedSize): TTexture;\r\n\r\n /**\r\n * Release a previously allocated transient texture back to the pool.\r\n *\r\n * @param texture - The texture to release.\r\n */\r\n release(texture: TTexture): void;\r\n\r\n /**\r\n * Retain a texture allocated by this allocator so it can outlive the graph pass\r\n * that produced it.\r\n *\r\n * This is used when a graph-produced transient texture must be handed off to\r\n * an external owner, such as a cross-frame history resource. Executors still\r\n * release the graph's own reference at the resource's last use; the external\r\n * owner must later call {@link RGTextureAllocator.release} for the retained\r\n * reference.\r\n *\r\n * Allocators that cannot retain transient textures should leave this undefined.\r\n */\r\n retain?(texture: TTexture): void;\r\n\r\n /**\r\n * Allocate a temporary framebuffer matching the given descriptor.\r\n *\r\n * Implementations should not auto-release this framebuffer; the graph executor\r\n * calls {@link RGTextureAllocator.releaseFramebuffer} when execution completes or aborts.\r\n *\r\n * @param desc - Framebuffer descriptor.\r\n * @returns The allocated framebuffer object.\r\n */\r\n allocateFramebuffer?(desc: RGFramebufferDesc): TFramebuffer;\r\n\r\n /**\r\n * Release a previously allocated temporary framebuffer.\r\n *\r\n * @param framebuffer - The framebuffer to release.\r\n */\r\n releaseFramebuffer?(framebuffer: TFramebuffer): void;\r\n}\r\n"],"names":["RGHandle","id","name","_id","_name","RGResource","kind","desc","producer","consumers","physicalId","RGSubpass","executeFn","RGPass","index","reads","writes","dependencies","hasSideEffect","data","subpasses","alive"],"mappings":"AAoCA;AAEA;;;;;;;;AAQC,IACM,MAAMA,QAAAA,CAAAA;qBAEX,GAAqB;qBAErB,KAAuB;AAEvB,qBACA,WAAA,CAAYC,EAAU,EAAEC,IAAY,CAAE;QACpC,IAAI,CAACC,GAAG,GAAGF,EAAAA;QACX,IAAI,CAACG,KAAK,GAAGF,IAAAA;AACf;2DAGA,IAAIA,IAAe,GAAA;QACjB,OAAO,IAAI,CAACE,KAAK;AACnB;AACF;AAOA;;;AAGC,IACM,MAAMC,UAAAA,CAAAA;IACFJ,EAAW;IACXC,IAAa;IACbI,IAAqB;IACrBC,IAA+C;mFAExD,UAA4B;2FAE5BC,WAA0B,IAAK;AAC/B,2CACSC,SAAsB,GAAA,EAAE;IAEjC,WACER,CAAAA,EAAU,EACVC,IAAY,EACZI,IAAoB,EACpBC,IAA8C,EAC9CG,UAAaT,GAAAA,EAAE,CACf;QACA,IAAI,CAACA,EAAE,GAAGA,EAAAA;QACV,IAAI,CAACC,IAAI,GAAGA,IAAAA;QACZ,IAAI,CAACI,IAAI,GAAGA,IAAAA;QACZ,IAAI,CAACC,IAAI,GAAGA,IAAAA;QACZ,IAAI,CAACG,UAAU,GAAGA,UAAAA;AACpB;AACF;AA4EA;;;;;;;;AAQC,IACM,MAAMC,SAAAA,CAAAA;IACFT,IAAa;IACbU,SAA0B;IAEnC,WAAYV,CAAAA,IAAY,EAAEU,SAAyB,CAAE;QACnD,IAAI,CAACV,IAAI,GAAGA,IAAAA;QACZ,IAAI,CAACU,SAAS,GAAGA,SAAAA;AACnB;AACF;AAEA;;;AAGC,IACM,MAAMC,MAAAA,CAAAA;IACFC,KAAc;IACdZ,IAAa;AACtB,qDACSa,KAAsB,GAAA,EAAE;AACjC,kDACSC,MAAuB,GAAA,EAAE;AAClC,mFACSC,YAAyB,GAAA,EAAE;sEAEpCC,gBAAgB,KAAM;uDAEtBC,OAAiB,IAAK;6BAEtBP,YAAmC,IAAK;AACxC,+EACSQ,SAA4B,GAAA,EAAE;gEAEvCC,QAAQ,IAAK;IAEb,WAAYP,CAAAA,KAAa,EAAEZ,IAAY,CAAE;QACvC,IAAI,CAACY,KAAK,GAAGA,KAAAA;QACb,IAAI,CAACZ,IAAI,GAAGA,IAAAA;AACd;AACF;;;;"}
1
+ {"version":3,"file":"types.js","sources":["../../../src/render/rendergraph/types.ts"],"sourcesContent":["import type { AbstractDevice, TextureFormat, TimestampQueryStatus } from '@zephyr3d/device';\r\n\r\n// ─── Resource Descriptors ───────────────────────────────────────────────\r\n\r\n/**\r\n * Sizing mode for render graph textures.\r\n *\r\n * - 'absolute': fixed pixel dimensions\r\n * - 'backbuffer-relative': scaled relative to the backbuffer size\r\n *\r\n * @public\r\n */\r\nexport type RGSizeMode = 'absolute' | 'backbuffer-relative';\r\n\r\n/**\r\n * Descriptor for a transient texture resource within the render graph.\r\n *\r\n * Transient textures are allocated and released automatically by the graph compiler.\r\n *\r\n * @public\r\n */\r\nexport interface RGTextureDesc {\r\n /** Debug label for this resource. */\r\n label?: string;\r\n /** Texture format (e.g. 'rgba8unorm', 'r32f', 'rgba16f'). */\r\n format: TextureFormat;\r\n /** Sizing mode. Default 'backbuffer-relative'. */\r\n sizeMode?: RGSizeMode;\r\n /** Width in pixels (absolute) or scale factor (backbuffer-relative, default 1.0). */\r\n width?: number;\r\n /** Height in pixels (absolute) or scale factor (backbuffer-relative, default 1.0). */\r\n height?: number;\r\n /** Number of mip levels. Default 1. */\r\n mipLevels?: number;\r\n}\r\n\r\n// ─── Handles ────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Opaque handle referencing a resource within the render graph.\r\n *\r\n * Handles are obtained from {@link RGPassBuilder.createTexture}, {@link RGPassBuilder.createFramebuffer},\r\n * {@link RenderGraph.importTexture}, or {@link RGPassBuilder.write}. They are lightweight identifiers\r\n * used to declare dependencies between passes.\r\n *\r\n * @public\r\n */\r\nexport class RGHandle {\r\n /** @internal */\r\n readonly _id: number;\r\n /** @internal */\r\n readonly _name: string;\r\n\r\n /** @internal */\r\n constructor(id: number, name: string) {\r\n this._id = id;\r\n this._name = name;\r\n }\r\n\r\n /** Debug-friendly name of the referenced resource. */\r\n get name(): string {\r\n return this._name;\r\n }\r\n}\r\n\r\n// ─── Internal Resource Tracking ─────────────────────────────────────────\r\n\r\n/** @public */\r\nexport type RGResourceKind = 'transient' | 'imported' | 'token' | 'framebuffer';\r\n\r\n/**\r\n * Internal bookkeeping for a resource within the render graph.\r\n * @public\r\n */\r\nexport class RGResource {\r\n readonly id: number;\r\n readonly name: string;\r\n readonly kind: RGResourceKind;\r\n readonly desc: RGTextureDesc | RGFramebufferDesc | null;\r\n /** Resource ID of the physical backing resource used by imported versions. */\r\n readonly physicalId: number;\r\n /** The pass that creates / writes this resource (null for imported until written). */\r\n producer: RGPass | null = null;\r\n /** Passes that read this resource. */\r\n readonly consumers: RGPass[] = [];\r\n\r\n constructor(\r\n id: number,\r\n name: string,\r\n kind: RGResourceKind,\r\n desc: RGTextureDesc | RGFramebufferDesc | null,\r\n physicalId = id\r\n ) {\r\n this.id = id;\r\n this.name = name;\r\n this.kind = kind;\r\n this.desc = desc;\r\n this.physicalId = physicalId;\r\n }\r\n}\r\n\r\n// ─── Internal Pass Tracking ─────────────────────────────────────────────\r\n\r\n// ─── Execution Context ──────────────────────────────────────────────\r\n\r\n/**\r\n * Context passed to pass execute callbacks during graph execution.\r\n *\r\n * Provides access to resolved GPU resources by their handles.\r\n *\r\n * @public\r\n */\r\nexport interface RGExecuteContext {\r\n /**\r\n * Resolve a handle to the actual GPU texture object.\r\n *\r\n * For transient resources, this returns the texture allocated by the executor.\r\n * For imported resources, this returns the texture registered via\r\n * {@link RenderGraphExecutor.setImportedTexture}. The handle must be declared\r\n * by the current pass with {@link RGPassBuilder.read} or {@link RGPassBuilder.write}.\r\n *\r\n * @param handle - Handle of the resource to resolve.\r\n * @returns The resolved texture object (type depends on the allocator).\r\n */\r\n getTexture<TTexture = unknown>(handle: RGHandle): TTexture;\r\n\r\n /**\r\n * Resolve a framebuffer handle to the actual backend framebuffer object.\r\n *\r\n * The handle must be declared by the current pass with {@link RGPassBuilder.read}\r\n * or created by the same pass with {@link RGPassBuilder.createFramebuffer}.\r\n *\r\n * @param handle - Handle returned from {@link RGPassBuilder.createFramebuffer}.\r\n * @returns The resolved framebuffer object (type depends on the allocator).\r\n */\r\n getFramebuffer<TFramebuffer = unknown>(handle: RGHandle): TFramebuffer;\r\n\r\n /**\r\n * Create a temporary framebuffer managed by the graph executor.\r\n *\r\n * The framebuffer is released automatically when graph execution finishes or\r\n * aborts. Attachments may be actual backend resources or texture formats,\r\n * depending on the allocator implementation. If an attachment is an\r\n * {@link RGHandle}, the current pass must declare it with\r\n * {@link RGPassBuilder.read} or {@link RGPassBuilder.write}.\r\n *\r\n * @param desc - Framebuffer descriptor.\r\n * @returns The allocated framebuffer object (type depends on the allocator).\r\n */\r\n createFramebuffer<TFramebuffer = unknown>(desc: RGFramebufferDesc): TFramebuffer;\r\n\r\n /**\r\n * Register a cleanup callback to run when graph execution finishes or aborts.\r\n *\r\n * Callbacks run in reverse registration order. Use this for temporary objects\r\n * created inside pass execution that are not graph resources, such as pooled\r\n * framebuffers wrapping graph-managed textures. If pass execution throws, the\r\n * executor still runs cleanup callbacks and preserves the original pass error\r\n * ahead of cleanup errors.\r\n *\r\n * @param callback - Cleanup function to invoke after execution.\r\n */\r\n deferCleanup(callback: () => void): void;\r\n}\r\n\r\n/**\r\n * Execute callback signature.\r\n *\r\n * The callback receives a context for resolving handles to GPU resources,\r\n * plus the user data returned from the setup function.\r\n *\r\n * @public\r\n */\r\nexport type RGExecuteFn<T = void> = (ctx: RGExecuteContext, data: T) => void;\r\n\r\n/**\r\n * Ordered execution step inside a render graph pass.\r\n *\r\n * Subpasses share the parent pass's resource declarations, lifetime, culling,\r\n * and access validation. They are intended to make multi-step pass bodies\r\n * explicit without splitting graph-level resource dependencies.\r\n *\r\n * @public\r\n */\r\nexport class RGSubpass<T = unknown> {\r\n readonly name: string;\r\n readonly executeFn: RGExecuteFn<T>;\r\n\r\n constructor(name: string, executeFn: RGExecuteFn<T>) {\r\n this.name = name;\r\n this.executeFn = executeFn;\r\n }\r\n}\r\n\r\n/**\r\n * Internal bookkeeping for a pass within the render graph.\r\n * @public\r\n */\r\nexport class RGPass<T = unknown> {\r\n readonly index: number;\r\n readonly name: string;\r\n /** Resources this pass reads (dependencies). */\r\n readonly reads: RGResource[] = [];\r\n /** Resources this pass creates or writes. */\r\n readonly writes: RGResource[] = [];\r\n /** Passes that must complete before this pass due to non-resource hazards. */\r\n readonly dependencies: RGPass[] = [];\r\n /** Whether this pass has side effects and must not be culled. */\r\n hasSideEffect = false;\r\n /** User data returned from the setup function. */\r\n data: T | null = null;\r\n /** Execute callback. */\r\n executeFn: RGExecuteFn<T> | null = null;\r\n /** Ordered subpasses for passes with multiple logical execution steps. */\r\n readonly subpasses: RGSubpass<T>[] = [];\r\n /** Set during compilation: true if this pass is needed. */\r\n alive = true;\r\n\r\n constructor(index: number, name: string) {\r\n this.index = index;\r\n this.name = name;\r\n }\r\n}\r\n\r\n// ─── Pass Builder ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * Builder interface used within the setup callback of {@link RenderGraph.addPass}\r\n * to declare a pass's resource requirements.\r\n *\r\n * @public\r\n */\r\nexport interface RGPassBuilder {\r\n /**\r\n * Declare a read dependency on an existing resource.\r\n *\r\n * The resource must have been created by a prior pass or imported into the graph.\r\n *\r\n * @param handle - Handle of the resource to read.\r\n */\r\n read(handle: RGHandle): void;\r\n\r\n /**\r\n * Declare that this pass writes a new version of an existing resource.\r\n *\r\n * The returned handle represents the post-write version. Use it for subsequent\r\n * reads and as the graph output passed to {@link RenderGraph.compile}. Passing\r\n * an older version of the same resource to `compile()` is rejected because it\r\n * usually means the caller ignored the handle returned by `write()`. If the pass\r\n * needs the previous contents, call {@link RGPassBuilder.read} on the input handle explicitly\r\n * before writing.\r\n *\r\n * @param handle - Handle of the resource to write to.\r\n * @returns A handle referencing the newly written version.\r\n */\r\n write(handle: RGHandle): RGHandle;\r\n\r\n /**\r\n * Create a new transient texture resource that this pass will produce.\r\n *\r\n * @param desc - Texture descriptor.\r\n * @returns A handle referencing the newly created resource.\r\n */\r\n createTexture(desc: RGTextureDesc): RGHandle;\r\n\r\n /**\r\n * Create a logical dependency token produced by this pass.\r\n *\r\n * Tokens do not resolve to GPU resources and are not allocated by the executor.\r\n * They are useful for ordering passes whose dependencies are side effects rather\r\n * than texture reads/writes.\r\n *\r\n * @param name - Debug label for this token.\r\n * @returns A handle referencing the newly created token.\r\n */\r\n createToken(name?: string): RGHandle;\r\n\r\n /**\r\n * Create a graph-managed framebuffer view.\r\n *\r\n * The graph compiler infers dependencies from any attachment handles in the\r\n * descriptor. The executor creates and releases the framebuffer automatically.\r\n *\r\n * @param desc - Framebuffer descriptor.\r\n * @returns A handle referencing the framebuffer view.\r\n */\r\n createFramebuffer(desc: RGFramebufferDesc): RGHandle;\r\n\r\n /**\r\n * Mark this pass as having side effects.\r\n *\r\n * Side-effect passes are never culled by the graph compiler, regardless of\r\n * whether their outputs are consumed. Use this for GPU readback, picking,\r\n * debug overlays, etc.\r\n */\r\n sideEffect(): void;\r\n\r\n /**\r\n * Add an ordered logical subpass to this pass.\r\n *\r\n * Subpasses execute in registration order and share the parent pass's declared\r\n * reads, writes, framebuffer views, and user data. A pass may use either\r\n * subpasses or {@link RGPassBuilder.setExecute}, but not both.\r\n *\r\n * @param name - Debug label for the subpass.\r\n * @param fn - Callback invoked when this subpass executes.\r\n */\r\n addSubpass<D>(name: string, fn: RGExecuteFn<D>): void;\r\n\r\n /**\r\n * Set the execution callback for this pass.\r\n *\r\n * A pass may use either this method or {@link RGPassBuilder.addSubpass}, but not both.\r\n *\r\n * @param fn - Callback invoked during graph execution.\r\n */\r\n setExecute<D>(fn: RGExecuteFn<D>): void;\r\n}\r\n\r\n// ─── Compiled Graph ─────────────────────────────────────────────────────\r\n\r\n/**\r\n * Lifetime information for a resource within the compiled graph.\r\n *\r\n * @public\r\n */\r\nexport interface RGResourceLifetime {\r\n /** The resource. */\r\n readonly resource: RGResource;\r\n /** Index of the first pass that uses (produces or reads) this resource. */\r\n readonly firstUse: number;\r\n /** Index of the last pass that uses this resource. */\r\n readonly lastUse: number;\r\n}\r\n\r\n/**\r\n * Result of compiling a render graph.\r\n *\r\n * Contains the ordered list of passes to execute and lifetime information\r\n * for automatic resource management.\r\n *\r\n * @public\r\n */\r\nexport interface CompiledRenderGraph {\r\n /** Topologically sorted passes (only non-culled passes). */\r\n readonly orderedPasses: ReadonlyArray<RGPass>;\r\n /** Resource lifetime information keyed by resource ID. */\r\n readonly lifetimes: ReadonlyMap<number, RGResourceLifetime>;\r\n}\r\n\r\n/**\r\n * Profiling scope type in a render graph timing tree.\r\n * @public\r\n */\r\nexport type RGProfileScopeType = 'graph' | 'pass' | 'subpass';\r\n\r\n/**\r\n * Render graph GPU timestamp profiling options.\r\n * @public\r\n */\r\nexport interface RGProfilingOptions {\r\n /** Enable render graph timestamp profiling. Default true when an options object is provided. */\r\n enabled?: boolean;\r\n /** Measure the whole graph execution. Default true. */\r\n graph?: boolean;\r\n /** Measure every render graph pass. Default true. */\r\n pass?: boolean;\r\n /** Measure every subpass and expose it as a child scope. Default true. */\r\n subpass?: boolean;\r\n /** Include pending upload/copy commands at timestamp boundaries. Default true. */\r\n includePendingUploads?: boolean;\r\n /** Allow graph profile scopes to remain open across frame boundaries. Default false. */\r\n allowCrossFrame?: boolean;\r\n /** Maximum unresolved profile frames kept by the executor. Default 3. */\r\n maxPendingFrames?: number;\r\n /** Root graph profile label. Default 'RenderGraph'. */\r\n label?: string;\r\n /** Device used for timestamp queries. If omitted, the scene global getDevice() is used. */\r\n device?: AbstractDevice;\r\n}\r\n\r\n/**\r\n * Render graph executor construction options.\r\n * @public\r\n */\r\nexport interface RenderGraphExecutorOptions {\r\n /** Device used for timestamp queries. If omitted, the scene global getDevice() is used. */\r\n device?: AbstractDevice;\r\n /** Render graph timestamp profiling options. Default false. */\r\n profiling?: boolean | RGProfilingOptions;\r\n}\r\n\r\n/**\r\n * Resolved GPU timing for one graph/pass/subpass scope.\r\n * @public\r\n */\r\nexport interface RGProfileScopeResult {\r\n /** Scope label. */\r\n name: string;\r\n /** Scope type. */\r\n type: RGProfileScopeType;\r\n /** Timestamp query id used by the device, or 0 for synthetic/unsupported scopes. */\r\n queryId: number;\r\n /** GPU duration in milliseconds. */\r\n durationMs: number;\r\n /** Timestamp result status. */\r\n status: TimestampQueryStatus;\r\n /** Child scopes. */\r\n children: RGProfileScopeResult[];\r\n /** Optional diagnostic message. */\r\n message?: string;\r\n}\r\n\r\n/**\r\n * Resolved GPU timing tree for one render graph execution.\r\n * @public\r\n */\r\nexport interface RGProfileResult {\r\n /** Render frame id when profiling began. */\r\n frameId: number;\r\n /** Aggregate profile status. */\r\n status: TimestampQueryStatus;\r\n /** Root graph scope. */\r\n graph: RGProfileScopeResult;\r\n /** Top-level pass scopes. Same objects as graph.children. */\r\n passes: RGProfileScopeResult[];\r\n}\r\n\r\n// ─── Texture Allocator ──────────────────────────────────────────────\r\n\r\n/**\r\n * Resolved dimensions for a texture allocation.\r\n * @public\r\n */\r\nexport interface RGResolvedSize {\r\n width: number;\r\n height: number;\r\n}\r\n\r\n/**\r\n * Descriptor for a framebuffer view managed by the graph or created temporarily during pass execution.\r\n *\r\n * This is intentionally backend-agnostic: graph-managed descriptors may use\r\n * {@link RGHandle} attachments, and executor-created descriptors use resolved\r\n * resources or texture formats understood by the allocator.\r\n *\r\n * @public\r\n */\r\nexport interface RGFramebufferDesc {\r\n /** Debug label for this framebuffer. */\r\n label?: string;\r\n /** Framebuffer width. Required when attachments are formats. */\r\n width?: number;\r\n /** Framebuffer height. Required when attachments are formats. */\r\n height?: number;\r\n /** Color attachments or formats. */\r\n colorAttachments: unknown | unknown[] | null;\r\n /** Depth/stencil attachment or format. */\r\n depthAttachment?: unknown | null;\r\n /** Whether color attachments created from formats should support mipmapping. */\r\n mipmapping?: boolean;\r\n /** Framebuffer sample count. */\r\n sampleCount?: number;\r\n /** Whether to ignore depth/stencil during MSAA resolve. */\r\n ignoreDepthStencil?: boolean;\r\n /** Attachment mip level. */\r\n attachmentMipLevel?: number;\r\n /** Attachment cubemap face. */\r\n attachmentCubeface?: number;\r\n /** Attachment array layer. */\r\n attachmentLayer?: number;\r\n}\r\n\r\n/**\r\n * Interface for allocating and releasing transient textures.\r\n *\r\n * Implement this to bridge the render graph with your GPU device's resource pool.\r\n * The executor calls `allocate()` before a resource's first use and\r\n * `release()` after its last use.\r\n *\r\n * Lifetime contract: the graph compiler extends a texture's lifetime to cover\r\n * every graph-managed framebuffer it is attached to, and the executor releases\r\n * framebuffers before textures at the same pass boundary. Allocators may\r\n * therefore assume `releaseFramebuffer()` is called before `release()` of its\r\n * attachments, and must keep a released framebuffer's attachments intact until\r\n * their own `release()` call.\r\n *\r\n * @typeParam TTexture - The concrete texture type (e.g. `Texture2D`).\r\n * @public\r\n */\r\nexport interface RGTextureAllocator<TTexture = unknown, TFramebuffer = unknown> {\r\n /**\r\n * Allocate a transient texture matching the given descriptor and resolved size.\r\n *\r\n * @param desc - The texture descriptor from the pass builder.\r\n * @param size - The resolved pixel dimensions.\r\n * @returns The allocated texture object.\r\n */\r\n allocate(desc: RGTextureDesc, size: RGResolvedSize): TTexture;\r\n\r\n /**\r\n * Release a previously allocated transient texture back to the pool.\r\n *\r\n * @param texture - The texture to release.\r\n */\r\n release(texture: TTexture): void;\r\n\r\n /**\r\n * Retain a texture allocated by this allocator so it can outlive the graph pass\r\n * that produced it.\r\n *\r\n * This is used when a graph-produced transient texture must be handed off to\r\n * an external owner, such as a cross-frame history resource. Executors still\r\n * release the graph's own reference at the resource's last use; the external\r\n * owner must later call {@link RGTextureAllocator.release} for the retained\r\n * reference.\r\n *\r\n * Allocators that cannot retain transient textures should leave this undefined.\r\n */\r\n retain?(texture: TTexture): void;\r\n\r\n /**\r\n * Allocate a temporary framebuffer matching the given descriptor.\r\n *\r\n * Implementations should not auto-release this framebuffer; the graph executor\r\n * calls {@link RGTextureAllocator.releaseFramebuffer} when execution completes or aborts.\r\n *\r\n * @param desc - Framebuffer descriptor.\r\n * @returns The allocated framebuffer object.\r\n */\r\n allocateFramebuffer?(desc: RGFramebufferDesc): TFramebuffer;\r\n\r\n /**\r\n * Release a previously allocated temporary framebuffer.\r\n *\r\n * @param framebuffer - The framebuffer to release.\r\n */\r\n releaseFramebuffer?(framebuffer: TFramebuffer): void;\r\n}\r\n"],"names":["RGHandle","id","name","_id","_name","RGResource","kind","desc","producer","consumers","physicalId","RGSubpass","executeFn","RGPass","index","reads","writes","dependencies","hasSideEffect","data","sub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A,EAAE;gEAEvCC,QAAQ,IAAK;IAEb,WAAYP,CAAAA,KAAa,EAAEZ,IAAY,CAAE;QACvC,IAAI,CAACY,KAAK,GAAGA,KAAAA;QACb,IAAI,CAACZ,IAAI,GAAGA,IAAAA;AACd;AACF;;;;"}
@@ -248,7 +248,7 @@ function screenSpaceRayTracing_Linear2D(scope, viewPos, traceRay, viewMatrix, pr
248
248
  });
249
249
  return scope.SSR_Linear2D(viewPos, traceRay, viewMatrix, projMatrix, invProjMatrix, stride, maxDistance, maxIterations, thickness, cameraNearFar, textureSize);
250
250
  }
251
- function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMatrix, invProjMatrix, cameraNearFar, maxMipLevel, maxIterations, thickness, textureSize, HiZTexture, normalTexture) {
251
+ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMatrix, invProjMatrix, cameraNearFar, maxMipLevel, maxIterations, maxDistance, thickness, textureSize, HiZTexture, normalTexture) {
252
252
  const pb = scope.$builder;
253
253
  pb.func('getMipResolution', [
254
254
  pb.int('mipLevel')
@@ -314,19 +314,41 @@ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMat
314
314
  pb.vec2('floorOffset'),
315
315
  pb.vec2('uvOffset'),
316
316
  pb.float('surfaceZ'),
317
+ pb.float('surfaceZMax'),
318
+ pb.int('currentMip'),
317
319
  pb.vec3('position').inout(),
318
320
  pb.float('currentT').inout()
319
321
  ], function() {
320
322
  this.$l.xyPlane = pb.add(pb.floor(this.currentMipPosition), this.floorOffset);
321
323
  this.xyPlane = pb.add(pb.mul(this.xyPlane, this.invCurrentMipResolution), this.uvOffset);
322
- this.$l.boundaryPlanes = pb.vec3(this.xyPlane, this.surfaceZ);
323
- this.$l.t = pb.mul(pb.sub(this.boundaryPlanes, this.origin), this.invDirection);
324
- this.t.z = this.$choice(pb.greaterThan(this.direction.z, 0), this.t.z, MAX_FLOAT_VALUE);
325
- this.$l.tMin = pb.min(pb.min(this.t.x, this.t.y), this.t.z);
326
- this.$l.aboveSurface = pb.greaterThan(this.surfaceZ, this.position.z);
327
- this.$l.skippedTile = pb.and(pb.notEqual(pb.floatBitsToUint(this.tMin), pb.floatBitsToUint(this.t.z)), this.aboveSurface);
328
- this.currentT = this.$choice(this.aboveSurface, this.tMin, this.currentT);
329
- this.position = pb.add(this.origin, pb.mul(this.direction, this.currentT));
324
+ this.$l.skippedTile = pb.bool();
325
+ this.$if(pb.greaterThan(this.direction.z, 0), function() {
326
+ // Preserve the proven min-depth traversal for rays moving away from the camera.
327
+ this.$l.boundaryPlanes = pb.vec3(this.xyPlane, this.surfaceZ);
328
+ this.$l.forwardT = pb.mul(pb.sub(this.boundaryPlanes, this.origin), this.invDirection);
329
+ this.$l.tMin = pb.min(pb.min(this.forwardT.x, this.forwardT.y), this.forwardT.z);
330
+ this.$l.aboveSurface = pb.greaterThan(this.surfaceZ, this.position.z);
331
+ this.skippedTile = pb.and(pb.notEqual(pb.floatBitsToUint(this.tMin), pb.floatBitsToUint(this.forwardT.z)), this.aboveSurface);
332
+ this.currentT = this.$choice(this.aboveSurface, this.tMin, this.currentT);
333
+ this.position = pb.add(this.origin, pb.mul(this.direction, this.currentT));
334
+ }).$else(function() {
335
+ this.$l.reverseT = pb.mul(pb.sub(this.xyPlane, this.origin.xy), this.invDirection.xy);
336
+ this.$l.tExit = pb.min(this.reverseT.x, this.reverseT.y);
337
+ this.$l.exitZ = pb.add(this.origin.z, pb.mul(this.direction.z, this.tExit));
338
+ this.$l.rayMinZ = pb.min(this.position.z, this.exitZ);
339
+ this.$l.rayMaxZ = pb.max(this.position.z, this.exitZ);
340
+ this.$l.overlapsDepth = pb.and(pb.greaterThanEqual(this.rayMaxZ, this.surfaceZ), pb.lessThanEqual(this.rayMinZ, this.surfaceZMax));
341
+ this.skippedTile = pb.not(this.overlapsDepth);
342
+ this.$if(this.skippedTile, function() {
343
+ this.currentT = this.tExit;
344
+ this.position = pb.add(this.origin, pb.mul(this.direction, this.currentT));
345
+ }).$elseif(pb.equal(this.currentMip, 0), function() {
346
+ this.$if(pb.greaterThan(pb.abs(this.direction.z), 1e-6), function() {
347
+ this.currentT = pb.div(pb.sub(this.surfaceZMax, this.origin.z), this.direction.z);
348
+ this.position = pb.add(this.origin, pb.mul(this.direction, this.currentT));
349
+ });
350
+ });
351
+ });
330
352
  this.$return(this.skippedTile);
331
353
  });
332
354
  pb.func('SSR_RaymarchHiZ', [
@@ -337,9 +359,10 @@ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMat
337
359
  pb.int('mostDetailMip'),
338
360
  pb.int('maxMipLevel'),
339
361
  pb.float('maxIterations'),
362
+ pb.float('maxT'),
340
363
  pb.float('numIterations').out()
341
364
  ], function() {
342
- this.$l.invDirection = this.$choice(pb.all(pb.compNotEqual(this.screenSpaceDirection, pb.vec3(0))), pb.div(pb.vec3(1), this.screenSpaceDirection), pb.vec3(MAX_FLOAT_VALUE));
365
+ this.$l.invDirection = pb.vec3(this.$choice(pb.greaterThan(pb.abs(this.screenSpaceDirection.x), 1e-8), pb.div(1, this.screenSpaceDirection.x), MAX_FLOAT_VALUE), this.$choice(pb.greaterThan(pb.abs(this.screenSpaceDirection.y), 1e-8), pb.div(1, this.screenSpaceDirection.y), MAX_FLOAT_VALUE), this.$choice(pb.greaterThan(pb.abs(this.screenSpaceDirection.z), 1e-8), pb.div(1, this.screenSpaceDirection.z), MAX_FLOAT_VALUE));
343
366
  this.$l.currentMip = this.mostDetailMip;
344
367
  this.$l.currentMipResolution = this.getMipResolution(this.currentMip);
345
368
  this.$l.invCurrentMipResolution = pb.div(pb.vec2(1), this.currentMipResolution);
@@ -350,10 +373,10 @@ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMat
350
373
  this.$l.position = pb.vec3();
351
374
  this.SSR_initialAdvanceRay(this.screenSpacePos, this.screenSpaceDirection, this.invDirection, this.currentMipResolution, this.invCurrentMipResolution, this.floorOffset, this.uvOffset, this.position, this.currentT);
352
375
  this.numIterations = pb.float(0);
353
- this.$while(pb.and(pb.lessThan(this.numIterations, this.maxIterations), pb.greaterThanEqual(this.currentMip, this.mostDetailMip)), function() {
376
+ this.$while(pb.and(pb.and(pb.lessThan(this.numIterations, this.maxIterations), pb.greaterThanEqual(this.currentMip, this.mostDetailMip)), pb.and(pb.lessThanEqual(this.currentT, this.maxT), pb.all(pb.greaterThanEqual(this.position.xy, pb.vec2(0))), pb.all(pb.lessThanEqual(this.position.xy, pb.vec2(1))))), function() {
354
377
  this.$l.currentMipPosition = pb.mul(this.currentMipResolution, this.position.xy);
355
- this.$l.surfaceZ = pb.textureLoad(HiZTexture, pb.ivec2(this.currentMipPosition), this.currentMip).r;
356
- this.$l.skippedTile = this.SSR_advanceRay(this.screenSpacePos, this.screenSpaceDirection, this.invDirection, this.currentMipPosition, this.invCurrentMipResolution, this.floorOffset, this.uvOffset, this.surfaceZ, this.position, this.currentT);
378
+ this.$l.depthRange = pb.textureLoad(HiZTexture, pb.ivec2(this.currentMipPosition), this.currentMip).rg;
379
+ this.$l.skippedTile = this.SSR_advanceRay(this.screenSpacePos, this.screenSpaceDirection, this.invDirection, this.currentMipPosition, this.invCurrentMipResolution, this.floorOffset, this.uvOffset, this.depthRange.x, this.depthRange.y, this.currentMip, this.position, this.currentT);
357
380
  this.$l.nextMipIsOutOfRange = pb.and(this.skippedTile, pb.greaterThanEqual(this.currentMip, this.maxMipLevel));
358
381
  this.$if(pb.not(this.nextMipIsOutOfRange), function() {
359
382
  this.currentMip = pb.add(this.currentMip, this.$choice(this.skippedTile, pb.int(1), pb.int(-1)));
@@ -362,7 +385,7 @@ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMat
362
385
  });
363
386
  this.numIterations = pb.add(this.numIterations, 1);
364
387
  });
365
- this.$l.validHit = this.$choice(pb.lessThanEqual(this.numIterations, this.maxIterations), pb.float(1), pb.float(0));
388
+ this.$l.validHit = this.$choice(pb.and(pb.lessThan(this.currentMip, this.mostDetailMip), pb.and(pb.greaterThanEqual(this.currentT, 0), pb.lessThanEqual(this.currentT, this.maxT))), pb.float(1), pb.float(0));
366
389
  this.$return(pb.vec4(this.position, this.validHit));
367
390
  });
368
391
  pb.func('SSR_HiZ', [
@@ -372,21 +395,30 @@ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMat
372
395
  pb.mat4('projMatrix'),
373
396
  pb.mat4('invProjMatrix'),
374
397
  pb.vec2('cameraNearFar'),
398
+ pb.float('maxDistance'),
375
399
  pb.float('thickness'),
376
400
  pb.vec4('textureSize'),
377
401
  pb.int('maxMipLevel'),
378
402
  pb.float('maxIterations')
379
403
  ], function() {
380
- this.$if(pb.greaterThan(this.traceRay.z, 0), function() {
404
+ this.$l.rayDirection = pb.normalize(this.traceRay);
405
+ this.$l.reverseRay = pb.greaterThan(this.rayDirection.z, 1e-6);
406
+ this.$l.rayLength = this.maxDistance;
407
+ this.$if(this.reverseRay, function() {
408
+ this.rayLength = pb.min(this.rayLength, pb.div(pb.sub(pb.neg(this.cameraNearFar.x), this.viewPos.z), this.rayDirection.z));
409
+ });
410
+ this.$if(pb.lessThanEqual(this.rayLength, 0), function() {
381
411
  this.$return(pb.vec4(0));
382
412
  });
383
413
  this.$l.originH = pb.mul(this.projMatrix, pb.vec4(this.viewPos, 1));
384
414
  this.$l.originCS = pb.div(this.originH.xyz, this.originH.w);
385
415
  this.$l.originTS = pb.add(pb.mul(this.originCS, 0.5), pb.vec3(0.5));
386
- this.$l.directionTS = this.projectDirection(this.viewPos, this.traceRay, this.originTS, this.projMatrix);
416
+ this.$l.endTS = this.projectPosition(pb.add(this.viewPos, pb.mul(this.rayDirection, this.rayLength)), this.projMatrix);
417
+ this.$l.directionTS = this.$choice(this.reverseRay, pb.sub(this.endTS, this.originTS), this.projectDirection(this.viewPos, this.rayDirection, this.originTS, this.projMatrix));
418
+ this.$l.maxT = this.$choice(this.reverseRay, pb.float(1), pb.float(MAX_FLOAT_VALUE));
387
419
  this.$l.mostDetailMip = pb.int(0);
388
420
  this.$l.numIterations = pb.float();
389
- this.$l.hit = this.SSR_RaymarchHiZ(this.originTS, this.directionTS, this.cameraNearFar, this.textureSize.zw, this.mostDetailMip, this.maxMipLevel, this.maxIterations, this.numIterations);
421
+ this.$l.hit = this.SSR_RaymarchHiZ(this.originTS, this.directionTS, this.cameraNearFar, this.textureSize.zw, this.mostDetailMip, this.maxMipLevel, this.maxIterations, this.maxT, this.numIterations);
390
422
  this.$l.confidence = pb.float(0);
391
423
  this.$if(pb.notEqual(this.hit.w, 0), function() {
392
424
  this.$l.surfaceZ = pb.textureSampleLevel(HiZTexture, this.hit.xy, 0).r;
@@ -394,18 +426,17 @@ function screenSpaceRayTracing_HiZ(scope, viewPos, traceRay, viewMatrix, projMat
394
426
  this.$return(pb.vec4(0));
395
427
  });
396
428
  this.$l.hit3D = invProjectPosition(this, this.hit.xyz, this.invProjMatrix);
397
- this.confidence = validateHit(this, this.hit.xy, this.hit3D, this.surfaceZ, this.thickness, this.originTS.xy, this.traceRay, this.viewMatrix, this.invProjMatrix, this.textureSize, normalTexture);
429
+ this.confidence = validateHit(this, this.hit.xy, this.hit3D, this.surfaceZ, this.thickness, this.originTS.xy, this.rayDirection, this.viewMatrix, this.invProjMatrix, this.textureSize, normalTexture);
398
430
  });
399
431
  this.$l.iterationAttenuation = pb.sub(1, pb.smoothStep(0, this.maxIterations, this.numIterations));
400
- this.$l.viewAttenuation = pb.sub(1, pb.smoothStep(-0.5, 0, this.traceRay.z));
401
432
  //this.$l.iterationAttenuation = pb.smoothStep(this.maxIterations, 1, this.numIterations);
402
- this.confidence = pb.mul(this.confidence, this.iterationAttenuation, this.viewAttenuation);
433
+ this.confidence = pb.mul(this.confidence, this.iterationAttenuation);
403
434
  this.$l.hitPixel = pb.mul(this.hit.xy, this.textureSize.zw);
404
435
  this.$l.startPixel = pb.mul(this.originTS.xy, this.textureSize.zw);
405
436
  this.$l.hitDistance = pb.length(pb.sub(this.hitPixel, this.startPixel));
406
437
  this.$return(pb.vec4(this.hit.xy, this.hitDistance, this.confidence));
407
438
  });
408
- return scope.SSR_HiZ(viewPos, traceRay, viewMatrix, projMatrix, invProjMatrix, cameraNearFar, thickness, textureSize, pb.sub(maxMipLevel, 1), maxIterations);
439
+ return scope.SSR_HiZ(viewPos, traceRay, viewMatrix, projMatrix, invProjMatrix, cameraNearFar, maxDistance, thickness, textureSize, pb.sub(maxMipLevel, 1), maxIterations);
409
440
  } /*
410
441
  float2 cell(float2 ray, float2 cell_count, uint camera) {
411
442
  return floor(ray.xy * cell_count);