@zephyr3d/scene 0.9.19 → 0.9.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animation/joint_dynamics/convex_collider.js +320 -0
- package/dist/animation/joint_dynamics/convex_collider.js.map +1 -0
- package/dist/asset/assetmanager.js +1 -0
- package/dist/asset/assetmanager.js.map +1 -1
- package/dist/camera/camera.js +39 -0
- package/dist/camera/camera.js.map +1 -1
- package/dist/index.d.ts +190 -4
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/material/meshmaterial.js +2 -2
- package/dist/material/meshmaterial.js.map +1 -1
- package/dist/material/mixins/lit.js +10 -0
- package/dist/material/mixins/lit.js.map +1 -1
- package/dist/material/shader/helper.js +117 -2
- package/dist/material/shader/helper.js.map +1 -1
- package/dist/posteffect/skinsss.js +10 -10
- package/dist/posteffect/skinsss.js.map +1 -1
- package/dist/posteffect/ssr.js +13 -13
- package/dist/posteffect/ssr.js.map +1 -1
- package/dist/posteffect/sss.js +8 -7
- package/dist/posteffect/sss.js.map +1 -1
- package/dist/posteffect/tonemap.js +5 -5
- package/dist/posteffect/tonemap.js.map +1 -1
- package/dist/render/abuffer_oit.js +5 -0
- package/dist/render/abuffer_oit.js.map +1 -1
- package/dist/render/cluster_light.js +52 -8
- package/dist/render/cluster_light.js.map +1 -1
- package/dist/render/dualdepthpeeling_oit.js +331 -0
- package/dist/render/dualdepthpeeling_oit.js.map +1 -0
- package/dist/render/lightpass.js +29 -8
- package/dist/render/lightpass.js.map +1 -1
- package/dist/render/renderer.js +3 -0
- package/dist/render/renderer.js.map +1 -1
- package/dist/render/rendergraph/blackboard.js +40 -39
- package/dist/render/rendergraph/blackboard.js.map +1 -1
- package/dist/render/rendergraph/device_pool_allocator.js +10 -1
- package/dist/render/rendergraph/device_pool_allocator.js.map +1 -1
- package/dist/render/rendergraph/forward_plus_builder.js +75 -4
- package/dist/render/rendergraph/forward_plus_builder.js.map +1 -1
- package/dist/render/rendergraph/types.js.map +1 -1
- package/dist/render/renderpass.js +12 -2
- package/dist/render/renderpass.js.map +1 -1
- package/dist/render/shadow_mask_pass.js +297 -0
- package/dist/render/shadow_mask_pass.js.map +1 -0
- package/dist/render/weightedblended_oit.js +5 -0
- package/dist/render/weightedblended_oit.js.map +1 -1
- package/dist/scene/basesprite.js +1 -0
- package/dist/scene/basesprite.js.map +1 -1
- package/dist/scene/batchgroup.js +1 -0
- package/dist/scene/batchgroup.js.map +1 -1
- package/dist/scene/environment.js +1 -0
- package/dist/scene/environment.js.map +1 -1
- package/dist/scene/msdftext.js +1 -0
- package/dist/scene/msdftext.js.map +1 -1
- package/dist/scene/msdftextsprite.js +1 -0
- package/dist/scene/msdftextsprite.js.map +1 -1
- package/dist/scene/particlesys.js +1 -0
- package/dist/scene/particlesys.js.map +1 -1
- package/dist/scene/scene.js +1 -0
- package/dist/scene/scene.js.map +1 -1
- package/dist/scene/terrain-cm/grass.js +1 -0
- package/dist/scene/terrain-cm/grass.js.map +1 -1
- package/dist/scene/terrain-cm/terrain-cm.js +1 -0
- package/dist/scene/terrain-cm/terrain-cm.js.map +1 -1
- package/dist/scene/water.js +1 -0
- package/dist/scene/water.js.map +1 -1
- package/dist/utility/serialization/manager.js +1 -0
- package/dist/utility/serialization/manager.js.map +1 -1
- package/dist/utility/serialization/scene/animation.js +1 -0
- package/dist/utility/serialization/scene/animation.js.map +1 -1
- package/dist/utility/serialization/scene/batch.js +1 -0
- package/dist/utility/serialization/scene/batch.js.map +1 -1
- package/dist/utility/serialization/scene/camera.js +35 -2
- package/dist/utility/serialization/scene/camera.js.map +1 -1
- package/dist/utility/serialization/scene/light.js +1 -0
- package/dist/utility/serialization/scene/light.js.map +1 -1
- package/dist/utility/serialization/scene/mesh.js +1 -0
- package/dist/utility/serialization/scene/mesh.js.map +1 -1
- package/dist/utility/serialization/scene/node.js +1 -0
- package/dist/utility/serialization/scene/node.js.map +1 -1
- package/dist/utility/serialization/scene/particle.js +1 -0
- package/dist/utility/serialization/scene/particle.js.map +1 -1
- package/dist/utility/serialization/scene/primitive.js +1 -0
- package/dist/utility/serialization/scene/primitive.js.map +1 -1
- package/dist/utility/serialization/scene/sprite.js +1 -0
- package/dist/utility/serialization/scene/sprite.js.map +1 -1
- package/dist/utility/serialization/scene/terrain.js +1 -0
- package/dist/utility/serialization/scene/terrain.js.map +1 -1
- package/dist/utility/serialization/scene/text.js +1 -0
- package/dist/utility/serialization/scene/text.js.map +1 -1
- package/dist/utility/serialization/scene/water.js +1 -0
- package/dist/utility/serialization/scene/water.js.map +1 -1
- package/dist/values.js +11 -1
- package/dist/values.js.map +1 -1
- package/package.json +2 -2
|
@@ -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 * 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","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 * Number of array layers. When omitted, a plain 2D texture is allocated. When\r\n * defined (including 1), the allocator produces a 2D array texture — a\r\n * single-layer array is a distinct texture type from a 2D texture and is not\r\n * interchangeable when bound to a `tex2DArray` sampler. Individual layers can be\r\n * targeted as framebuffer color attachments via {@link RGFramebufferDesc.attachmentLayer}.\r\n */\r\n arrayLayers?: 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","subpasses","alive"],"mappings":"AA4CA;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;;;;"}
|
|
@@ -12,6 +12,7 @@ import { getDevice } from '../app/api.js';
|
|
|
12
12
|
/** @internal */ _type;
|
|
13
13
|
/** @internal */ _globalBindGroups;
|
|
14
14
|
/** @internal */ _clearColor;
|
|
15
|
+
/** @internal */ _clearColors;
|
|
15
16
|
/** @internal */ _clearDepth;
|
|
16
17
|
/** @internal */ _clearStencil;
|
|
17
18
|
/**
|
|
@@ -21,6 +22,7 @@ import { getDevice } from '../app/api.js';
|
|
|
21
22
|
super();
|
|
22
23
|
this._type = type;
|
|
23
24
|
this._clearColor = new Vector4(0, 0, 0, 1);
|
|
25
|
+
this._clearColors = null;
|
|
24
26
|
this._clearDepth = 1;
|
|
25
27
|
this._clearStencil = 0;
|
|
26
28
|
this._globalBindGroups = {};
|
|
@@ -30,6 +32,13 @@ import { getDevice } from '../app/api.js';
|
|
|
30
32
|
}
|
|
31
33
|
set clearColor(color) {
|
|
32
34
|
this._clearColor = color;
|
|
35
|
+
this._clearColors = null;
|
|
36
|
+
}
|
|
37
|
+
/** Per-target color values that are used to clear the frame buffer */ get clearColors() {
|
|
38
|
+
return this._clearColors;
|
|
39
|
+
}
|
|
40
|
+
set clearColors(colors) {
|
|
41
|
+
this._clearColors = colors;
|
|
33
42
|
}
|
|
34
43
|
/** Depth value that is used to clear the frame buffer */ get clearDepth() {
|
|
35
44
|
return this._clearDepth;
|
|
@@ -173,8 +182,9 @@ import { getDevice } from '../app/api.js';
|
|
|
173
182
|
this._globalBindGroups = {};
|
|
174
183
|
}
|
|
175
184
|
/** @internal */ clearFramebuffer() {
|
|
176
|
-
|
|
177
|
-
|
|
185
|
+
const clearColor = this._clearColors ?? this._clearColor;
|
|
186
|
+
if (clearColor || this._clearDepth || this._clearStencil) {
|
|
187
|
+
getDevice().clearFrameBuffer(clearColor, this._clearDepth, this._clearStencil);
|
|
178
188
|
}
|
|
179
189
|
}
|
|
180
190
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderpass.js","sources":["../../src/render/renderpass.ts"],"sourcesContent":["import type { Immutable, Nullable } from '@zephyr3d/base';\r\nimport { Disposable, Vector4 } from '@zephyr3d/base';\r\nimport { CullVisitor } from './cull_visitor';\r\nimport type { RenderItemListInfo, RenderQueueItem } from './render_queue';\r\nimport { RenderQueue } from './render_queue';\r\nimport type { Camera } from '../camera/camera';\r\nimport type { DrawContext } from './drawable';\r\nimport { RenderBundleWrapper } from './renderbundle_wrapper';\r\nimport { MaterialVaryingFlags, RENDER_PASS_TYPE_LIGHT } from '../values';\r\nimport type { BindGroup } from '@zephyr3d/device';\r\nimport { getDevice } from '../app/api';\r\n\r\n/**\r\n * Base class for any kind of render passes\r\n * @public\r\n */\r\nexport abstract class RenderPass extends Disposable {\r\n /** @internal */\r\n protected _type: number;\r\n /** @internal */\r\n protected _globalBindGroups: Record<string, BindGroup>;\r\n /** @internal */\r\n protected _clearColor: Nullable<Vector4>;\r\n /** @internal */\r\n protected _clearDepth: Nullable<number>;\r\n /** @internal */\r\n protected _clearStencil: Nullable<number>;\r\n /**\r\n * Creates an instanceof RenderPass\r\n * @param type - Render pass type\r\n */\r\n constructor(type: number) {\r\n super();\r\n this._type = type;\r\n this._clearColor = new Vector4(0, 0, 0, 1);\r\n this._clearDepth = 1;\r\n this._clearStencil = 0;\r\n this._globalBindGroups = {};\r\n }\r\n /** Color value that is used to clear the frame buffer */\r\n get clearColor(): Nullable<Immutable<Vector4>> {\r\n return this._clearColor;\r\n }\r\n set clearColor(color: Nullable<Immutable<Vector4>>) {\r\n this._clearColor = color;\r\n }\r\n /** Depth value that is used to clear the frame buffer */\r\n get clearDepth() {\r\n return this._clearDepth;\r\n }\r\n set clearDepth(depth) {\r\n this._clearDepth = depth;\r\n }\r\n /** Stencil value that is used to clear the frame buffer */\r\n get clearStencil() {\r\n return this._clearStencil;\r\n }\r\n set clearStencil(stencil) {\r\n this._clearStencil = stencil;\r\n }\r\n /**\r\n * The render pass type\r\n */\r\n get type() {\r\n return this._type;\r\n }\r\n /** @internal */\r\n isAutoFlip(ctx: DrawContext) {\r\n return !!(ctx.device.getFramebuffer() && ctx.device.type === 'webgpu');\r\n }\r\n /**\r\n * Renders a scene\r\n * @param ctx - Drawing context\r\n */\r\n render(\r\n ctx: DrawContext,\r\n renderCamera?: Nullable<Camera>,\r\n cullCamera?: Nullable<Camera>,\r\n renderQueue?: RenderQueue\r\n ) {\r\n ctx.renderPass = this;\r\n this.drawScene(ctx, renderCamera ?? ctx.camera, cullCamera ?? renderCamera ?? ctx.camera, renderQueue);\r\n }\r\n /** @internal */\r\n getGlobalBindGroupHash(ctx: DrawContext, camera: Camera) {\r\n return `${this.constructor.name}:${this._getGlobalBindGroupHash(ctx, camera)}`;\r\n }\r\n /** @internal */\r\n protected abstract _getGlobalBindGroupHash(ctx: DrawContext, camera: Camera): string;\r\n /** @internal */\r\n protected abstract renderItems(ctx: DrawContext, renderCamera: Camera, renderQueue: RenderQueue): void;\r\n /** @internal */\r\n protected drawScene(ctx: DrawContext, renderCamera: Camera, cullCamera: Camera, renderQueue?: RenderQueue) {\r\n const device = ctx.device;\r\n this.clearFramebuffer();\r\n const rq = renderQueue ?? this.cullScene(ctx, cullCamera);\r\n if (rq) {\r\n const windingReversed = device.isWindingOrderReversed();\r\n device.reverseVertexWindingOrder(this.isAutoFlip(ctx) ? !windingReversed : windingReversed);\r\n this.renderItems(ctx, renderCamera, rq);\r\n device.reverseVertexWindingOrder(windingReversed);\r\n if (rq !== renderQueue) {\r\n rq.dispose();\r\n }\r\n }\r\n }\r\n /**\r\n * Culls a scene by a given camera\r\n * @param ctx - The draw context\r\n * @param cullCamera - The camera that will be used to cull the scene\r\n * @returns The cull result\r\n */\r\n cullScene(ctx: DrawContext, cullCamera: Camera) {\r\n const renderQueue = new RenderQueue(this);\r\n const cullVisitor = new CullVisitor(this, cullCamera, renderQueue);\r\n if (ctx.scene.octree) {\r\n ctx.scene.octree.getRootNode().traverse(cullVisitor);\r\n } else {\r\n ctx.scene.rootNode.traverse(cullVisitor);\r\n }\r\n renderQueue.end(cullCamera);\r\n ctx.sunLight = renderQueue.sunLight;\r\n ctx.primaryDirectionalLight = renderQueue.primaryDirectionalLight;\r\n ctx.primaryTransmissionLight = renderQueue.primaryTransmissionLight;\r\n return renderQueue;\r\n }\r\n /** @internal */\r\n private internalDrawItemList(\r\n ctx: DrawContext,\r\n items: RenderQueueItem[],\r\n renderQueue: Nullable<RenderQueue>,\r\n renderBundle: Nullable<RenderBundleWrapper>,\r\n reverseWinding: boolean,\r\n hash: string\r\n ) {\r\n let recording = false;\r\n const disableRenderBundles = this.shouldDisableRenderBundles(ctx);\r\n if (renderBundle && ctx.camera.commandBufferReuse && !disableRenderBundles) {\r\n const bundle = renderBundle.getRenderBundle(hash);\r\n if (bundle) {\r\n ctx.device.executeRenderBundle(bundle);\r\n return;\r\n }\r\n recording = true;\r\n renderBundle.beginRenderBundle();\r\n }\r\n for (const item of items) {\r\n ctx.instanceData = item.instanceData;\r\n const reverse = reverseWinding !== item.drawable.getNode().worldMatrixDet < 0;\r\n if (reverse) {\r\n ctx.device.reverseVertexWindingOrder(!ctx.device.isWindingOrderReversed());\r\n }\r\n if (recording) {\r\n RenderBundleWrapper.addDrawable(\r\n item.drawable,\r\n item.drawable.getMaterial()?.coreMaterial!,\r\n item.drawable.getPrimitive()!,\r\n renderBundle!,\r\n hash\r\n );\r\n }\r\n item.drawable.draw(ctx, renderQueue, recording || disableRenderBundles ? undefined : hash);\r\n if (reverse) {\r\n ctx.device.reverseVertexWindingOrder(!ctx.device.isWindingOrderReversed());\r\n }\r\n }\r\n if (renderBundle && ctx.camera.commandBufferReuse && !disableRenderBundles) {\r\n renderBundle.endRenderBundle(hash);\r\n }\r\n }\r\n private shouldDisableRenderBundles(ctx: DrawContext) {\r\n return (\r\n (ctx.renderPass?.type === RENDER_PASS_TYPE_LIGHT &&\r\n (!!ctx.SSS || !!ctx.currentShadowLight || !!ctx.lightBlending)) ||\r\n false\r\n );\r\n }\r\n /** @internal */\r\n protected drawItemList(itemList: RenderItemListInfo, ctx: DrawContext, reverseWinding: boolean) {\r\n ctx.instanceData = null;\r\n const windingHash = reverseWinding ? '1' : '0';\r\n const bindGroupHash = ctx.device.getBindGroup(0)[0].getGPUId();\r\n const framebufferHash = ctx.device.getFramebuffer()?.getHash() ?? '';\r\n const ctxHash = `${ctx.sceneColorTexture?.uid ?? 0}-${ctx.linearDepthTexture?.uid ?? 0}`;\r\n const hash = `${windingHash}-${bindGroupHash}-${framebufferHash}-${ctxHash}-${ctx.renderPassHash}`;\r\n if (itemList) {\r\n if (itemList.itemList.length > 0) {\r\n ctx.materialFlags &= ~(\r\n MaterialVaryingFlags.SKIN_ANIMATION |\r\n MaterialVaryingFlags.INSTANCING |\r\n MaterialVaryingFlags.MORPH_ANIMATION\r\n );\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.itemList,\r\n itemList.renderQueue,\r\n itemList.renderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.skinItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.SKIN_ANIMATION;\r\n ctx.materialFlags &= ~(MaterialVaryingFlags.MORPH_ANIMATION | MaterialVaryingFlags.INSTANCING);\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.skinItemList,\r\n itemList.renderQueue,\r\n itemList.skinRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.morphItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.MORPH_ANIMATION;\r\n ctx.materialFlags &= ~(MaterialVaryingFlags.SKIN_ANIMATION | MaterialVaryingFlags.INSTANCING);\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.morphItemList,\r\n itemList.renderQueue,\r\n itemList.morphRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.skinAndMorphItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.SKIN_ANIMATION | MaterialVaryingFlags.MORPH_ANIMATION;\r\n ctx.materialFlags &= ~MaterialVaryingFlags.INSTANCING;\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.skinAndMorphItemList,\r\n itemList.renderQueue,\r\n itemList.skinAndMorphRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.instanceItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.INSTANCING;\r\n ctx.materialFlags &= ~(MaterialVaryingFlags.SKIN_ANIMATION | MaterialVaryingFlags.MORPH_ANIMATION);\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.instanceItemList,\r\n itemList.renderQueue,\r\n itemList.instanceRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n }\r\n }\r\n /**\r\n * Disposes the render pass\r\n */\r\n protected onDispose() {\r\n super.onDispose();\r\n this._globalBindGroups = {};\r\n }\r\n /** @internal */\r\n private clearFramebuffer() {\r\n if (this._clearColor || this._clearDepth || this._clearStencil) {\r\n getDevice().clearFrameBuffer(this._clearColor, this._clearDepth, this._clearStencil);\r\n }\r\n }\r\n}\r\n"],"names":["RenderPass","Disposable","type","_type","_clearColor","Vector4","_clearDepth","_clearStencil","_globalBindGroups","clearColor","color","clearDepth","depth","clearStencil","stencil","isAutoFlip","ctx","device","getFramebuffer","render","renderCamera","cullCamera","renderQueue","renderPass","drawScene","camera","getGlobalBindGroupHash","name","_getGlobalBindGroupHash","clearFramebuffer","rq","cullScene","windingReversed","isWindingOrderReversed","reverseVertexWindingOrder","renderItems","dispose","RenderQueue","cullVisitor","CullVisitor","scene","octree","getRootNode","traverse","rootNode","end","sunLight","primaryDirectionalLight","primaryTransmissionLight","internalDrawItemList","items","renderBundle","reverseWinding","hash","recording","disableRenderBundles","shouldDisableRenderBundles","commandBufferReuse","bundle","getRenderBundle","executeRenderBundle","beginRenderBundle","item","instanceData","reverse","drawable","getNode","worldMatrixDet","RenderBundleWrapper","addDrawable","getMaterial","coreMaterial","getPrimitive","draw","undefined","endRenderBundle","RENDER_PASS_TYPE_LIGHT","SSS","currentShadowLight","lightBlending","itemList","windingHash","bindGroupHash","getBindGroup","getGPUId","framebufferHash","getHash","ctxHash","sceneColorTexture","uid","linearDepthTexture","renderPassHash","length","materialFlags","MaterialVaryingFlags","SKIN_ANIMATION","INSTANCING","MORPH_ANIMATION","materialList","forEach","mat","apply","skinItemList","skinRenderBundle","morphItemList","morphRenderBundle","skinAndMorphItemList","skinAndMorphRenderBundle","instanceItemList","instanceRenderBundle","onDispose","getDevice","clearFrameBuffer"],"mappings":";;;;;;;AAYA;;;IAIO,MAAeA,UAAmBC,SAAAA,UAAAA,CAAAA;qBAEvC,KAAwB;qBAExB,iBAAuD;qBAEvD,WAAyC;qBAEzC,WAAwC;qBAExC,aAA0C;AAC1C;;;MAIA,WAAA,CAAYC,IAAY,CAAE;QACxB,KAAK,EAAA;QACL,IAAI,CAACC,KAAK,GAAGD,IAAAA;AACb,QAAA,IAAI,CAACE,WAAW,GAAG,IAAIC,OAAQ,CAAA,CAAA,EAAG,GAAG,CAAG,EAAA,CAAA,CAAA;QACxC,IAAI,CAACC,WAAW,GAAG,CAAA;QACnB,IAAI,CAACC,aAAa,GAAG,CAAA;QACrB,IAAI,CAACC,iBAAiB,GAAG,EAAC;AAC5B;+DAEA,IAAIC,UAA2C,GAAA;QAC7C,OAAO,IAAI,CAAC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,CAAAA,aAAa,IAAIC,oBAAAA,CAAqBE,UAAU;gBACpDhF,GAAI6E,CAAAA,aAAa,IAAI,EAAEC,qBAAqBC,cAAc,GAAGD,oBAAqBG,CAAAA,eAAe,CAAD;gBAChGjB,QAASkB,CAAAA,YAAY,CAACC,OAAO,CAAC,CAACC,GAAQA,GAAAA,GAAAA,CAAIC,KAAK,CAACrF,GAAAA,CAAAA,CAAAA;AACjD,gBAAA,IAAI,CAACiC,oBAAoB,CACvBjC,GAAAA,EACAgE,SAAS4B,gBAAgB,EACzB5B,QAAS1D,CAAAA,WAAW,EACpB0D,QAAAA,CAAS6B,oBAAoB,IAAI,MACjCzD,cACAC,EAAAA,IAAAA,CAAAA;AAEJ;AACF;AACF;AACA;;AAEC,MACD,SAAsB,GAAA;AACpB,QAAA,KAAK,CAACyD,SAAAA,EAAAA;QACN,IAAI,CAACtG,iBAAiB,GAAG,EAAC;AAC5B;qBAEA,gBAA2B,GAAA;QACzB,IAAI,IAAI,CAACJ,WAAW,IAAI,IAAI,CAACE,WAAW,IAAI,IAAI,CAACC,aAAa,EAAE;AAC9DwG,YAAAA,SAAAA,EAAAA,CAAYC,gBAAgB,CAAC,IAAI,CAAC5G,WAAW,EAAE,IAAI,CAACE,WAAW,EAAE,IAAI,CAACC,aAAa,CAAA;AACrF;AACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"renderpass.js","sources":["../../src/render/renderpass.ts"],"sourcesContent":["import type { Immutable, Nullable } from '@zephyr3d/base';\r\nimport { Disposable, Vector4 } from '@zephyr3d/base';\r\nimport { CullVisitor } from './cull_visitor';\r\nimport type { RenderItemListInfo, RenderQueueItem } from './render_queue';\r\nimport { RenderQueue } from './render_queue';\r\nimport type { Camera } from '../camera/camera';\r\nimport type { DrawContext } from './drawable';\r\nimport { RenderBundleWrapper } from './renderbundle_wrapper';\r\nimport { MaterialVaryingFlags, RENDER_PASS_TYPE_LIGHT } from '../values';\r\nimport type { BindGroup, FrameBufferClearColors } from '@zephyr3d/device';\r\nimport { getDevice } from '../app/api';\r\n\r\n/**\r\n * Base class for any kind of render passes\r\n * @public\r\n */\r\nexport abstract class RenderPass extends Disposable {\r\n /** @internal */\r\n protected _type: number;\r\n /** @internal */\r\n protected _globalBindGroups: Record<string, BindGroup>;\r\n /** @internal */\r\n protected _clearColor: Nullable<Vector4>;\r\n /** @internal */\r\n protected _clearColors: Nullable<readonly Nullable<Vector4>[]>;\r\n /** @internal */\r\n protected _clearDepth: Nullable<number>;\r\n /** @internal */\r\n protected _clearStencil: Nullable<number>;\r\n /**\r\n * Creates an instanceof RenderPass\r\n * @param type - Render pass type\r\n */\r\n constructor(type: number) {\r\n super();\r\n this._type = type;\r\n this._clearColor = new Vector4(0, 0, 0, 1);\r\n this._clearColors = null;\r\n this._clearDepth = 1;\r\n this._clearStencil = 0;\r\n this._globalBindGroups = {};\r\n }\r\n /** Color value that is used to clear the frame buffer */\r\n get clearColor(): Nullable<Immutable<Vector4>> {\r\n return this._clearColor;\r\n }\r\n set clearColor(color: Nullable<Immutable<Vector4>>) {\r\n this._clearColor = color;\r\n this._clearColors = null;\r\n }\r\n /** Per-target color values that are used to clear the frame buffer */\r\n get clearColors(): Nullable<readonly Nullable<Immutable<Vector4>>[]> {\r\n return this._clearColors;\r\n }\r\n set clearColors(colors: Nullable<readonly Nullable<Immutable<Vector4>>[]>) {\r\n this._clearColors = colors as Nullable<readonly Nullable<Vector4>[]>;\r\n }\r\n /** Depth value that is used to clear the frame buffer */\r\n get clearDepth() {\r\n return this._clearDepth;\r\n }\r\n set clearDepth(depth) {\r\n this._clearDepth = depth;\r\n }\r\n /** Stencil value that is used to clear the frame buffer */\r\n get clearStencil() {\r\n return this._clearStencil;\r\n }\r\n set clearStencil(stencil) {\r\n this._clearStencil = stencil;\r\n }\r\n /**\r\n * The render pass type\r\n */\r\n get type() {\r\n return this._type;\r\n }\r\n /** @internal */\r\n isAutoFlip(ctx: DrawContext) {\r\n return !!(ctx.device.getFramebuffer() && ctx.device.type === 'webgpu');\r\n }\r\n /**\r\n * Renders a scene\r\n * @param ctx - Drawing context\r\n */\r\n render(\r\n ctx: DrawContext,\r\n renderCamera?: Nullable<Camera>,\r\n cullCamera?: Nullable<Camera>,\r\n renderQueue?: RenderQueue\r\n ) {\r\n ctx.renderPass = this;\r\n this.drawScene(ctx, renderCamera ?? ctx.camera, cullCamera ?? renderCamera ?? ctx.camera, renderQueue);\r\n }\r\n /** @internal */\r\n getGlobalBindGroupHash(ctx: DrawContext, camera: Camera) {\r\n return `${this.constructor.name}:${this._getGlobalBindGroupHash(ctx, camera)}`;\r\n }\r\n /** @internal */\r\n protected abstract _getGlobalBindGroupHash(ctx: DrawContext, camera: Camera): string;\r\n /** @internal */\r\n protected abstract renderItems(ctx: DrawContext, renderCamera: Camera, renderQueue: RenderQueue): void;\r\n /** @internal */\r\n protected drawScene(ctx: DrawContext, renderCamera: Camera, cullCamera: Camera, renderQueue?: RenderQueue) {\r\n const device = ctx.device;\r\n this.clearFramebuffer();\r\n const rq = renderQueue ?? this.cullScene(ctx, cullCamera);\r\n if (rq) {\r\n const windingReversed = device.isWindingOrderReversed();\r\n device.reverseVertexWindingOrder(this.isAutoFlip(ctx) ? !windingReversed : windingReversed);\r\n this.renderItems(ctx, renderCamera, rq);\r\n device.reverseVertexWindingOrder(windingReversed);\r\n if (rq !== renderQueue) {\r\n rq.dispose();\r\n }\r\n }\r\n }\r\n /**\r\n * Culls a scene by a given camera\r\n * @param ctx - The draw context\r\n * @param cullCamera - The camera that will be used to cull the scene\r\n * @returns The cull result\r\n */\r\n cullScene(ctx: DrawContext, cullCamera: Camera) {\r\n const renderQueue = new RenderQueue(this);\r\n const cullVisitor = new CullVisitor(this, cullCamera, renderQueue);\r\n if (ctx.scene.octree) {\r\n ctx.scene.octree.getRootNode().traverse(cullVisitor);\r\n } else {\r\n ctx.scene.rootNode.traverse(cullVisitor);\r\n }\r\n renderQueue.end(cullCamera);\r\n ctx.sunLight = renderQueue.sunLight;\r\n ctx.primaryDirectionalLight = renderQueue.primaryDirectionalLight;\r\n ctx.primaryTransmissionLight = renderQueue.primaryTransmissionLight;\r\n return renderQueue;\r\n }\r\n /** @internal */\r\n private internalDrawItemList(\r\n ctx: DrawContext,\r\n items: RenderQueueItem[],\r\n renderQueue: Nullable<RenderQueue>,\r\n renderBundle: Nullable<RenderBundleWrapper>,\r\n reverseWinding: boolean,\r\n hash: string\r\n ) {\r\n let recording = false;\r\n const disableRenderBundles = this.shouldDisableRenderBundles(ctx);\r\n if (renderBundle && ctx.camera.commandBufferReuse && !disableRenderBundles) {\r\n const bundle = renderBundle.getRenderBundle(hash);\r\n if (bundle) {\r\n ctx.device.executeRenderBundle(bundle);\r\n return;\r\n }\r\n recording = true;\r\n renderBundle.beginRenderBundle();\r\n }\r\n for (const item of items) {\r\n ctx.instanceData = item.instanceData;\r\n const reverse = reverseWinding !== item.drawable.getNode().worldMatrixDet < 0;\r\n if (reverse) {\r\n ctx.device.reverseVertexWindingOrder(!ctx.device.isWindingOrderReversed());\r\n }\r\n if (recording) {\r\n RenderBundleWrapper.addDrawable(\r\n item.drawable,\r\n item.drawable.getMaterial()?.coreMaterial!,\r\n item.drawable.getPrimitive()!,\r\n renderBundle!,\r\n hash\r\n );\r\n }\r\n item.drawable.draw(ctx, renderQueue, recording || disableRenderBundles ? undefined : hash);\r\n if (reverse) {\r\n ctx.device.reverseVertexWindingOrder(!ctx.device.isWindingOrderReversed());\r\n }\r\n }\r\n if (renderBundle && ctx.camera.commandBufferReuse && !disableRenderBundles) {\r\n renderBundle.endRenderBundle(hash);\r\n }\r\n }\r\n private shouldDisableRenderBundles(ctx: DrawContext) {\r\n return (\r\n (ctx.renderPass?.type === RENDER_PASS_TYPE_LIGHT &&\r\n (!!ctx.SSS || !!ctx.currentShadowLight || !!ctx.lightBlending)) ||\r\n false\r\n );\r\n }\r\n /** @internal */\r\n protected drawItemList(itemList: RenderItemListInfo, ctx: DrawContext, reverseWinding: boolean) {\r\n ctx.instanceData = null;\r\n const windingHash = reverseWinding ? '1' : '0';\r\n const bindGroupHash = ctx.device.getBindGroup(0)[0].getGPUId();\r\n const framebufferHash = ctx.device.getFramebuffer()?.getHash() ?? '';\r\n const ctxHash = `${ctx.sceneColorTexture?.uid ?? 0}-${ctx.linearDepthTexture?.uid ?? 0}`;\r\n const hash = `${windingHash}-${bindGroupHash}-${framebufferHash}-${ctxHash}-${ctx.renderPassHash}`;\r\n if (itemList) {\r\n if (itemList.itemList.length > 0) {\r\n ctx.materialFlags &= ~(\r\n MaterialVaryingFlags.SKIN_ANIMATION |\r\n MaterialVaryingFlags.INSTANCING |\r\n MaterialVaryingFlags.MORPH_ANIMATION\r\n );\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.itemList,\r\n itemList.renderQueue,\r\n itemList.renderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.skinItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.SKIN_ANIMATION;\r\n ctx.materialFlags &= ~(MaterialVaryingFlags.MORPH_ANIMATION | MaterialVaryingFlags.INSTANCING);\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.skinItemList,\r\n itemList.renderQueue,\r\n itemList.skinRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.morphItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.MORPH_ANIMATION;\r\n ctx.materialFlags &= ~(MaterialVaryingFlags.SKIN_ANIMATION | MaterialVaryingFlags.INSTANCING);\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.morphItemList,\r\n itemList.renderQueue,\r\n itemList.morphRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.skinAndMorphItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.SKIN_ANIMATION | MaterialVaryingFlags.MORPH_ANIMATION;\r\n ctx.materialFlags &= ~MaterialVaryingFlags.INSTANCING;\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.skinAndMorphItemList,\r\n itemList.renderQueue,\r\n itemList.skinAndMorphRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n if (itemList.instanceItemList.length > 0) {\r\n ctx.materialFlags |= MaterialVaryingFlags.INSTANCING;\r\n ctx.materialFlags &= ~(MaterialVaryingFlags.SKIN_ANIMATION | MaterialVaryingFlags.MORPH_ANIMATION);\r\n itemList.materialList.forEach((mat) => mat.apply(ctx));\r\n this.internalDrawItemList(\r\n ctx,\r\n itemList.instanceItemList,\r\n itemList.renderQueue,\r\n itemList.instanceRenderBundle ?? null,\r\n reverseWinding,\r\n hash\r\n );\r\n }\r\n }\r\n }\r\n /**\r\n * Disposes the render pass\r\n */\r\n protected onDispose() {\r\n super.onDispose();\r\n this._globalBindGroups = {};\r\n }\r\n /** @internal */\r\n private clearFramebuffer() {\r\n const clearColor = (this._clearColors ?? this._clearColor) as FrameBufferClearColors;\r\n if (clearColor || this._clearDepth || this._clearStencil) {\r\n getDevice().clearFrameBuffer(clearColor, this._clearDepth, this._clearStencil);\r\n }\r\n }\r\n}\r\n"],"names":["RenderPass","Disposable","type","_type","_clearColor","Vector4","_clearColors","_clearDepth","_clearStencil","_globalBindGroups","clearColor","color","clearColors","colors","clearDepth","depth","clearStencil","stencil","isAutoFlip","ctx","device","getFramebuffer","render","renderCamera","cullCamera","renderQueue","renderPass","drawScene","camera","getGlobalBindGroupHash","name","_getGlobalBindGroupHash","clearFramebuffer","rq","cullScene","windingReversed","isWindingOrderReversed","reverseVertexWindingOrder","renderItems","dispose","RenderQueue","cullVisitor","CullVisitor","scene","octree","getRootNode","traverse","rootNode","end","sunLight","primaryDirectionalLight","primaryTransmissionLight","internalDrawItemList","items","renderBundle","reverseWinding","hash","recording","disableRenderBundles","shouldDisableRenderBundles","commandBufferReuse","bundle","getRenderBundle","executeRenderBundle","beginRenderBundle","item","instanceData","reverse","drawable","getNode","worldMatrixDet","RenderBundleWrapper","addDrawable","getMaterial","coreMaterial","getPrimitive","draw","undefined","endRenderBundle","RENDER_PASS_TYPE_LIGHT","SSS","currentShadowLight","lightBlending","itemList","windingHash","bindGroupHash","getBindGroup","getGPUId","framebufferHash","getHash","ctxHash","sceneColorTexture","uid","linearDepthTexture","renderPassHash","length","materialFlags","MaterialVaryingFlags","SKIN_ANIMATION","INSTANCING","MORPH_ANIMATION","materialList","forEach","mat","apply","skinItemList","skinRenderBundle","morphItemList","morphRenderBundle","skinAndMorphItemList","skinAndMorphRenderBundle","instanceItemList","instanceRenderBundle","onDispose","getDevice","clearFrameBuffer"],"mappings":";;;;;;;AAYA;;;IAIO,MAAeA,UAAmBC,SAAAA,UAAAA,CAAAA;qBAEvC,KAAwB;qBAExB,iBAAuD;qBAEvD,WAAyC;qBAEzC,YAA+D;qBAE/D,WAAwC;qBAExC,aAA0C;AAC1C;;;MAIA,WAAA,CAAYC,IAAY,CAAE;QACxB,KAAK,EAAA;QACL,IAAI,CAACC,KAAK,GAAGD,IAAAA;AACb,QAAA,IAAI,CAACE,WAAW,GAAG,IAAIC,OAAQ,CAAA,CAAA,EAAG,GAAG,CAAG,EAAA,CAAA,CAAA;QACxC,IAAI,CAACC,YAAY,GAAG,IAAA;QACpB,IAAI,CAACC,WAAW,GAAG,CAAA;QACnB,IAAI,CAACC,aAAa,GAAG,CAAA;QACrB,IAAI,CAACC,iBAAiB,GAAG,EAAC;AAC5B;+DAEA,IAAIC,UAA2C,GAAA;QAC7C,OAAO,IAAI,CAACN,WAAW;AACzB;IACA,IAAIM,UAAAA,CAAWC,KAAmC,EAAE;QAClD,IAAI,CAACP,WAAW,GAAGO,KAAAA;QACnB,IAAI,CAACL,YAAY,GAAG,IAAA;AACtB;2EAEA,IAAIM,WAAiE,GAAA;QACnE,OAAO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ACxC5E,GAAI6E,CAAAA,aAAa,IAAIC,oBAAAA,CAAqBE,UAAU;gBACpDhF,GAAI6E,CAAAA,aAAa,IAAI,EAAEC,qBAAqBC,cAAc,GAAGD,oBAAqBG,CAAAA,eAAe,CAAD;gBAChGjB,QAASkB,CAAAA,YAAY,CAACC,OAAO,CAAC,CAACC,GAAQA,GAAAA,GAAAA,CAAIC,KAAK,CAACrF,GAAAA,CAAAA,CAAAA;AACjD,gBAAA,IAAI,CAACiC,oBAAoB,CACvBjC,GAAAA,EACAgE,SAAS4B,gBAAgB,EACzB5B,QAAS1D,CAAAA,WAAW,EACpB0D,QAAAA,CAAS6B,oBAAoB,IAAI,MACjCzD,cACAC,EAAAA,IAAAA,CAAAA;AAEJ;AACF;AACF;AACA;;AAEC,MACD,SAAsB,GAAA;AACpB,QAAA,KAAK,CAACyD,SAAAA,EAAAA;QACN,IAAI,CAACxG,iBAAiB,GAAG,EAAC;AAC5B;qBAEA,gBAA2B,GAAA;AACzB,QAAA,MAAMC,aAAc,IAAI,CAACJ,YAAY,IAAI,IAAI,CAACF,WAAW;QACzD,IAAIM,UAAAA,IAAc,IAAI,CAACH,WAAW,IAAI,IAAI,CAACC,aAAa,EAAE;YACxD0G,SAAYC,EAAAA,CAAAA,gBAAgB,CAACzG,UAAY,EAAA,IAAI,CAACH,WAAW,EAAE,IAAI,CAACC,aAAa,CAAA;AAC/E;AACF;AACF;;;;"}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { Vector2, Vector4 } from '@zephyr3d/base';
|
|
2
|
+
import { ShaderHelper } from '../material/shader/helper.js';
|
|
3
|
+
import { drawFullscreenQuad } from './fullscreenquad.js';
|
|
4
|
+
import { MAX_SHADOW_MASK_LIGHTS } from '../values.js';
|
|
5
|
+
|
|
6
|
+
const UNIFORM_NAME_SHADOW_MAP = 'Z_UniformShadowMap';
|
|
7
|
+
/**
|
|
8
|
+
* Number of shadow-casting lights packed into a single RGBA8 mask array layer.
|
|
9
|
+
* One light per color channel.
|
|
10
|
+
*/ const SHADOW_MASK_LIGHTS_PER_LAYER = 4;
|
|
11
|
+
/**
|
|
12
|
+
* Maximum number of shadow mask array layers, derived from the per-light cap.
|
|
13
|
+
*/ const MAX_SHADOW_MASK_LAYERS = MAX_SHADOW_MASK_LIGHTS / SHADOW_MASK_LIGHTS_PER_LAYER;
|
|
14
|
+
/**
|
|
15
|
+
* Renders the screen-space shadow mask for the Forward+ pipeline.
|
|
16
|
+
*
|
|
17
|
+
* For each shadow-casting light, the light's visibility factor `[0,1]` (1 = lit,
|
|
18
|
+
* 0 = fully shadowed) is reconstructed from the linear depth prepass and written
|
|
19
|
+
* into one channel of one layer of an `rgba8unorm` texture array. Four lights are
|
|
20
|
+
* packed per layer (one per RGBA channel).
|
|
21
|
+
*
|
|
22
|
+
* The layer/channel assignment must stay in lockstep with
|
|
23
|
+
* {@link ClusteredLight.getVisibleLights}: shadow-casting lights occupy clustered
|
|
24
|
+
* buffer indices `1..N` in the order of `renderQueue.shadowedLights`. The zero-based
|
|
25
|
+
* light ordinal `s = index - 1` maps to `layer = s >> 2`, `channel = s & 3`. The
|
|
26
|
+
* clustered shading pass recovers the same mapping from a light's buffer index, so
|
|
27
|
+
* no per-light mask index is stored.
|
|
28
|
+
*
|
|
29
|
+
* @internal
|
|
30
|
+
*/ class ShadowMaskRenderer {
|
|
31
|
+
/** Fullscreen mask programs keyed by a per-light shader signature. */ _programs;
|
|
32
|
+
/** Bind groups paired with each cached program. */ _bindGroups;
|
|
33
|
+
/** One render state per RGBA channel (color mask selects the target channel). */ _channelStates;
|
|
34
|
+
_nearFar;
|
|
35
|
+
_cameraPosition;
|
|
36
|
+
_cameraParams;
|
|
37
|
+
constructor(){
|
|
38
|
+
this._programs = new Map();
|
|
39
|
+
this._bindGroups = new Map();
|
|
40
|
+
this._channelStates = null;
|
|
41
|
+
this._nearFar = new Vector2();
|
|
42
|
+
this._cameraPosition = new Vector4();
|
|
43
|
+
this._cameraParams = new Vector4();
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Number of array layers required to hold `numLights` shadow lights.
|
|
47
|
+
* @param numLights - Number of shadow-casting lights.
|
|
48
|
+
* @returns Layer count, clamped to {@link MAX_SHADOW_MASK_LAYERS}.
|
|
49
|
+
*/ static getLayerCount(numLights) {
|
|
50
|
+
const n = Math.min(numLights, MAX_SHADOW_MASK_LIGHTS);
|
|
51
|
+
return Math.min(Math.ceil(n / SHADOW_MASK_LIGHTS_PER_LAYER), MAX_SHADOW_MASK_LAYERS);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Render the shadow mask for the given shadow-casting lights.
|
|
55
|
+
*
|
|
56
|
+
* @param ctx - Draw context (must carry shadowMapInfo for the lights).
|
|
57
|
+
* @param depthTexture - Linear depth texture from the depth prepass.
|
|
58
|
+
* @param lights - Shadow-casting lights, in clustered-buffer order (index 1..N).
|
|
59
|
+
* @param getLayerFramebuffer - Resolves the framebuffer bound to mask array layer `k`.
|
|
60
|
+
*/ render(ctx, depthTexture, lights, getLayerFramebuffer) {
|
|
61
|
+
const device = ctx.device;
|
|
62
|
+
const numLights = Math.min(lights.length, MAX_SHADOW_MASK_LIGHTS);
|
|
63
|
+
if (numLights === 0 || !ctx.shadowMapInfo) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const numLayers = ShadowMaskRenderer.getLayerCount(numLights);
|
|
67
|
+
const channelStates = this.getChannelStates(device);
|
|
68
|
+
const savedShadowLight = ctx.currentShadowLight;
|
|
69
|
+
device.pushDeviceStates();
|
|
70
|
+
for(let layer = 0; layer < numLayers; layer++){
|
|
71
|
+
const framebuffer = getLayerFramebuffer(layer);
|
|
72
|
+
device.setFramebuffer(framebuffer);
|
|
73
|
+
// Clear to "fully lit" (1 = no shadow) so channels without an assigned
|
|
74
|
+
// light, and pixels outside any shadow, read as unshadowed. The mask array
|
|
75
|
+
// has no depth attachment, so depth/stencil clear args are null.
|
|
76
|
+
device.clearFrameBuffer(new Vector4(1, 1, 1, 1), null, null);
|
|
77
|
+
for(let channel = 0; channel < SHADOW_MASK_LIGHTS_PER_LAYER; channel++){
|
|
78
|
+
const ordinal = layer * SHADOW_MASK_LIGHTS_PER_LAYER + channel;
|
|
79
|
+
if (ordinal >= numLights) {
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
const light = lights[ordinal];
|
|
83
|
+
const shadowMapParams = ctx.shadowMapInfo.get(light);
|
|
84
|
+
if (!shadowMapParams || !shadowMapParams.shadowMap) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
ctx.currentShadowLight = light;
|
|
88
|
+
this.renderLightChannel(ctx, depthTexture, light, shadowMapParams, channelStates[channel]);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
device.popDeviceStates();
|
|
92
|
+
ctx.currentShadowLight = savedShadowLight;
|
|
93
|
+
}
|
|
94
|
+
/** Render one shadow light into one color channel of the current framebuffer. */ renderLightChannel(ctx, depthTexture, light, shadowMapParams, renderState) {
|
|
95
|
+
const device = ctx.device;
|
|
96
|
+
const key = this.getProgramKey(ctx, shadowMapParams);
|
|
97
|
+
let program = this._programs.get(key) ?? null;
|
|
98
|
+
let bindGroup = this._bindGroups.get(key) ?? null;
|
|
99
|
+
if (!program) {
|
|
100
|
+
program = this.createProgram(ctx, shadowMapParams);
|
|
101
|
+
bindGroup = device.createBindGroup(program.bindGroupLayouts[0]);
|
|
102
|
+
this._programs.set(key, program);
|
|
103
|
+
this._bindGroups.set(key, bindGroup);
|
|
104
|
+
}
|
|
105
|
+
bindGroup = this._bindGroups.get(key);
|
|
106
|
+
this.setUniforms(bindGroup, ctx, depthTexture, light, shadowMapParams);
|
|
107
|
+
device.setProgram(program);
|
|
108
|
+
device.setBindGroup(0, bindGroup);
|
|
109
|
+
drawFullscreenQuad(renderState);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The program signature: distinct shadow implementations, cascade counts and
|
|
113
|
+
* shadow map types must not share a compiled program.
|
|
114
|
+
*/ getProgramKey(ctx, shadowMapParams) {
|
|
115
|
+
return `${ctx.device.type}|${shadowMapParams.shaderHash}`;
|
|
116
|
+
}
|
|
117
|
+
getChannelStates(device) {
|
|
118
|
+
if (!this._channelStates) {
|
|
119
|
+
this._channelStates = [];
|
|
120
|
+
for(let c = 0; c < SHADOW_MASK_LIGHTS_PER_LAYER; c++){
|
|
121
|
+
const rs = device.createRenderStateSet();
|
|
122
|
+
rs.useDepthState().enableTest(false).enableWrite(false);
|
|
123
|
+
rs.useRasterizerState().setCullMode('none');
|
|
124
|
+
rs.useColorState().setColorMask(c === 0, c === 1, c === 2, c === 3);
|
|
125
|
+
this._channelStates.push(rs);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return this._channelStates;
|
|
129
|
+
}
|
|
130
|
+
setUniforms(bindGroup, ctx, depthTexture, light, shadowMapParams) {
|
|
131
|
+
const camera = ctx.camera;
|
|
132
|
+
const near = camera.getNearPlane();
|
|
133
|
+
const far = camera.getFarPlane();
|
|
134
|
+
const cameraPos = camera.getWorldPosition();
|
|
135
|
+
this._cameraPosition.setXYZW(cameraPos.x, cameraPos.y, cameraPos.z, 0);
|
|
136
|
+
this._cameraParams.setXYZW(near, far, 1, 1);
|
|
137
|
+
this._nearFar.setXY(near, far);
|
|
138
|
+
bindGroup.setValue('camera', {
|
|
139
|
+
position: this._cameraPosition,
|
|
140
|
+
params: this._cameraParams,
|
|
141
|
+
shadowDebugCascades: camera.shadowDebugCascades ? 1 : 0,
|
|
142
|
+
framestamp: ctx.device.frameInfo.frameCounter
|
|
143
|
+
});
|
|
144
|
+
// Full shadow light struct (matches helper.ts currentShadowLight lightStruct,
|
|
145
|
+
// including implParams which PCSS/VSM impls read via getShadowImplParams).
|
|
146
|
+
const implParams = new Vector4();
|
|
147
|
+
shadowMapParams.impl.getParams(implParams);
|
|
148
|
+
bindGroup.setValue('light', {
|
|
149
|
+
sunDir: ctx.sunLight ? ctx.sunLight.directionAndCutoff.xyz().scaleBy(-1) : new Vector4(0, 1, 0, 0).xyz(),
|
|
150
|
+
shadowCascades: shadowMapParams.numShadowCascades,
|
|
151
|
+
positionAndRange: light.positionAndRange,
|
|
152
|
+
directionAndCutoff: light.directionAndCutoff,
|
|
153
|
+
diffuseAndIntensity: light.diffuseAndIntensity,
|
|
154
|
+
extraParams: light.extraParams,
|
|
155
|
+
cascadeDistances: shadowMapParams.cascadeDistances,
|
|
156
|
+
depthBiasValues: shadowMapParams.depthBiasValues[0],
|
|
157
|
+
shadowCameraParams: shadowMapParams.cameraParams,
|
|
158
|
+
depthBiasScales: shadowMapParams.depthBiasScales,
|
|
159
|
+
implParams: implParams,
|
|
160
|
+
shadowMatrices: new Float32Array(shadowMapParams.shadowMatrices),
|
|
161
|
+
shadowStrength: light.shadow.shadowStrength,
|
|
162
|
+
envLightStrength: ctx.env?.light.strength ?? 0,
|
|
163
|
+
envLightSpecularStrength: ctx.env?.light.specularStrength ?? 1
|
|
164
|
+
});
|
|
165
|
+
bindGroup.setValue('invViewProjMatrix', camera.invViewProjectionMatrix);
|
|
166
|
+
bindGroup.setValue('cameraNearFar', this._nearFar);
|
|
167
|
+
bindGroup.setValue('flip', this.needFlip(ctx.device) ? 1 : 0);
|
|
168
|
+
bindGroup.setTexture('depthTex', depthTexture);
|
|
169
|
+
bindGroup.setTexture(UNIFORM_NAME_SHADOW_MAP, shadowMapParams.shadowMap, shadowMapParams.shadowMapSampler);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Whether the fullscreen output needs a vertical flip. Mask array layers are
|
|
173
|
+
* offscreen render targets, so the convention matches other offscreen passes
|
|
174
|
+
* (no flip); WebGPU still flips clip-space Y in the vertex shader.
|
|
175
|
+
*/ needFlip(_device) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
createProgram(ctx, shadowMapParams) {
|
|
179
|
+
const device = ctx.device;
|
|
180
|
+
const numCascades = shadowMapParams.numShadowCascades;
|
|
181
|
+
const shadowMap = shadowMapParams.shadowMap;
|
|
182
|
+
const program = device.buildRenderProgram({
|
|
183
|
+
label: 'ShadowMask',
|
|
184
|
+
vertex (pb) {
|
|
185
|
+
this.flip = pb.int().uniform(0);
|
|
186
|
+
this.$inputs.pos = pb.vec2().attrib('position');
|
|
187
|
+
this.$outputs.uv = pb.vec2();
|
|
188
|
+
pb.main(function() {
|
|
189
|
+
this.$builtins.position = pb.vec4(this.$inputs.pos, 1, 1);
|
|
190
|
+
this.$outputs.uv = pb.add(pb.mul(this.$inputs.pos.xy, 0.5), pb.vec2(0.5));
|
|
191
|
+
this.$if(pb.notEqual(this.flip, 0), function() {
|
|
192
|
+
this.$builtins.position.y = pb.neg(this.$builtins.position.y);
|
|
193
|
+
});
|
|
194
|
+
if (device.type === 'webgpu') {
|
|
195
|
+
this.$builtins.position.y = pb.neg(this.$builtins.position.y);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
fragment (pb) {
|
|
200
|
+
const cameraStruct = pb.defineStruct([
|
|
201
|
+
pb.vec4('position'),
|
|
202
|
+
pb.vec4('params'),
|
|
203
|
+
pb.float('shadowDebugCascades'),
|
|
204
|
+
// Required by PCSS temporal jitter (ShaderHelper.getFramestamp).
|
|
205
|
+
pb.int('framestamp')
|
|
206
|
+
]);
|
|
207
|
+
// Must match helper.ts currentShadowLight lightStruct field-for-field.
|
|
208
|
+
const lightStruct = pb.defineStruct([
|
|
209
|
+
pb.vec3('sunDir'),
|
|
210
|
+
pb.int('shadowCascades'),
|
|
211
|
+
pb.vec4('positionAndRange'),
|
|
212
|
+
pb.vec4('directionAndCutoff'),
|
|
213
|
+
pb.vec4('diffuseAndIntensity'),
|
|
214
|
+
pb.vec4('extraParams'),
|
|
215
|
+
pb.vec4('cascadeDistances'),
|
|
216
|
+
pb.vec4('depthBiasValues'),
|
|
217
|
+
pb.vec4('shadowCameraParams'),
|
|
218
|
+
pb.vec4('depthBiasScales'),
|
|
219
|
+
pb.vec4('implParams'),
|
|
220
|
+
pb.vec4[16]('shadowMatrices'),
|
|
221
|
+
pb.float('shadowStrength'),
|
|
222
|
+
pb.float('envLightStrength'),
|
|
223
|
+
pb.float('envLightSpecularStrength')
|
|
224
|
+
]);
|
|
225
|
+
this.camera = cameraStruct().uniform(0);
|
|
226
|
+
this.light = lightStruct().uniform(0);
|
|
227
|
+
const shadowTex = shadowMap.isTextureCube() ? shadowMap.isDepth() ? pb.texCubeShadow() : pb.texCube() : shadowMap.isTexture2D() ? shadowMap.isDepth() ? pb.tex2DShadow() : pb.tex2D() : shadowMap.isDepth() ? pb.tex2DArrayShadow() : pb.tex2DArray();
|
|
228
|
+
if (!shadowMap.isDepth() && !device.getDeviceCaps().textureCaps.getTextureFormatInfo(shadowMap.format).filterable) {
|
|
229
|
+
shadowTex.sampleType('unfilterable-float');
|
|
230
|
+
}
|
|
231
|
+
this[UNIFORM_NAME_SHADOW_MAP] = shadowTex.uniform(0);
|
|
232
|
+
this.depthTex = pb.tex2D().uniform(0);
|
|
233
|
+
this.invViewProjMatrix = pb.mat4().uniform(0);
|
|
234
|
+
this.cameraNearFar = pb.vec2().uniform(0);
|
|
235
|
+
this.$outputs.color = pb.vec4();
|
|
236
|
+
// Explicit-depth cascade selection (fragCoord.z is invalid in a fullscreen
|
|
237
|
+
// pass). Mirrors posteffect/sss.ts calculateTransmissionShadow.
|
|
238
|
+
pb.func('zShadowMaskFactor', [
|
|
239
|
+
pb.vec3('worldPos'),
|
|
240
|
+
pb.float('depth01'),
|
|
241
|
+
pb.float('NoL')
|
|
242
|
+
], function() {
|
|
243
|
+
if (numCascades > 1) {
|
|
244
|
+
this.$l.linearDepth = pb.mul(this.depth01, this.camera.params.y);
|
|
245
|
+
this.$l.splitDistances = this.light.cascadeDistances;
|
|
246
|
+
this.$l.comparison = pb.vec4(pb.greaterThan(pb.vec4(this.linearDepth), this.splitDistances));
|
|
247
|
+
this.$l.cascadeFlags = pb.vec4(pb.float(pb.greaterThan(this.light.shadowCascades, 0)), pb.float(pb.greaterThan(this.light.shadowCascades, 1)), pb.float(pb.greaterThan(this.light.shadowCascades, 2)), pb.float(pb.greaterThan(this.light.shadowCascades, 3)));
|
|
248
|
+
this.$l.split = pb.int(pb.dot(this.comparison, this.cascadeFlags));
|
|
249
|
+
if (device.type === 'webgl') {
|
|
250
|
+
this.$l.shadowVertex = pb.vec4();
|
|
251
|
+
this.$for(pb.int('cascade'), 0, 4, function() {
|
|
252
|
+
this.$if(pb.equal(this.cascade, this.split), function() {
|
|
253
|
+
this.shadowVertex = ShaderHelper.calculateShadowSpaceVertex(this, pb.vec4(this.worldPos, 1), this.cascade);
|
|
254
|
+
this.$break();
|
|
255
|
+
});
|
|
256
|
+
});
|
|
257
|
+
} else {
|
|
258
|
+
this.$l.shadowVertex = ShaderHelper.calculateShadowSpaceVertex(this, pb.vec4(this.worldPos, 1), this.split);
|
|
259
|
+
}
|
|
260
|
+
this.$l.shadow = shadowMapParams.impl.computeShadowCSM(shadowMapParams, this, this.shadowVertex, this.NoL, this.split);
|
|
261
|
+
this.$l.shadowDistance = this.light.shadowCameraParams.w;
|
|
262
|
+
this.shadow = pb.mix(this.shadow, 1, pb.smoothStep(pb.mul(this.shadowDistance, 0.8), this.shadowDistance, pb.distance(this.camera.position.xyz, this.worldPos)));
|
|
263
|
+
this.shadow = pb.mix(1, this.shadow, this.light.shadowStrength);
|
|
264
|
+
this.$return(pb.clamp(this.shadow, 0, 1));
|
|
265
|
+
} else {
|
|
266
|
+
this.$l.shadowVertex = ShaderHelper.calculateShadowSpaceVertex(this, pb.vec4(this.worldPos, 1));
|
|
267
|
+
this.$l.shadow = shadowMapParams.impl.computeShadow(shadowMapParams, this, this.shadowVertex, this.NoL);
|
|
268
|
+
this.$l.shadowDistance = this.light.shadowCameraParams.w;
|
|
269
|
+
this.shadow = pb.mix(this.shadow, 1, pb.smoothStep(pb.mul(this.shadowDistance, 0.8), this.shadowDistance, pb.distance(this.camera.position.xyz, this.worldPos)));
|
|
270
|
+
this.shadow = pb.mix(1, this.shadow, this.light.shadowStrength);
|
|
271
|
+
this.$return(pb.clamp(this.shadow, 0, 1));
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
pb.main(function() {
|
|
275
|
+
this.$l.pos = ShaderHelper.samplePositionFromDepth(this, this.depthTex, this.$inputs.uv, this.invViewProjMatrix, this.cameraNearFar);
|
|
276
|
+
// NoL is unavailable in a fullscreen pass (no geometric normal); it only
|
|
277
|
+
// feeds normal-offset bias, so a conservative 1.0 is used.
|
|
278
|
+
this.$l.factor = this.zShadowMaskFactor(this.pos.xyz, this.pos.w, pb.float(1));
|
|
279
|
+
this.$outputs.color = pb.vec4(this.factor);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
program.name = '@ShadowMask';
|
|
284
|
+
return program;
|
|
285
|
+
}
|
|
286
|
+
/** Release cached GPU resources. */ dispose() {
|
|
287
|
+
for (const program of this._programs.values()){
|
|
288
|
+
program.dispose();
|
|
289
|
+
}
|
|
290
|
+
this._programs.clear();
|
|
291
|
+
this._bindGroups.clear();
|
|
292
|
+
this._channelStates = null;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export { MAX_SHADOW_MASK_LAYERS, SHADOW_MASK_LIGHTS_PER_LAYER, ShadowMaskRenderer };
|
|
297
|
+
//# sourceMappingURL=shadow_mask_pass.js.map
|