Skip to main content

graphics_core/pipelines/
alpha_blit.rs

1//! Generic transparent texture alpha-blit composite pass (`LoadOp::Load`, zero Vello dependency).
2
3const ALPHA_BLIT_WGSL: &str = r#"
4struct VsOut {
5    @builtin(position) pos: vec4<f32>,
6    @location(0) uv: vec2<f32>,
7};
8
9@vertex
10fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {
11    let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
12    let pos = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
13    return VsOut(pos, uv);
14}
15
16@group(0) @binding(0) var src_tex: texture_2d<f32>;
17@group(0) @binding(1) var src_samp: sampler;
18
19@fragment
20fn fs_main_straight(in: VsOut) -> @location(0) vec4<f32> {
21    let c = textureSample(src_tex, src_samp, in.uv);
22    return vec4<f32>(c.rgb * c.a, c.a);
23}
24
25@fragment
26fn fs_main_premul(in: VsOut) -> @location(0) vec4<f32> {
27    return textureSample(src_tex, src_samp, in.uv);
28}
29"#;
30
31/// Alpha encoding of the source texture sampled by [`AlphaBlitPipeline`].
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum SourceAlphaMode {
34    /// Source texture stores straight (unpremultiplied) RGB + A (e.g., Vello `Rgba8Unorm` output).
35    #[default]
36    Straight,
37    /// Source texture already stores premultiplied RGB + A.
38    Premultiplied,
39}
40
41/// Pure-WGPU fullscreen alpha-compositing blit pipeline using `LoadOp::Load`.
42pub struct AlphaBlitPipeline {
43    bind_group_layout: wgpu::BindGroupLayout,
44    sampler: wgpu::Sampler,
45    straight_pipeline: wgpu::RenderPipeline,
46    premul_pipeline: wgpu::RenderPipeline,
47}
48
49fn create_blit_pipeline(
50    device: &wgpu::Device,
51    layout: &wgpu::PipelineLayout,
52    shader: &wgpu::ShaderModule,
53    dst_format: wgpu::TextureFormat,
54    fs_entry: &str,
55    label: &str,
56) -> wgpu::RenderPipeline {
57    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
58        label: Some(label),
59        layout: Some(layout),
60        vertex: wgpu::VertexState {
61            module: shader,
62            entry_point: Some("vs_main"),
63            compilation_options: wgpu::PipelineCompilationOptions::default(),
64            buffers: &[],
65        },
66        primitive: wgpu::PrimitiveState {
67            topology: wgpu::PrimitiveTopology::TriangleList,
68            ..Default::default()
69        },
70        depth_stencil: None,
71        multisample: wgpu::MultisampleState::default(),
72        fragment: Some(wgpu::FragmentState {
73            module: shader,
74            entry_point: Some(fs_entry),
75            compilation_options: wgpu::PipelineCompilationOptions::default(),
76            targets: &[Some(wgpu::ColorTargetState {
77                format: dst_format,
78                blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
79                write_mask: wgpu::ColorWrites::ALL,
80            })],
81        }),
82        multiview_mask: None,
83        cache: None,
84    })
85}
86
87impl AlphaBlitPipeline {
88    pub fn new(device: &wgpu::Device, dst_format: wgpu::TextureFormat) -> Self {
89        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
90            label: Some("graphics_core_alpha_blit_shader"),
91            source: wgpu::ShaderSource::Wgsl(ALPHA_BLIT_WGSL.into()),
92        });
93
94        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
95            label: Some("graphics_core_alpha_blit_bgl"),
96            entries: &[
97                wgpu::BindGroupLayoutEntry {
98                    binding: 0,
99                    visibility: wgpu::ShaderStages::FRAGMENT,
100                    ty: wgpu::BindingType::Texture {
101                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
102                        view_dimension: wgpu::TextureViewDimension::D2,
103                        multisampled: false,
104                    },
105                    count: None,
106                },
107                wgpu::BindGroupLayoutEntry {
108                    binding: 1,
109                    visibility: wgpu::ShaderStages::FRAGMENT,
110                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
111                    count: None,
112                },
113            ],
114        });
115
116        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
117            label: Some("graphics_core_alpha_blit_sampler"),
118            mag_filter: wgpu::FilterMode::Nearest,
119            min_filter: wgpu::FilterMode::Nearest,
120            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
121            ..Default::default()
122        });
123
124        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
125            label: Some("graphics_core_alpha_blit_layout"),
126            bind_group_layouts: &[Some(&bind_group_layout)],
127            immediate_size: 0,
128        });
129
130        let straight_pipeline = create_blit_pipeline(
131            device,
132            &pipeline_layout,
133            &shader,
134            dst_format,
135            "fs_main_straight",
136            "graphics_core_alpha_blit_straight",
137        );
138        let premul_pipeline = create_blit_pipeline(
139            device,
140            &pipeline_layout,
141            &shader,
142            dst_format,
143            "fs_main_premul",
144            "graphics_core_alpha_blit_premul",
145        );
146
147        Self {
148            bind_group_layout,
149            sampler,
150            straight_pipeline,
151            premul_pipeline,
152        }
153    }
154
155    /// Creates a reusable bind group for a given source texture view.
156    pub fn create_bind_group(
157        &self,
158        device: &wgpu::Device,
159        src_view: &wgpu::TextureView,
160    ) -> wgpu::BindGroup {
161        device.create_bind_group(&wgpu::BindGroupDescriptor {
162            label: Some("graphics_core_alpha_blit_bg"),
163            layout: &self.bind_group_layout,
164            entries: &[
165                wgpu::BindGroupEntry {
166                    binding: 0,
167                    resource: wgpu::BindingResource::TextureView(src_view),
168                },
169                wgpu::BindGroupEntry {
170                    binding: 1,
171                    resource: wgpu::BindingResource::Sampler(&self.sampler),
172                },
173            ],
174        })
175    }
176
177    /// Composites a pre-bound source texture over `dst_view` preserving existing contents (`LoadOp::Load`).
178    pub fn composite_with_bind_group(
179        &self,
180        encoder: &mut wgpu::CommandEncoder,
181        bind_group: &wgpu::BindGroup,
182        dst_view: &wgpu::TextureView,
183        mode: SourceAlphaMode,
184    ) {
185        let pipeline = match mode {
186            SourceAlphaMode::Straight => &self.straight_pipeline,
187            SourceAlphaMode::Premultiplied => &self.premul_pipeline,
188        };
189
190        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
191            label: Some("graphics_core_alpha_blit_pass"),
192            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
193                view: dst_view,
194                resolve_target: None,
195                ops: wgpu::Operations {
196                    load: wgpu::LoadOp::Load,
197                    store: wgpu::StoreOp::Store,
198                },
199                depth_slice: None,
200            })],
201            depth_stencil_attachment: None,
202            timestamp_writes: None,
203            occlusion_query_set: None,
204            multiview_mask: None,
205        });
206
207        pass.set_pipeline(pipeline);
208        pass.set_bind_group(0, bind_group, &[]);
209        pass.draw(0..3, 0..1);
210    }
211
212    /// Convenience method creating a temporary bind group and compositing `src_view` over `dst_view`.
213    pub fn composite(
214        &self,
215        device: &wgpu::Device,
216        encoder: &mut wgpu::CommandEncoder,
217        src_view: &wgpu::TextureView,
218        dst_view: &wgpu::TextureView,
219        mode: SourceAlphaMode,
220    ) {
221        let bg = self.create_bind_group(device, src_view);
222        self.composite_with_bind_group(encoder, &bg, dst_view, mode);
223    }
224}