Skip to main content

lactea_render/renderer/
burn.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! `ProjectM::BurnInTexture`: one textured quad copied into the image the next warp samples.
5
6use super::*;
7use wgpu::util::DeviceExt;
8
9const SRC: &str = r#"
10@group(0) @binding(0) var tex: texture_2d<f32>;
11@group(0) @binding(1) var samp: sampler;
12
13struct VOut {
14    @builtin(position) position: vec4<f32>,
15    @location(0) uv: vec2<f32>,
16};
17
18@vertex
19fn vs_main(@location(0) clip: vec4<f32>, @location(1) uv: vec2<f32>) -> VOut {
20    var o: VOut;
21    o.position = clip;
22    o.uv = uv;
23    return o;
24}
25
26@fragment
27fn fs_main(in: VOut) -> @location(0) vec4<f32> {
28    return textureSample(tex, samp, in.uv);
29}
30"#;
31
32const ATTRS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x2];
33
34/// Corner of the quad: homogeneous clip position and texture coordinate (row 0 = top).
35#[repr(C)]
36#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
37struct Vertex {
38    clip: [f32; 4],
39    uv: [f32; 2],
40}
41
42/// The copy pipeline (replace, no blending), built on the first burn.
43pub(super) struct BurnPipe {
44    pipeline: wgpu::RenderPipeline,
45}
46
47impl BurnPipe {
48    pub(super) fn new(device: &wgpu::Device, bgl_tex: &wgpu::BindGroupLayout) -> Self {
49        let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
50            label: Some("burn"),
51            source: wgpu::ShaderSource::Wgsl(SRC.into()),
52        });
53        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
54            label: Some("burn"),
55            bind_group_layouts: &[Some(bgl_tex)],
56            immediate_size: 0,
57        });
58        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
59            label: Some("burn"),
60            layout: Some(&layout),
61            vertex: wgpu::VertexState {
62                module: &module,
63                entry_point: Some("vs_main"),
64                compilation_options: Default::default(),
65                buffers: &[Some(wgpu::VertexBufferLayout {
66                    array_stride: std::mem::size_of::<Vertex>() as u64,
67                    step_mode: wgpu::VertexStepMode::Vertex,
68                    attributes: &ATTRS,
69                })],
70            },
71            primitive: wgpu::PrimitiveState {
72                topology: wgpu::PrimitiveTopology::TriangleStrip,
73                ..Default::default()
74            },
75            depth_stencil: None,
76            multisample: wgpu::MultisampleState::default(),
77            fragment: Some(wgpu::FragmentState {
78                module: &module,
79                entry_point: Some("fs_main"),
80                compilation_options: Default::default(),
81                targets: &[Some(wgpu::ColorTargetState {
82                    format: INTERNAL_FORMAT,
83                    blend: None,
84                    write_mask: wgpu::ColorWrites::ALL,
85                })],
86            }),
87            multiview_mask: None,
88            cache: None,
89        });
90        Self { pipeline }
91    }
92}
93
94/// The quad of `CopyTexture::Copy(left, top, width, height)` for a `target_w x target_h` target: projectM scales the
95/// unit quad by `(width / W, height / H)` and feeds `(left / W, top / H)` through the matrix's fourth *column*, which
96/// the row-vector product `position * matrix` turns into the homogeneous `w = 1 + x left / W + y top / H`, not into
97/// a translation. The same arithmetic is kept so a burn lands where projectM puts it.
98fn quad(target: (u32, u32), rect: [i32; 4]) -> [Vertex; 4] {
99    let (w, h) = (target.0 as f32, target.1 as f32);
100    let [left, top, width, height] = rect.map(|v| v as f32);
101    let (sx, sy) = (width / w, height / h);
102    let (tx, ty) = (left / w, top / h);
103    // triangle strip: top-left, top-right, bottom-left, bottom-right (y up in clip space)
104    [
105        (-1.0f32, 1.0f32, 0.0f32, 0.0f32),
106        (1.0, 1.0, 1.0, 0.0),
107        (-1.0, -1.0, 0.0, 1.0),
108        (1.0, -1.0, 1.0, 1.0),
109    ]
110    .map(|(x, y, u, v)| Vertex {
111        clip: [x * sx, y * sy, 0.0, 1.0 + x * tx + y * ty],
112        uv: [u, v],
113    })
114}
115
116impl Renderer {
117    /// `ProjectM::BurnInTexture`: draws `rgba8` (`w x h`, row 0 = top, straight alpha ignored) as one quad over the
118    /// image the next frame's warp reads, opaque and without blending. `rect = [left, top, width, height]` in
119    /// target pixels, with projectM's placement arithmetic (see [`quad`]); a rectangle of zero size draws nothing.
120    /// Unlike projectM's OpenGL texture id the pixels are copied in, so the caller keeps its buffer.
121    pub fn burn_texture(
122        &mut self,
123        rgba8: &[u8],
124        w: u32,
125        h: u32,
126        rect: [i32; 4],
127    ) -> Result<(), RenderError> {
128        check_frames(
129            "burn texture",
130            self.device.limits().max_texture_dimension_2d,
131            w,
132            h,
133            &[rgba8],
134        )?;
135        let src = upload_2d(&self.device, &self.queue, w, h, rgba8, false, "burn");
136        let pipe = self
137            .pipes
138            .burn
139            .get_or_init(|| BurnPipe::new(&self.device, &self.pipes.bgl_tex));
140        let verts = quad((self.cfg.width, self.cfg.height), rect);
141        let buf = self
142            .device
143            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
144                label: Some("burn verts"),
145                contents: bytemuck::cast_slice(&verts),
146                usage: wgpu::BufferUsages::VERTEX,
147            });
148        let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
149            label: Some("burn"),
150            layout: &self.pipes.bgl_tex,
151            entries: &[
152                wgpu::BindGroupEntry {
153                    binding: 0,
154                    resource: wgpu::BindingResource::TextureView(&src.view),
155                },
156                wgpu::BindGroupEntry {
157                    binding: 1,
158                    resource: wgpu::BindingResource::Sampler(self.pipes.sampler(
159                        Filter::Point,
160                        Address::Clamp,
161                        true,
162                    )),
163                },
164            ],
165        });
166        let mut encoder = self
167            .device
168            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
169                label: Some("burn"),
170            });
171        {
172            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
173                label: Some("burn"),
174                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
175                    view: &self.main[self.main_idx].view,
176                    depth_slice: None,
177                    resolve_target: None,
178                    ops: wgpu::Operations {
179                        load: wgpu::LoadOp::Load,
180                        store: wgpu::StoreOp::Store,
181                    },
182                })],
183                ..Default::default()
184            });
185            pass.set_pipeline(&pipe.pipeline);
186            pass.set_bind_group(0, &bg, &[]);
187            pass.set_vertex_buffer(0, buf.slice(..));
188            pass.draw(0..4, 0..1);
189        }
190        self.queue.submit([encoder.finish()]);
191        Ok(())
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::quad;
198
199    /// A burn at the origin covers the centred `width x height` rectangle of the target, `w` stays 1.
200    #[test]
201    fn origin_burn_scales_about_the_centre() {
202        let q = quad((100, 50), [0, 0, 50, 25]);
203        assert_eq!(q[0].clip, [-0.5, 0.5, 0.0, 1.0]);
204        assert_eq!(q[3].clip, [0.5, -0.5, 0.0, 1.0]);
205    }
206}