{"version":3,"file":"GpuMsaaRestore.js","sources":["../../../../../src/rendering/renderers/gpu/renderTarget/GpuMsaaRestore.ts"],"sourcesContent":["import { TextureSource } from '../../shared/texture/sources/TextureSource';\n\nimport type { RenderTarget } from '../../shared/renderTarget/RenderTarget';\nimport type { WebGPURenderer } from '../WebGPURenderer';\n\n/**\n * Restores a multisampled colour buffer from its resolved image.\n *\n * A transient MSAA colour buffer (every one on a tile-based GPU, and ones the user marks `transient`\n * elsewhere) is cleared on load and discarded on store, which skips writing the 4-sample buffer back to\n * memory. The resolved single-sample texture is still stored, so a pass that reopens the target (a filter\n * popping back, a mask adding stencil, `clear: false`) copies the resolved texture into the target's back\n * texture and draws it back in as the pass's first draw, instead of loading samples that were never written.\n * On tile-based GPUs this beats storing and loading the 4-sample buffer even when a target is reopened every\n * frame; on GPUs that keep MSAA in video memory it doesn't, which is why they store it by default.\n *\n * The draw is a full-screen `textureLoad` with no blending, so every pixel gets its resolved colour back.\n * The back textures belong to the targets (`GpuRenderTarget.msaaBackTextures`); this holds only the\n * pipelines and bind groups.\n * @category rendering\n * @ignore\n */\nexport class GpuMsaaRestore\n{\n    private readonly _renderer: WebGPURenderer;\n    private readonly _device: GPUDevice;\n    private readonly _layout: GPUBindGroupLayout;\n    private readonly _pipelineLayout: GPUPipelineLayout;\n    /** per attachment layout, one pipeline per colour attachment */\n    private readonly _pipelines: Record<string, GPURenderPipeline[]> = Object.create(null);\n    private readonly _modules: Record<number, GPUShaderModule> = Object.create(null);\n    /** one bind group per back texture, dropped with the texture when a resize replaces it */\n    private readonly _bindGroups = new WeakMap<GPUTexture, GPUBindGroup>();\n\n    constructor(renderer: WebGPURenderer)\n    {\n        this._renderer = renderer;\n        this._device = renderer.gpu.device;\n        this._layout = this._device.createBindGroupLayout({\n            entries: [{\n                binding: 0,\n                visibility: GPUShaderStage.FRAGMENT,\n                texture: { sampleType: 'unfilterable-float' },\n            }],\n        });\n        this._pipelineLayout = this._device.createPipelineLayout({ bindGroupLayouts: [this._layout] });\n    }\n\n    /**\n     * Copies one colour attachment's resolved image into the target's back texture, creating it on first use\n     * at the attachment's size and format. Must be recorded outside a render pass.\n     * @param commandEncoder - the encoder to record the copy on\n     * @param renderTarget - the target being reopened\n     * @param index - the colour attachment to copy\n     * @param resolved - the attachment's resolved texture\n     */\n    public copy(commandEncoder: GPUCommandEncoder, renderTarget: RenderTarget, index: number, resolved: GPUTexture): void\n    {\n        const gpuRenderTarget = this._renderer.renderTarget.getGpuRenderTarget(renderTarget);\n        const colorTexture = renderTarget.colorAttachments[index].texture;\n\n        gpuRenderTarget.msaaBackTextures[index] ??= new TextureSource({\n            label: 'msaa-back-texture',\n            width: colorTexture.width,\n            height: colorTexture.height,\n            resolution: colorTexture._resolution,\n            format: gpuRenderTarget.msaaTextures[index].format,\n            autoGenerateMipmaps: false,\n            // every restore copies into it afresh, so an idle one can be freed and re-created on the next restore\n            autoGarbageCollect: true,\n        });\n\n        const backTexture = this._renderer.texture.getGpuSource(gpuRenderTarget.msaaBackTextures[index]);\n\n        commandEncoder.copyTextureToTexture(\n            { texture: resolved },\n            { texture: backTexture },\n            { width: Math.min(resolved.width, backTexture.width), height: Math.min(resolved.height, backTexture.height) },\n        );\n    }\n\n    /**\n     * Draws one colour attachment's back texture into the multisampled buffer. Must be the first draw of the\n     * pass, before any viewport or scissor is set.\n     * @param pass - the pass that was just begun\n     * @param renderTarget - the target the pass renders to\n     * @param index - the colour attachment to restore, copied by {@link GpuMsaaRestore.copy}\n     */\n    public draw(pass: GPURenderPassEncoder, renderTarget: RenderTarget, index: number): void\n    {\n        const gpuRenderTarget = this._renderer.renderTarget.getGpuRenderTarget(renderTarget);\n        const backTexture = this._renderer.texture.getGpuSource(gpuRenderTarget.msaaBackTextures[index]);\n\n        // the pipeline has to match the pass's attachments; a mask can add stencil mid-frame, so read them now\n        let key = renderTarget.depthStencilAttachment?.texture.format ?? '';\n\n        for (const attachment of renderTarget.colorAttachments)\n        {\n            key += `|${attachment.texture.format}`;\n        }\n\n        const pipelines = this._pipelines[key] ??= [];\n        let bindGroup = this._bindGroups.get(backTexture);\n\n        if (!bindGroup)\n        {\n            bindGroup = this._device.createBindGroup({\n                layout: this._layout,\n                entries: [{ binding: 0, resource: backTexture.createView() }],\n            });\n            this._bindGroups.set(backTexture, bindGroup);\n        }\n\n        pass.setPipeline(pipelines[index] ??= this._createPipeline(renderTarget, index));\n        pass.setBindGroup(0, bindGroup);\n        pass.draw(3);\n    }\n\n    private _getModule(index: number): GPUShaderModule\n    {\n        this._modules[index] ??= this._device.createShaderModule({\n            label: 'msaa-restore',\n            code: /* wgsl */ `\n                @group(0) @binding(0) var resolved: texture_2d<f32>;\n\n                @vertex\n                fn vertexMain(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {\n                    let pos = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));\n\n                    return vec4<f32>(pos[i], 0.0, 1.0);\n                }\n\n                @fragment\n                fn fragmentMain(@builtin(position) position: vec4<f32>) -> @location(${index}) vec4<f32> {\n                    return textureLoad(resolved, vec2<i32>(position.xy), 0);\n                }\n            `,\n        });\n\n        return this._modules[index];\n    }\n\n    private _createPipeline(renderTarget: RenderTarget, index: number): GPURenderPipeline\n    {\n        const depthStencilFormat = renderTarget.depthStencilAttachment?.texture.format;\n        let depthStencil: GPUDepthStencilState;\n\n        if (depthStencilFormat)\n        {\n            // matches the pass; the restore never tests or writes depth/stencil\n            depthStencil = { format: depthStencilFormat };\n\n            if (depthStencilFormat.includes('depth'))\n            {\n                depthStencil.depthWriteEnabled = false;\n                depthStencil.depthCompare = 'always';\n            }\n        }\n\n        const module = this._getModule(index);\n\n        return this._device.createRenderPipeline({\n            label: 'msaa-restore',\n            layout: this._pipelineLayout,\n            vertex: { module, entryPoint: 'vertexMain' },\n            fragment: {\n                module,\n                entryPoint: 'fragmentMain',\n                // every attachment must be declared to match the pass; only the restored one is written\n                targets: renderTarget.colorAttachments.map((attachment, i) => ({\n                    format: attachment.texture.format,\n                    writeMask: i === index ? GPUColorWrite.ALL : 0,\n                })),\n            },\n            depthStencil,\n            multisample: { count: 4 },\n        });\n    }\n}\n"],"names":["TextureSource"],"mappings":";;;;;AAsBO,MAAM,cAAA,CACb;AAAA,EAWI,YAAY,QAAA,EACZ;AANA;AAAA,IAAA,IAAA,CAAiB,UAAA,mBAAkD,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA;AACrF,IAAA,IAAA,CAAiB,QAAA,mBAA4C,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA;AAE/E;AAAA,IAAA,IAAA,CAAiB,WAAA,uBAAkB,OAAA,EAAkC;AAIjE,IAAA,IAAA,CAAK,SAAA,GAAY,QAAA;AACjB,IAAA,IAAA,CAAK,OAAA,GAAU,SAAS,GAAA,CAAI,MAAA;AAC5B,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA,CAAK,OAAA,CAAQ,qBAAA,CAAsB;AAAA,MAC9C,SAAS,CAAC;AAAA,QACN,OAAA,EAAS,CAAA;AAAA,QACT,YAAY,cAAA,CAAe,QAAA;AAAA,QAC3B,OAAA,EAAS,EAAE,UAAA,EAAY,oBAAA;AAAqB,OAC/C;AAAA,KACJ,CAAA;AACD,IAAA,IAAA,CAAK,eAAA,GAAkB,IAAA,CAAK,OAAA,CAAQ,oBAAA,CAAqB,EAAE,kBAAkB,CAAC,IAAA,CAAK,OAAO,CAAA,EAAG,CAAA;AAAA,EACjG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUO,IAAA,CAAK,cAAA,EAAmC,YAAA,EAA4B,KAAA,EAAe,QAAA,EAC1F;AAzDJ,IAAA,IAAA,EAAA;AA0DQ,IAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,SAAA,CAAU,YAAA,CAAa,mBAAmB,YAAY,CAAA;AACnF,IAAA,MAAM,YAAA,GAAe,YAAA,CAAa,gBAAA,CAAiB,KAAK,CAAA,CAAE,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