Skip to main content

graphics_core/pipelines/
composite_finalize.rs

1//! Single-pass fullscreen composite + alpha-finalize and depth-stamp pipelines (zero Vello dependency).
2
3use std::fmt;
4
5use crate::pipelines::SourceAlphaMode;
6
7const COMPOSITE_WGSL: &str = r#"
8struct VsOut {
9    @builtin(position) pos: vec4<f32>,
10    @location(0) uv: vec2<f32>,
11};
12
13@vertex
14fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {
15    let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
16    let pos = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
17    return VsOut(pos, uv);
18}
19
20@group(0) @binding(0) var base_tex: texture_2d<f32>;
21@group(0) @binding(1) var overlay_tex: texture_2d<f32>;
22@group(0) @binding(2) var tex_samp: sampler;
23
24fn to_premul(c: vec4<f32>, straight: bool) -> vec4<f32> {
25    if (straight) {
26        return vec4<f32>(c.rgb * c.a, c.a);
27    }
28    return c;
29}
30
31fn finalize_pm(pm: vec4<f32>, out_straight: bool) -> vec4<f32> {
32    if (out_straight) {
33        let rgb = select(vec3<f32>(0.0), clamp(pm.rgb / pm.a, vec3<f32>(0.0), vec3<f32>(1.0)), pm.a > 1e-5);
34        return vec4<f32>(rgb, clamp(pm.a, 0.0, 1.0));
35    }
36    return pm;
37}
38
39fn composite_impl(uv: vec2<f32>, base_straight: bool, overlay_straight: bool, out_straight: bool) -> vec4<f32> {
40    let base_pm = to_premul(textureSample(base_tex, tex_samp, uv), base_straight);
41    let over_pm = to_premul(textureSample(overlay_tex, tex_samp, uv), overlay_straight);
42    let pm = over_pm + base_pm * (1.0 - over_pm.a);
43    return finalize_pm(pm, out_straight);
44}
45
46@fragment fn fs_ss_s(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, true, true, true); }
47@fragment fn fs_ss_p(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, true, true, false); }
48@fragment fn fs_sp_s(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, true, false, true); }
49@fragment fn fs_sp_p(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, true, false, false); }
50@fragment fn fs_ps_s(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, false, true, true); }
51@fragment fn fs_ps_p(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, false, true, false); }
52@fragment fn fs_pp_s(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, false, false, true); }
53@fragment fn fs_pp_p(in: VsOut) -> @location(0) vec4<f32> { return composite_impl(in.uv, false, false, false); }
54"#;
55
56const SINGLE_WGSL: &str = r#"
57struct VsOut {
58    @builtin(position) pos: vec4<f32>,
59    @location(0) uv: vec2<f32>,
60};
61
62@vertex
63fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {
64    let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
65    let pos = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
66    return VsOut(pos, uv);
67}
68
69@group(0) @binding(0) var src_tex: texture_2d<f32>;
70@group(0) @binding(1) var src_samp: sampler;
71
72fn finalize_single_impl(uv: vec2<f32>, src_straight: bool, out_straight: bool) -> vec4<f32> {
73    let raw = textureSample(src_tex, src_samp, uv);
74    let pm = select(raw, vec4<f32>(raw.rgb * raw.a, raw.a), src_straight);
75    if (out_straight) {
76        let rgb = select(vec3<f32>(0.0), clamp(pm.rgb / pm.a, vec3<f32>(0.0), vec3<f32>(1.0)), pm.a > 1e-5);
77        return vec4<f32>(rgb, clamp(pm.a, 0.0, 1.0));
78    }
79    return pm;
80}
81
82@fragment fn fs_s_s(in: VsOut) -> @location(0) vec4<f32> { return finalize_single_impl(in.uv, true, true); }
83@fragment fn fs_s_p(in: VsOut) -> @location(0) vec4<f32> { return finalize_single_impl(in.uv, true, false); }
84@fragment fn fs_p_s(in: VsOut) -> @location(0) vec4<f32> { return finalize_single_impl(in.uv, false, true); }
85@fragment fn fs_p_p(in: VsOut) -> @location(0) vec4<f32> { return finalize_single_impl(in.uv, false, false); }
86
87@fragment
88fn fs_stamp_depth(in: VsOut) {
89    let c = textureSample(src_tex, src_samp, in.uv);
90    if (c.a <= 0.0) {
91        discard;
92    }
93}
94"#;
95
96/// Output alpha encoding emitted by [`CompositeFinalizePipeline`].
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub enum OutputAlphaMode {
99    /// Emit straight (unpremultiplied) RGB + A, zeroing RGB when alpha <= 1e-5.
100    #[default]
101    Straight,
102    /// Emit premultiplied RGB + A directly into the destination attachment.
103    Premultiplied,
104}
105
106/// Errors returned by [`CompositeFinalizePipeline`] depth-stamping operations.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum CompositeFinalizeError {
109    /// Depth-stamp pass requested on a pipeline created with `depth_format: None`.
110    DepthPipelineNotConfigured,
111}
112
113impl fmt::Display for CompositeFinalizeError {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Self::DepthPipelineNotConfigured => {
117                write!(f, "CompositeFinalizePipeline created without depth_format")
118            }
119        }
120    }
121}
122
123impl std::error::Error for CompositeFinalizeError {}
124
125#[inline]
126fn source_mode_idx(mode: SourceAlphaMode) -> usize {
127    match mode {
128        SourceAlphaMode::Straight => 0,
129        SourceAlphaMode::Premultiplied => 1,
130    }
131}
132
133#[inline]
134fn output_mode_idx(mode: OutputAlphaMode) -> usize {
135    match mode {
136        OutputAlphaMode::Straight => 0,
137        OutputAlphaMode::Premultiplied => 1,
138    }
139}
140
141fn create_fullscreen_color_pipeline(
142    device: &wgpu::Device,
143    layout: &wgpu::PipelineLayout,
144    shader: &wgpu::ShaderModule,
145    dst_format: wgpu::TextureFormat,
146    fs_entry: &str,
147    label: &str,
148) -> wgpu::RenderPipeline {
149    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
150        label: Some(label),
151        layout: Some(layout),
152        vertex: wgpu::VertexState {
153            module: shader,
154            entry_point: Some("vs_main"),
155            compilation_options: wgpu::PipelineCompilationOptions::default(),
156            buffers: &[],
157        },
158        primitive: wgpu::PrimitiveState {
159            topology: wgpu::PrimitiveTopology::TriangleList,
160            ..Default::default()
161        },
162        depth_stencil: None,
163        multisample: wgpu::MultisampleState::default(),
164        fragment: Some(wgpu::FragmentState {
165            module: shader,
166            entry_point: Some(fs_entry),
167            compilation_options: wgpu::PipelineCompilationOptions::default(),
168            targets: &[Some(wgpu::ColorTargetState {
169                format: dst_format,
170                blend: None,
171                write_mask: wgpu::ColorWrites::ALL,
172            })],
173        }),
174        multiview_mask: None,
175        cache: None,
176    })
177}
178
179fn create_depth_stamp_pipeline(
180    device: &wgpu::Device,
181    layout: &wgpu::PipelineLayout,
182    shader: &wgpu::ShaderModule,
183    depth_format: wgpu::TextureFormat,
184) -> wgpu::RenderPipeline {
185    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
186        label: Some("graphics_core_composite_stamp_depth"),
187        layout: Some(layout),
188        vertex: wgpu::VertexState {
189            module: shader,
190            entry_point: Some("vs_main"),
191            compilation_options: wgpu::PipelineCompilationOptions::default(),
192            buffers: &[],
193        },
194        primitive: wgpu::PrimitiveState {
195            topology: wgpu::PrimitiveTopology::TriangleList,
196            ..Default::default()
197        },
198        depth_stencil: Some(wgpu::DepthStencilState {
199            format: depth_format,
200            depth_write_enabled: Some(true),
201            depth_compare: Some(wgpu::CompareFunction::Always),
202            stencil: wgpu::StencilState::default(),
203            bias: wgpu::DepthBiasState::default(),
204        }),
205        multisample: wgpu::MultisampleState::default(),
206        fragment: Some(wgpu::FragmentState {
207            module: shader,
208            entry_point: Some("fs_stamp_depth"),
209            compilation_options: wgpu::PipelineCompilationOptions::default(),
210            targets: &[],
211        }),
212        multiview_mask: None,
213        cache: None,
214    })
215}
216
217fn texture_layout_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
218    wgpu::BindGroupLayoutEntry {
219        binding,
220        visibility: wgpu::ShaderStages::FRAGMENT,
221        ty: wgpu::BindingType::Texture {
222            sample_type: wgpu::TextureSampleType::Float { filterable: true },
223            view_dimension: wgpu::TextureViewDimension::D2,
224            multisampled: false,
225        },
226        count: None,
227    }
228}
229
230fn sampler_layout_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
231    wgpu::BindGroupLayoutEntry {
232        binding,
233        visibility: wgpu::ShaderStages::FRAGMENT,
234        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
235        count: None,
236    }
237}
238
239/// Pure-WGPU single-pass composite, alpha-finalize (`LoadOp::DontCare`), and overlay depth-stamp pipeline.
240pub struct CompositeFinalizePipeline {
241    composite_bgl: wgpu::BindGroupLayout,
242    single_bgl: wgpu::BindGroupLayout,
243    sampler: wgpu::Sampler,
244    // Indexed as [base_alpha][overlay_alpha][output_alpha].
245    composite_pipelines: [[[wgpu::RenderPipeline; 2]; 2]; 2],
246    // Indexed as [src_alpha][output_alpha].
247    single_pipelines: [[wgpu::RenderPipeline; 2]; 2],
248    depth_stamp_pipeline: Option<wgpu::RenderPipeline>,
249}
250
251impl CompositeFinalizePipeline {
252    pub fn new(
253        device: &wgpu::Device,
254        dst_format: wgpu::TextureFormat,
255        depth_format: Option<wgpu::TextureFormat>,
256    ) -> Self {
257        let composite_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
258            label: Some("graphics_core_composite_finalize_shader"),
259            source: wgpu::ShaderSource::Wgsl(COMPOSITE_WGSL.into()),
260        });
261        let single_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
262            label: Some("graphics_core_single_finalize_shader"),
263            source: wgpu::ShaderSource::Wgsl(SINGLE_WGSL.into()),
264        });
265
266        let composite_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
267            label: Some("graphics_core_composite_finalize_bgl"),
268            entries: &[
269                texture_layout_entry(0),
270                texture_layout_entry(1),
271                sampler_layout_entry(2),
272            ],
273        });
274        let single_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
275            label: Some("graphics_core_single_finalize_bgl"),
276            entries: &[texture_layout_entry(0), sampler_layout_entry(1)],
277        });
278
279        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
280            label: Some("graphics_core_composite_finalize_sampler"),
281            mag_filter: wgpu::FilterMode::Nearest,
282            min_filter: wgpu::FilterMode::Nearest,
283            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
284            ..Default::default()
285        });
286
287        let composite_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
288            label: Some("graphics_core_composite_finalize_layout"),
289            bind_group_layouts: &[Some(&composite_bgl)],
290            immediate_size: 0,
291        });
292        let single_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
293            label: Some("graphics_core_single_finalize_layout"),
294            bind_group_layouts: &[Some(&single_bgl)],
295            immediate_size: 0,
296        });
297
298        let composite_pipelines = [
299            [
300                [
301                    create_fullscreen_color_pipeline(
302                        device,
303                        &composite_layout,
304                        &composite_shader,
305                        dst_format,
306                        "fs_ss_s",
307                        "graphics_core_composite_ss_s",
308                    ),
309                    create_fullscreen_color_pipeline(
310                        device,
311                        &composite_layout,
312                        &composite_shader,
313                        dst_format,
314                        "fs_ss_p",
315                        "graphics_core_composite_ss_p",
316                    ),
317                ],
318                [
319                    create_fullscreen_color_pipeline(
320                        device,
321                        &composite_layout,
322                        &composite_shader,
323                        dst_format,
324                        "fs_sp_s",
325                        "graphics_core_composite_sp_s",
326                    ),
327                    create_fullscreen_color_pipeline(
328                        device,
329                        &composite_layout,
330                        &composite_shader,
331                        dst_format,
332                        "fs_sp_p",
333                        "graphics_core_composite_sp_p",
334                    ),
335                ],
336            ],
337            [
338                [
339                    create_fullscreen_color_pipeline(
340                        device,
341                        &composite_layout,
342                        &composite_shader,
343                        dst_format,
344                        "fs_ps_s",
345                        "graphics_core_composite_ps_s",
346                    ),
347                    create_fullscreen_color_pipeline(
348                        device,
349                        &composite_layout,
350                        &composite_shader,
351                        dst_format,
352                        "fs_ps_p",
353                        "graphics_core_composite_ps_p",
354                    ),
355                ],
356                [
357                    create_fullscreen_color_pipeline(
358                        device,
359                        &composite_layout,
360                        &composite_shader,
361                        dst_format,
362                        "fs_pp_s",
363                        "graphics_core_composite_pp_s",
364                    ),
365                    create_fullscreen_color_pipeline(
366                        device,
367                        &composite_layout,
368                        &composite_shader,
369                        dst_format,
370                        "fs_pp_p",
371                        "graphics_core_composite_pp_p",
372                    ),
373                ],
374            ],
375        ];
376
377        let single_pipelines = [
378            [
379                create_fullscreen_color_pipeline(
380                    device,
381                    &single_layout,
382                    &single_shader,
383                    dst_format,
384                    "fs_s_s",
385                    "graphics_core_single_s_s",
386                ),
387                create_fullscreen_color_pipeline(
388                    device,
389                    &single_layout,
390                    &single_shader,
391                    dst_format,
392                    "fs_s_p",
393                    "graphics_core_single_s_p",
394                ),
395            ],
396            [
397                create_fullscreen_color_pipeline(
398                    device,
399                    &single_layout,
400                    &single_shader,
401                    dst_format,
402                    "fs_p_s",
403                    "graphics_core_single_p_s",
404                ),
405                create_fullscreen_color_pipeline(
406                    device,
407                    &single_layout,
408                    &single_shader,
409                    dst_format,
410                    "fs_p_p",
411                    "graphics_core_single_p_p",
412                ),
413            ],
414        ];
415
416        let depth_stamp_pipeline = depth_format
417            .map(|df| create_depth_stamp_pipeline(device, &single_layout, &single_shader, df));
418
419        Self {
420            composite_bgl,
421            single_bgl,
422            sampler,
423            composite_pipelines,
424            single_pipelines,
425            depth_stamp_pipeline,
426        }
427    }
428
429    /// Creates a reusable bind group for 2-input `overlay` over `base` compositing.
430    pub fn create_composite_bind_group(
431        &self,
432        device: &wgpu::Device,
433        base_view: &wgpu::TextureView,
434        overlay_view: &wgpu::TextureView,
435    ) -> wgpu::BindGroup {
436        device.create_bind_group(&wgpu::BindGroupDescriptor {
437            label: Some("graphics_core_composite_finalize_bg"),
438            layout: &self.composite_bgl,
439            entries: &[
440                wgpu::BindGroupEntry {
441                    binding: 0,
442                    resource: wgpu::BindingResource::TextureView(base_view),
443                },
444                wgpu::BindGroupEntry {
445                    binding: 1,
446                    resource: wgpu::BindingResource::TextureView(overlay_view),
447                },
448                wgpu::BindGroupEntry {
449                    binding: 2,
450                    resource: wgpu::BindingResource::Sampler(&self.sampler),
451                },
452            ],
453        })
454    }
455
456    /// Creates a reusable bind group for 1-input finalization or overlay depth stamping.
457    pub fn create_single_bind_group(
458        &self,
459        device: &wgpu::Device,
460        src_view: &wgpu::TextureView,
461    ) -> wgpu::BindGroup {
462        device.create_bind_group(&wgpu::BindGroupDescriptor {
463            label: Some("graphics_core_single_finalize_bg"),
464            layout: &self.single_bgl,
465            entries: &[
466                wgpu::BindGroupEntry {
467                    binding: 0,
468                    resource: wgpu::BindingResource::TextureView(src_view),
469                },
470                wgpu::BindGroupEntry {
471                    binding: 1,
472                    resource: wgpu::BindingResource::Sampler(&self.sampler),
473                },
474            ],
475        })
476    }
477
478    fn run_fullscreen_color_pass(
479        encoder: &mut wgpu::CommandEncoder,
480        dst_view: &wgpu::TextureView,
481        pipeline: &wgpu::RenderPipeline,
482        bind_group: &wgpu::BindGroup,
483        label: &'static str,
484    ) {
485        // SAFETY: the fullscreen triangle covers the entire viewport with color blending disabled.
486        let load = wgpu::LoadOp::DontCare(unsafe { wgpu::LoadOpDontCare::enabled() });
487        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
488            label: Some(label),
489            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
490                view: dst_view,
491                resolve_target: None,
492                ops: wgpu::Operations {
493                    load,
494                    store: wgpu::StoreOp::Store,
495                },
496                depth_slice: None,
497            })],
498            depth_stencil_attachment: None,
499            timestamp_writes: None,
500            occlusion_query_set: None,
501            multiview_mask: None,
502        });
503        pass.set_pipeline(pipeline);
504        pass.set_bind_group(0, bind_group, &[]);
505        pass.draw(0..3, 0..1);
506    }
507
508    /// Composites `overlay` over `base` via `f32` Porter-Duff `SrcOver` into `dst_view` (`LoadOp::DontCare`).
509    pub fn composite_with_bind_group(
510        &self,
511        encoder: &mut wgpu::CommandEncoder,
512        dst_view: &wgpu::TextureView,
513        bind_group: &wgpu::BindGroup,
514        base_alpha: SourceAlphaMode,
515        overlay_alpha: SourceAlphaMode,
516        output_alpha: OutputAlphaMode,
517    ) {
518        let pipeline = &self.composite_pipelines[source_mode_idx(base_alpha)]
519            [source_mode_idx(overlay_alpha)][output_mode_idx(output_alpha)];
520        Self::run_fullscreen_color_pass(
521            encoder,
522            dst_view,
523            pipeline,
524            bind_group,
525            "graphics_core_composite_finalize_pass",
526        );
527    }
528
529    /// Convenience wrapper creating a temporary composite bind group and encoding [`Self::composite_with_bind_group`].
530    #[allow(clippy::too_many_arguments)]
531    pub fn composite(
532        &self,
533        device: &wgpu::Device,
534        encoder: &mut wgpu::CommandEncoder,
535        dst_view: &wgpu::TextureView,
536        base_view: &wgpu::TextureView,
537        overlay_view: &wgpu::TextureView,
538        base_alpha: SourceAlphaMode,
539        overlay_alpha: SourceAlphaMode,
540        output_alpha: OutputAlphaMode,
541    ) {
542        let bg = self.create_composite_bind_group(device, base_view, overlay_view);
543        self.composite_with_bind_group(
544            encoder,
545            dst_view,
546            &bg,
547            base_alpha,
548            overlay_alpha,
549            output_alpha,
550        );
551    }
552
553    /// Finalizes a single source texture into `dst_view` (`LoadOp::DontCare`).
554    pub fn finalize_single_with_bind_group(
555        &self,
556        encoder: &mut wgpu::CommandEncoder,
557        dst_view: &wgpu::TextureView,
558        bind_group: &wgpu::BindGroup,
559        src_alpha: SourceAlphaMode,
560        output_alpha: OutputAlphaMode,
561    ) {
562        let pipeline =
563            &self.single_pipelines[source_mode_idx(src_alpha)][output_mode_idx(output_alpha)];
564        Self::run_fullscreen_color_pass(
565            encoder,
566            dst_view,
567            pipeline,
568            bind_group,
569            "graphics_core_single_finalize_pass",
570        );
571    }
572
573    /// Convenience wrapper creating a temporary bind group and encoding [`Self::finalize_single_with_bind_group`].
574    pub fn finalize_single(
575        &self,
576        device: &wgpu::Device,
577        encoder: &mut wgpu::CommandEncoder,
578        dst_view: &wgpu::TextureView,
579        src_view: &wgpu::TextureView,
580        src_alpha: SourceAlphaMode,
581        output_alpha: OutputAlphaMode,
582    ) {
583        let bg = self.create_single_bind_group(device, src_view);
584        self.finalize_single_with_bind_group(encoder, dst_view, &bg, src_alpha, output_alpha);
585    }
586
587    /// Stamps `z = 0.0` into `depth_view` (`LoadOp::Load`) wherever the bound overlay texture has `alpha > 0.0`.
588    pub fn stamp_overlay_depth_with_bind_group(
589        &self,
590        encoder: &mut wgpu::CommandEncoder,
591        depth_view: &wgpu::TextureView,
592        single_bind_group: &wgpu::BindGroup,
593    ) -> Result<(), CompositeFinalizeError> {
594        let pipeline = self
595            .depth_stamp_pipeline
596            .as_ref()
597            .ok_or(CompositeFinalizeError::DepthPipelineNotConfigured)?;
598        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
599            label: Some("graphics_core_composite_stamp_depth_pass"),
600            color_attachments: &[],
601            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
602                view: depth_view,
603                depth_ops: Some(wgpu::Operations {
604                    load: wgpu::LoadOp::Load,
605                    store: wgpu::StoreOp::Store,
606                }),
607                stencil_ops: None,
608            }),
609            timestamp_writes: None,
610            occlusion_query_set: None,
611            multiview_mask: None,
612        });
613        pass.set_pipeline(pipeline);
614        pass.set_bind_group(0, single_bind_group, &[]);
615        pass.draw(0..3, 0..1);
616        Ok(())
617    }
618
619    /// Convenience wrapper creating a temporary single-texture bind group and stamping `z = 0.0` into `depth_view`.
620    pub fn stamp_overlay_depth(
621        &self,
622        device: &wgpu::Device,
623        encoder: &mut wgpu::CommandEncoder,
624        depth_view: &wgpu::TextureView,
625        overlay_view: &wgpu::TextureView,
626    ) -> Result<(), CompositeFinalizeError> {
627        let bg = self.create_single_bind_group(device, overlay_view);
628        self.stamp_overlay_depth_with_bind_group(encoder, depth_view, &bg)
629    }
630}