Skip to main content

lactea_render/renderer/
mod.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-FileCopyrightText: 2005-2013 Nullsoft, Inc.
3// SPDX-License-Identifier: (MIT OR Apache-2.0) AND BSD-3-Clause
4
5//! GPU side: resources, pipelines and the per-frame pass sequence.
6
7use crate::blur;
8use crate::config::{Compat, CompatRules, CompiledShader, RenderConfig, RenderError, StrokeRaster};
9use crate::frame::{FrameInput, ShapeImage};
10use crate::geom::{self, WarpVertex, WfVertex};
11use crate::motion::MotionVectorState;
12use crate::noise;
13use crate::rng::Rng;
14use crate::shader_ext::ShaderExt;
15use crate::shaders;
16use crate::sprite::{SpriteDraw, SpriteImage, SpritePipes};
17use crate::stroke::{self, LineRule};
18use crate::uniforms::{self, MilkUniformInputs, RotParams};
19use crate::warp_mesh::{self, MeshGeometry, VertexVars, WarpAnim};
20use crate::wavegen;
21use crate::wavegen_md3;
22use lactea_abi::dump::Stage;
23use lactea_abi::{
24    Address, BINDING_MILK_EXT, FFT_BINS, FRAGMENT_ENTRY, Filter, MeshVertex, MilkUniforms,
25    NoiseTex, PassUniforms, ShaderInterface, TexDim, TexSource,
26};
27use std::collections::HashMap;
28use wgpu::util::DeviceExt;
29
30mod burn;
31mod fixed;
32mod orchestrate;
33mod passes;
34mod pipelines;
35mod uv_readback;
36
37use pipelines::*;
38use uv_readback::UvReadback;
39
40const INTERNAL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
41
42// ---------------------------------------------------------------------------------------
43// small GPU helpers
44// ---------------------------------------------------------------------------------------
45
46#[derive(Clone)]
47struct Tex {
48    texture: wgpu::Texture,
49    view: wgpu::TextureView,
50    w: u32,
51    h: u32,
52}
53
54fn create_target(device: &wgpu::Device, w: u32, h: u32, label: &str) -> Tex {
55    let texture = device.create_texture(&wgpu::TextureDescriptor {
56        label: Some(label),
57        size: wgpu::Extent3d {
58            width: w,
59            height: h,
60            depth_or_array_layers: 1,
61        },
62        mip_level_count: 1,
63        sample_count: 1,
64        dimension: wgpu::TextureDimension::D2,
65        format: INTERNAL_FORMAT,
66        usage: wgpu::TextureUsages::RENDER_ATTACHMENT
67            | wgpu::TextureUsages::TEXTURE_BINDING
68            | wgpu::TextureUsages::COPY_SRC
69            | wgpu::TextureUsages::COPY_DST,
70        view_formats: &[],
71    });
72    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
73    Tex {
74        texture,
75        view,
76        w,
77        h,
78    }
79}
80
81/// `texCoords` of projectM's warp shader: `RG16F`.
82const WARP_SINK_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Float;
83
84fn create_sink(device: &wgpu::Device, w: u32, h: u32) -> Tex {
85    let texture = device.create_texture(&wgpu::TextureDescriptor {
86        label: Some("warp_sink"),
87        size: wgpu::Extent3d {
88            width: w,
89            height: h,
90            depth_or_array_layers: 1,
91        },
92        mip_level_count: 1,
93        sample_count: 1,
94        dimension: wgpu::TextureDimension::D2,
95        format: WARP_SINK_FORMAT,
96        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
97        view_formats: &[],
98    });
99    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
100    Tex {
101        texture,
102        view,
103        w,
104        h,
105    }
106}
107
108/// An empty `R32Float` texture, as the shader FFT and BeatDrop's wave textures are: zero until the first upload.
109/// `R32Float` is not filterable without `FLOAT32_FILTERABLE`; the translated shaders `textureLoad` it and blend the
110/// neighbouring texels by hand.
111fn create_r32f_tex(
112    device: &wgpu::Device,
113    queue: &wgpu::Queue,
114    label: &str,
115    w: usize,
116    h: usize,
117) -> Tex {
118    let texture = device.create_texture(&wgpu::TextureDescriptor {
119        label: Some(label),
120        size: wgpu::Extent3d {
121            width: w as u32,
122            height: h as u32,
123            depth_or_array_layers: 1,
124        },
125        mip_level_count: 1,
126        sample_count: 1,
127        dimension: wgpu::TextureDimension::D2,
128        format: wgpu::TextureFormat::R32Float,
129        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
130        view_formats: &[],
131    });
132    queue.write_texture(
133        wgpu::TexelCopyTextureInfo {
134            texture: &texture,
135            mip_level: 0,
136            origin: wgpu::Origin3d::ZERO,
137            aspect: wgpu::TextureAspect::All,
138        },
139        &vec![0u8; w * h * 4],
140        wgpu::TexelCopyBufferLayout {
141            offset: 0,
142            bytes_per_row: Some(w as u32 * 4),
143            rows_per_image: Some(h as u32),
144        },
145        wgpu::Extent3d {
146            width: w as u32,
147            height: h as u32,
148            depth_or_array_layers: 1,
149        },
150    );
151    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
152    Tex {
153        texture,
154        view,
155        w: w as u32,
156        h: h as u32,
157    }
158}
159
160/// CPU box-filter mip chain (D3D `AUTOGENMIPMAP` equivalent), level 0 included.
161fn mip_chain(data: &[u8], w: u32, h: u32) -> Vec<(Vec<u8>, u32, u32)> {
162    let mut levels = vec![(data.to_vec(), w, h)];
163    while levels.last().map(|l| l.1 > 1 || l.2 > 1).unwrap_or(false) {
164        let (src, sw, sh) = levels.last().unwrap();
165        let (dw, dh) = ((*sw / 2).max(1), (*sh / 2).max(1));
166        let mut dst = vec![0u8; (dw * dh * 4) as usize];
167        for y in 0..dh {
168            for x in 0..dw {
169                let x0 = (x * 2).min(sw - 1);
170                let x1 = (x * 2 + 1).min(sw - 1);
171                let y0 = (y * 2).min(sh - 1);
172                let y1 = (y * 2 + 1).min(sh - 1);
173                for c in 0..4 {
174                    let s = |xx: u32, yy: u32| src[((yy * sw + xx) * 4 + c) as usize] as u32;
175                    dst[((y * dw + x) * 4 + c) as usize] =
176                        ((s(x0, y0) + s(x1, y0) + s(x0, y1) + s(x1, y1) + 2) / 4) as u8;
177                }
178            }
179        }
180        levels.push((dst, dw, dh));
181    }
182    levels
183}
184
185fn upload_2d(
186    device: &wgpu::Device,
187    queue: &wgpu::Queue,
188    w: u32,
189    h: u32,
190    rgba: &[u8],
191    mips: bool,
192    label: &str,
193) -> Tex {
194    let levels = if mips {
195        mip_chain(rgba, w, h)
196    } else {
197        vec![(rgba.to_vec(), w, h)]
198    };
199    let texture = device.create_texture(&wgpu::TextureDescriptor {
200        label: Some(label),
201        size: wgpu::Extent3d {
202            width: w,
203            height: h,
204            depth_or_array_layers: 1,
205        },
206        mip_level_count: levels.len() as u32,
207        sample_count: 1,
208        dimension: wgpu::TextureDimension::D2,
209        format: INTERNAL_FORMAT,
210        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
211        view_formats: &[],
212    });
213    for (i, (data, lw, lh)) in levels.iter().enumerate() {
214        queue.write_texture(
215            wgpu::TexelCopyTextureInfo {
216                texture: &texture,
217                mip_level: i as u32,
218                origin: wgpu::Origin3d::ZERO,
219                aspect: wgpu::TextureAspect::All,
220            },
221            data,
222            wgpu::TexelCopyBufferLayout {
223                offset: 0,
224                bytes_per_row: Some(lw * 4),
225                rows_per_image: Some(*lh),
226            },
227            wgpu::Extent3d {
228                width: *lw,
229                height: *lh,
230                depth_or_array_layers: 1,
231            },
232        );
233    }
234    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
235    Tex {
236        texture,
237        view,
238        w,
239        h,
240    }
241}
242
243fn upload_3d(device: &wgpu::Device, queue: &wgpu::Queue, n: u32, rgba: &[u8], label: &str) -> Tex {
244    let texture = device.create_texture(&wgpu::TextureDescriptor {
245        label: Some(label),
246        size: wgpu::Extent3d {
247            width: n,
248            height: n,
249            depth_or_array_layers: n,
250        },
251        mip_level_count: 1,
252        sample_count: 1,
253        dimension: wgpu::TextureDimension::D3,
254        format: INTERNAL_FORMAT,
255        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
256        view_formats: &[],
257    });
258    queue.write_texture(
259        wgpu::TexelCopyTextureInfo {
260            texture: &texture,
261            mip_level: 0,
262            origin: wgpu::Origin3d::ZERO,
263            aspect: wgpu::TextureAspect::All,
264        },
265        rgba,
266        wgpu::TexelCopyBufferLayout {
267            offset: 0,
268            bytes_per_row: Some(n * 4),
269            rows_per_image: Some(n),
270        },
271        wgpu::Extent3d {
272            width: n,
273            height: n,
274            depth_or_array_layers: n,
275        },
276    );
277    let view = texture.create_view(&wgpu::TextureViewDescriptor {
278        dimension: Some(wgpu::TextureViewDimension::D3),
279        ..Default::default()
280    });
281    Tex {
282        texture,
283        view,
284        w: n,
285        h: n,
286    }
287}
288
289/// `frames` must be a non-empty list of `w * h * 4` byte images of a non-empty size that fits the device's
290/// largest 2D texture (`max_side`).
291fn check_frames(
292    what: &str,
293    max_side: u32,
294    w: u32,
295    h: u32,
296    frames: &[&[u8]],
297) -> Result<(), RenderError> {
298    if w > max_side || h > max_side {
299        return Err(RenderError::Invalid(format!(
300            "{what}: {w}x{h} exceeds the device texture limit of {max_side}"
301        )));
302    }
303    let need = w as usize * h as usize * 4;
304    if w == 0 || h == 0 || frames.is_empty() || frames.iter().any(|f| f.len() != need) {
305        return Err(RenderError::Invalid(format!(
306            "{what}: {} frame(s) of {w}x{h} need {need} bytes each",
307            frames.len()
308        )));
309    }
310    Ok(())
311}
312
313fn buffer_init<T: bytemuck::Pod>(
314    device: &wgpu::Device,
315    label: &str,
316    data: &[T],
317    usage: wgpu::BufferUsages,
318) -> wgpu::Buffer {
319    let bytes: &[u8] = bytemuck::cast_slice(data);
320    if bytes.is_empty() {
321        // zero-sized buffers are awkward; hand out a 16-byte dummy
322        return device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
323            label: Some(label),
324            contents: &[0u8; 16],
325            usage,
326        });
327    }
328    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
329        label: Some(label),
330        contents: bytes,
331        usage,
332    })
333}
334
335// ---------------------------------------------------------------------------------------
336// blend modes / pipeline set
337// ---------------------------------------------------------------------------------------
338
339use crate::blend::{self, Which};
340/// A blur pass's uniform values and the bind group built from them.
341type BlurBindGroup = ([[f32; 4]; 6], wgpu::BindGroup);
342
343#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
344enum Blend {
345    /// D3DRS_ALPHABLENDENABLE = FALSE (or ONE/ZERO)
346    Replace,
347    /// ONE / ONE
348    Add,
349    /// SRCALPHA / INVSRCALPHA
350    SrcAlpha,
351    /// INVSRCALPHA / SRCALPHA (`bFlipAlpha` of MD2's preset blend)
352    InvSrcAlpha,
353    /// SRCALPHA / ONE
354    SrcAlphaAdd,
355    /// INVDESTCOLOR / ZERO
356    InvDstZero,
357    /// ZERO / DESTCOLOR
358    ZeroDst,
359    /// ZERO / INVDESTCOLOR
360    ZeroInvDst,
361    /// DESTCOLOR / ONE
362    DstOne,
363}
364
365impl Blend {
366    /// Every variant: the pipeline maps are keyed over this, so a new mode gets its pipelines
367    /// without a second list. `blend_state` is the exhaustive match that forces a new arm.
368    const ALL: [Blend; 9] = [
369        Blend::Replace,
370        Blend::Add,
371        Blend::SrcAlpha,
372        Blend::InvSrcAlpha,
373        Blend::SrcAlphaAdd,
374        Blend::InvDstZero,
375        Blend::ZeroDst,
376        Blend::ZeroInvDst,
377        Blend::DstOne,
378    ];
379}
380
381fn blend_state(b: Blend) -> Option<wgpu::BlendState> {
382    use wgpu::BlendFactor as F;
383    let (s, d) = match b {
384        Blend::Replace => return None,
385        Blend::Add => (F::One, F::One),
386        Blend::SrcAlpha => (F::SrcAlpha, F::OneMinusSrcAlpha),
387        Blend::InvSrcAlpha => (F::OneMinusSrcAlpha, F::SrcAlpha),
388        Blend::SrcAlphaAdd => (F::SrcAlpha, F::One),
389        Blend::InvDstZero => (F::OneMinusDst, F::Zero),
390        Blend::ZeroDst => (F::Zero, F::Dst),
391        Blend::ZeroInvDst => (F::Zero, F::OneMinusDst),
392        Blend::DstOne => (F::Dst, F::One),
393    };
394    let c = wgpu::BlendComponent {
395        src_factor: s,
396        dst_factor: d,
397        operation: wgpu::BlendOperation::Add,
398    };
399    Some(wgpu::BlendState { color: c, alpha: c })
400}
401
402#[derive(Clone, Copy, Debug, PartialEq, Eq)]
403enum Kind {
404    Flat,
405    Tex,
406    /// A textured draw that samples the main image with the leftover blur sampler (linear, clamp), see
407    /// `Renderer::build_overlay`.
408    TexLeak,
409    /// A textured draw that samples a shape's `image=` user texture (index into `Batch::images`).
410    TexImage(u32),
411}
412
413/// Primitive topology of a flat-colour draw.
414#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
415enum Prim {
416    /// `TriangleList`
417    Tri,
418    /// `LineList` (pairs of vertices, vertex colours interpolate along the line)
419    Line,
420    /// `PointList` (1 px)
421    Point,
422}
423
424#[derive(Default)]
425struct Batch {
426    wf: Vec<WfVertex>,
427    mesh: Vec<MeshVertex>,
428    cmds: Vec<(Kind, Blend, Prim, u32, u32)>,
429    /// Textures of [`Kind::TexImage`] commands (one entry per command).
430    images: Vec<ShapeImage>,
431    /// Command indices after the custom shapes / after the custom waves: where sprite layers 2 and 3 go.
432    marks: [usize; 2],
433    /// Commands before this index never merge with later ones (a sprite layer may be drawn in between).
434    barrier: usize,
435}
436
437impl Batch {
438    fn flat(&mut self, blend: Blend, verts: &[WfVertex]) {
439        self.flat_prim(Prim::Tri, blend, verts);
440    }
441    fn flat_prim(&mut self, prim: Prim, blend: Blend, verts: &[WfVertex]) {
442        if verts.is_empty() {
443            return;
444        }
445        let start = self.wf.len() as u32;
446        self.wf.extend_from_slice(verts);
447        if self.cmds.len() > self.barrier
448            && let Some(last) = self.cmds.last_mut()
449            && last.0 == Kind::Flat
450            && last.1 == blend
451            && last.2 == prim
452            && last.3 + last.4 == start
453        {
454            last.4 += verts.len() as u32;
455            return;
456        }
457        self.cmds
458            .push((Kind::Flat, blend, prim, start, verts.len() as u32));
459    }
460    fn tex(&mut self, blend: Blend, verts: &[MeshVertex]) {
461        if verts.is_empty() {
462            return;
463        }
464        let start = self.mesh.len() as u32;
465        self.mesh.extend_from_slice(verts);
466        if self.cmds.len() > self.barrier
467            && let Some(last) = self.cmds.last_mut()
468            && last.0 == Kind::Tex
469            && last.1 == blend
470            && last.3 + last.4 == start
471        {
472            last.4 += verts.len() as u32;
473            return;
474        }
475        self.cmds
476            .push((Kind::Tex, blend, Prim::Tri, start, verts.len() as u32));
477    }
478    fn tex_leak(&mut self, blend: Blend, verts: &[MeshVertex]) {
479        if verts.is_empty() {
480            return;
481        }
482        let start = self.mesh.len() as u32;
483        self.mesh.extend_from_slice(verts);
484        self.cmds
485            .push((Kind::TexLeak, blend, Prim::Tri, start, verts.len() as u32));
486    }
487    /// A textured fill that samples the user texture of a shape's `image=` key.
488    fn tex_image(&mut self, blend: Blend, verts: &[MeshVertex], image: &ShapeImage) {
489        if verts.is_empty() {
490            return;
491        }
492        let start = self.mesh.len() as u32;
493        self.mesh.extend_from_slice(verts);
494        let id = self.images.len() as u32;
495        self.images.push(ShapeImage {
496            name: image.name.to_ascii_lowercase(),
497            ..image.clone()
498        });
499        self.cmds.push((
500            Kind::TexImage(id),
501            blend,
502            Prim::Tri,
503            start,
504            verts.len() as u32,
505        ));
506    }
507    /// Let `fill` append vertices of `prim` to the flat-vertex buffer and record them as one command (merged with the
508    /// previous one when it is compatible), without an intermediate buffer.
509    fn flat_extend(&mut self, prim: Prim, blend: Blend, fill: impl FnOnce(&mut Vec<WfVertex>)) {
510        let start = self.wf.len() as u32;
511        fill(&mut self.wf);
512        let count = self.wf.len() as u32 - start;
513        if count == 0 {
514            return;
515        }
516        if self.cmds.len() > self.barrier
517            && let Some(last) = self.cmds.last_mut()
518            && last.0 == Kind::Flat
519            && last.1 == blend
520            && last.2 == prim
521            && last.3 + last.4 == start
522        {
523            last.4 += count;
524            return;
525        }
526        self.cmds.push((Kind::Flat, blend, prim, start, count));
527    }
528    /// 1-pixel line segments: `segs` holds pairs of vertices (clip space, per-vertex colour); `rule` picks the
529    /// GL line rule (see `stroke.rs`).
530    fn segments(
531        &mut self,
532        mode: StrokeRaster,
533        rule: LineRule,
534        blend: Blend,
535        w: f32,
536        h: f32,
537        segs: &[WfVertex],
538    ) {
539        match mode {
540            StrokeRaster::Native => self.flat_prim(Prim::Line, blend, segs),
541            StrokeRaster::Emulated => self.flat_extend(Prim::Point, blend, |out| {
542                stroke::raster_segments(segs, w as u32, h as u32, rule, out);
543            }),
544            StrokeRaster::Quads => self.flat_extend(Prim::Tri, blend, |out| {
545                for s in segs.as_chunks::<2>().0 {
546                    geom::push_line(out, s[0].pos, s[1].pos, w, h, s[0].color);
547                }
548            }),
549        }
550    }
551    /// Points of `size` pixels (`size == 1` is a 1-px GL point; larger sizes are D3D9 point sprites = quads).
552    fn points(
553        &mut self,
554        mode: StrokeRaster,
555        blend: Blend,
556        w: f32,
557        h: f32,
558        pts: &[WfVertex],
559        size: f32,
560    ) {
561        match mode {
562            StrokeRaster::Native if size <= 1.0 => self.flat_prim(Prim::Point, blend, pts),
563            StrokeRaster::Emulated if size <= 1.0 => self.flat_extend(Prim::Point, blend, |out| {
564                stroke::raster_points(pts, w as u32, h as u32, out);
565            }),
566            _ => self.flat_extend(Prim::Tri, blend, |out| {
567                for p in pts {
568                    geom::push_point(out, p.pos, size, w, h, p.color);
569                }
570            }),
571        }
572    }
573    /// Remember the current end of the command list as sprite split `which` (0 = after the custom shapes, 1 = after
574    /// the custom waves).
575    fn mark(&mut self, which: usize) {
576        self.marks[which] = self.cmds.len();
577        self.barrier = self.cmds.len();
578    }
579    fn is_empty(&self) -> bool {
580        self.cmds.is_empty()
581    }
582}
583
584struct Pipelines {
585    bgl_tex: wgpu::BindGroupLayout,
586    bgl_warp_vs: wgpu::BindGroupLayout,
587    /// projectM warp vertex stage + fixed-function fragment, keyed by `main_alpha`
588    warp_tex: HashMap<bool, wgpu::RenderPipeline>,
589    warp_uv_readback: wgpu::RenderPipeline,
590    bgl_blur: wgpu::BindGroupLayout,
591    bgl_blit: wgpu::BindGroupLayout,
592    bgl_mu: wgpu::BindGroupLayout,
593    /// keyed by (blend, alpha): `alpha` = projectM RGBA semantics (alpha written, `tex.a` modulates)
594    tex: HashMap<(Blend, bool), wgpu::RenderPipeline>,
595    flat: HashMap<(Blend, Prim, bool), wgpu::RenderPipeline>,
596    blur_h: wgpu::RenderPipeline,
597    blur_v: wgpu::RenderPipeline,
598    blit: wgpu::RenderPipeline,
599    mesh_vs: wgpu::ShaderModule,
600    /// `[linear wrap, linear clamp, point wrap, point clamp]` with mips, then the same four limited to level 0
601    samplers: [wgpu::Sampler; 8],
602    /// MD3 sprite pipelines, built when the first sprite image is registered.
603    sprite: std::sync::OnceLock<SpritePipes>,
604    /// The `burn_texture` copy pipeline, built on first use.
605    burn: std::sync::OnceLock<burn::BurnPipe>,
606    /// Sprite pipelines for the host's output format when it is not the internal one.
607    sprite_out: std::sync::OnceLock<SpritePipes>,
608}
609
610/// Uniforms of [`shaders::warp_vs`] (projectM's warp vertex shader).
611#[repr(C)]
612#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
613struct WarpVsUniforms {
614    /// `aspectX, aspectY, invAspectX, invAspectY`
615    aspect: [f32; 4],
616    /// `warpTime, warpScaleInverse, texelOffset.x, texelOffset.y`
617    timing: [f32; 4],
618    /// `warpFactors`
619    factors: [f32; 4],
620    /// `frag_COLOR` (`decay`, or 1)
621    diffuse: [f32; 4],
622}
623
624struct ShaderPass {
625    pipeline: wgpu::RenderPipeline,
626    /// Warp shaders only: the same fragment stage behind projectM's warp vertex shader ([`shaders::warp_vs`]).
627    warp_pipeline: Option<wgpu::RenderPipeline>,
628    pass_bgl: wgpu::BindGroupLayout,
629    interface: ShaderInterface,
630    /// Warp shaders: the fragment stage returns the interpolated UV as a second output ([`with_uv_output`]).
631    uv_sink: bool,
632    /// `CompatRules::md2_preset_blend` only: the same fragment stage with MD2's blend-pass alpha blending, keyed
633    /// `[SRCALPHA / INVSRCALPHA, INVSRCALPHA / SRCALPHA]` (`bFlipAlpha`), mesh vertices.
634    alpha_pipelines: Option<[wgpu::RenderPipeline; 2]>,
635}
636
637/// Vertex data of a user-shader pass: the generic mesh vertex, or projectM's warp mesh vertex (GPU UV
638/// evaluation) with the uniforms of its vertex stage.
639enum PassVerts<'a> {
640    Mesh(&'a [MeshVertex]),
641    Warp(&'a [WarpVertex], &'a WarpVsUniforms),
642}
643
644struct UserTex {
645    /// The texture (the first frame of an animation).
646    tex: Tex,
647    anim: Option<UserAnim>,
648}
649
650/// An animated GIF used as a shader texture (MD3): the frame shown is picked by the time of the frame.
651struct UserAnim {
652    /// Never empty.
653    frames: Vec<Tex>,
654    /// Seconds per frame, same length as `frames`.
655    delays: Vec<f64>,
656}
657
658impl UserTex {
659    fn view_at(&self, time: f64) -> &wgpu::TextureView {
660        match &self.anim {
661            Some(a) => &a.frames[crate::sprite::gif_frame_index(&a.delays, time)].view,
662            None => &self.tex.view,
663        }
664    }
665}
666
667/// The shader-side state of one preset: its warp / composite pass and the user textures their samplers read (MD2's
668/// `m_shaders`, and `m_OldShaders` during a blend).
669struct ShaderSet {
670    warp: Option<ShaderPass>,
671    comp: Option<ShaderPass>,
672    user_tex: HashMap<String, UserTex>,
673}
674
675/// A preset's installed shaders and textures, detached from the renderer ([`Renderer::take_shader_state`]).
676pub struct ShaderState(ShaderSet);
677
678/// How a user-shader pass writes its target ([`Renderer::run_shader_pass`]).
679#[derive(Clone, Copy, Debug, PartialEq, Eq)]
680enum PassBlend {
681    /// Clear the target, opaque draw.
682    Replace,
683    /// Keep the target, `SRCALPHA / INVSRCALPHA`.
684    SrcAlpha,
685    /// Keep the target, `INVSRCALPHA / SRCALPHA`.
686    InvSrcAlpha,
687}
688
689/// Row pitch of a buffer copy of `row_bytes` bytes per row (wgpu requires multiples of 256).
690fn padded_bytes_per_row(row_bytes: u32) -> u32 {
691    row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
692}
693
694/// Read an `Rgba8Unorm`-sized (4 bytes per texel) `w` x `h` texture back as tightly packed RGBA8 (row 0 = top).
695/// Submits its own copy and waits for it, so the frame's command buffers must have been submitted.
696pub fn readback_rgba8(
697    device: &wgpu::Device,
698    queue: &wgpu::Queue,
699    texture: &wgpu::Texture,
700    w: u32,
701    h: u32,
702) -> Result<Vec<u8>, RenderError> {
703    let bpr = padded_bytes_per_row(w * 4);
704    let buf = device.create_buffer(&wgpu::BufferDescriptor {
705        label: Some("readback"),
706        size: u64::from(bpr) * u64::from(h),
707        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
708        mapped_at_creation: false,
709    });
710    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
711        label: Some("readback"),
712    });
713    enc.copy_texture_to_buffer(
714        wgpu::TexelCopyTextureInfo {
715            texture,
716            mip_level: 0,
717            origin: wgpu::Origin3d::ZERO,
718            aspect: wgpu::TextureAspect::All,
719        },
720        wgpu::TexelCopyBufferInfo {
721            buffer: &buf,
722            layout: wgpu::TexelCopyBufferLayout {
723                offset: 0,
724                bytes_per_row: Some(bpr),
725                rows_per_image: Some(h),
726            },
727        },
728        wgpu::Extent3d {
729            width: w,
730            height: h,
731            depth_or_array_layers: 1,
732        },
733    );
734    queue.submit(Some(enc.finish()));
735    let slice = buf.slice(..);
736    let (tx, rx) = std::sync::mpsc::channel();
737    slice.map_async(wgpu::MapMode::Read, move |r| {
738        let _ = tx.send(r);
739    });
740    device
741        .poll(wgpu::PollType::wait_indefinitely())
742        .map_err(|e| RenderError::Readback(format!("{e:?}")))?;
743    rx.recv()
744        .map_err(|e| RenderError::Readback(e.to_string()))?
745        .map_err(|e| RenderError::Readback(e.to_string()))?;
746    let data = slice
747        .get_mapped_range()
748        .map_err(|e| RenderError::Readback(e.to_string()))?;
749    let row = w as usize * 4;
750    let mut out = Vec::with_capacity(row * h as usize);
751    for y in 0..h {
752        let s = y as usize * bpr as usize;
753        out.extend_from_slice(&data[s..s + row]);
754    }
755    drop(data);
756    buf.unmap();
757    Ok(out)
758}
759
760/// Index buffer of the GPU warp mesh ([`geom::warp_gpu_indices`]) and its index count; only projectM's rules draw it.
761/// Constant for a mesh size, so built when the mesh changes rather than every frame.
762fn warp_index_buffer(
763    device: &wgpu::Device,
764    geom: &MeshGeometry,
765    rules: &CompatRules,
766) -> Option<(wgpu::Buffer, u32)> {
767    if !rules.warp_uv_on_gpu {
768        return None;
769    }
770    let idx = geom::warp_gpu_indices(geom, rules.warp_diag_flipped);
771    let buf = buffer_init(device, "warp indices", &idx, wgpu::BufferUsages::INDEX);
772    Some((buf, idx.len() as u32))
773}
774
775/// Check a render size against zero and the device's 2D texture limit.
776fn check_size(device: &wgpu::Device, width: u32, height: u32) -> Result<(), RenderError> {
777    if width == 0 || height == 0 {
778        return Err(RenderError::Invalid(format!(
779            "render size must be non-zero, got {width}x{height}"
780        )));
781    }
782    let max = device.limits().max_texture_dimension_2d;
783    if width > max || height > max {
784        return Err(RenderError::Invalid(format!(
785            "render size {width}x{height} exceeds the device texture limit of {max}"
786        )));
787    }
788    Ok(())
789}
790
791/// The mesh geometry of `cfg`, after checking that its size and mesh are usable.
792fn checked_geometry(
793    device: &wgpu::Device,
794    cfg: &RenderConfig,
795) -> Result<MeshGeometry, RenderError> {
796    check_size(device, cfg.width, cfg.height)?;
797    MeshGeometry::new(cfg.mesh[0], cfg.mesh[1], cfg.width, cfg.height)
798}
799
800// ---------------------------------------------------------------------------------------
801// Renderer
802// ---------------------------------------------------------------------------------------
803
804/// The MilkDrop 2 frame renderer. See the crate docs for the pass order.
805pub struct Renderer {
806    device: wgpu::Device,
807    queue: wgpu::Queue,
808    cfg: RenderConfig,
809    rules: CompatRules,
810    geom: MeshGeometry,
811    /// Triangles of the GPU warp mesh over the unique vertices of [`geom::build_warp_gpu_vertices`].
812    warp_indices: Option<(wgpu::Buffer, u32)>,
813    /// See [`Renderer::blit`].
814    blit_bg: std::cell::RefCell<Option<wgpu::BindGroup>>,
815    /// Bind groups of blur passes 1.. keyed by their uniform values (see `Renderer::run_blur`); dropped on `resize`.
816    blur_bg: std::cell::RefCell<Vec<Option<BlurBindGroup>>>,
817    rot: RotParams,
818    pipes: std::sync::Arc<Pipelines>,
819    /// `m_lpVS[0..2]` ping-pong; `main[main_idx]` holds the latest `main` image.
820    main: [Tex; 2],
821    main_idx: usize,
822    warped: Tex,
823    final_tex: Tex,
824    blur: Vec<Tex>,
825    noise: Vec<Tex>,
826    user_tex: HashMap<String, UserTex>,
827    /// MD3 sprite images by id ([`Renderer::set_sprite_image`]).
828    sprite_images: HashMap<u32, SpriteImage>,
829    /// Time of the frame being recorded: animated textures pick their frame from it.
830    anim_time: f64,
831    dummy_2d: Tex,
832    dummy_3d: Tex,
833    /// `sampler_fft` ([`TexSource::Fft`]): the smoothed MilkDrop 3 shader FFT (512 x 1), or under
834    /// `CompatRules::md2_shader_inputs` BeatDrop's `m_lpFFTTexture` (1024 x 2: spectrum, peak hold). Owned per renderer
835    /// (a [`Renderer::sibling`] has its own) and replaced whenever a frame carries `FrameInput::ext.fft` /
836    /// `FrameInput::ext.beatdrop`.
837    fft: Tex,
838    /// BeatDrop's `m_lpWaveTexture` (480 x 2: left, right), only under `CompatRules::md2_shader_inputs`. The
839    /// translator names it by the user texture `"wave"` (the frozen ABI has no source for it): see
840    /// [`Renderer::engine_wave`].
841    wave: Option<Tex>,
842    /// Scratch attachment for the user warp shader's second output ([`with_uv_output`]); never read.
843    warp_sink: Tex,
844    warp_shader: Option<ShaderPass>,
845    comp_shader: Option<ShaderPass>,
846    /// MD2's `m_OldShaders` (+ the old preset's textures): the old preset's shaders while a preset blend runs.
847    old_shaders: Option<ShaderSet>,
848    /// Warp UV grid of the previous frame (motion vector reverse propagation).
849    prev_warp_uv: Option<Vec<[f32; 2]>>,
850    /// The previous frame's warp vertex-shader inputs, to evaluate its UVs on the GPU (motion vector lookups).
851    prev_warp_gpu: Option<crate::frame::WarpGpu>,
852    /// Persistent readback of the GPU's warp UVs ([`Renderer::gpu_warp_vertex_uv`]).
853    uv_readback: Option<UvReadback>,
854    /// projectM's motion vector mesh (stale vertices, index count).
855    mv_state: MotionVectorState,
856    frames_since_resize: u32,
857    /// projectM's persistent main-wave buffer tail (see [`wavegen::PmWaveTail`]); zero at preset load.
858    main_wave_tail: wavegen::PmWaveTail,
859    /// Working buffers of the per-frame geometry builders.
860    scratch: FrameScratch,
861    /// Highest blur level used by the last rendered frame's shaders (for tests / diagnostics).
862    last_blur_levels: u8,
863    /// Minimum blur level computed every frame ([`Renderer::set_min_blur_levels`]).
864    #[cfg(feature = "diagnostics")]
865    min_blur_levels: u8,
866    /// One-shot override of the composite `sampler_main` ([`Renderer::inject_comp_source`]).
867    #[cfg(feature = "diagnostics")]
868    comp_source_override: Option<Tex>,
869}
870
871/// Hooks for comparing against a reference render (feature `diagnostics`): replacing internal images, forcing
872/// per-frame state and reading intermediate images back.
873#[cfg(feature = "diagnostics")]
874impl Renderer {
875    /// Replace a built-in noise texture (e.g. with a reference render's noise). 2D: `size*size*4` bytes,
876    /// row 0 first; volumes: `size^3*4`, slice-major. Sizes are MD2's (see [`crate::noise::noise_spec`]).
877    pub fn inject_noise(&mut self, which: NoiseTex, data: &[u8]) -> Result<(), RenderError> {
878        let (size, _, vol) = noise::noise_spec(which);
879        let expect = if vol {
880            (size * size * size * 4) as usize
881        } else {
882            (size * size * 4) as usize
883        };
884        if data.len() != expect {
885            return Err(RenderError::Invalid(format!(
886                "{which:?}: expected {expect} bytes, got {}",
887                data.len()
888            )));
889        }
890        self.noise[which.index()] = if vol {
891            upload_3d(&self.device, &self.queue, size, data, "noise_vol")
892        } else {
893            upload_2d(&self.device, &self.queue, size, size, data, true, "noise")
894        };
895        Ok(())
896    }
897
898    /// Replace the previous-frame image (`main`, what the next warp samples).
899    pub fn inject_main(&mut self, rgba8: &[u8]) -> Result<(), RenderError> {
900        let t = &self.main[self.main_idx];
901        self.write_rgba8(t, rgba8, "inject_main")
902    }
903
904    /// Use `rgba8` as the composite source (a comp shader's `sampler_main`, or the no-shader composite's
905    /// texture) for the next rendered frame only. Does not touch the stored `main` image, so the `main` stage
906    /// read-back stays the renderer's own.
907    pub fn inject_comp_source(&mut self, rgba8: &[u8]) -> Result<(), RenderError> {
908        let (w, h) = (self.cfg.width, self.cfg.height);
909        let t = create_target(&self.device, w, h, "comp source override");
910        self.write_rgba8(&t, rgba8, "inject_comp_source")?;
911        self.comp_source_override = Some(t);
912        Ok(())
913    }
914
915    /// Make the next frame's motion-vector pass use this warp UV grid (the previous frame's UVs).
916    pub fn inject_prev_warp_uv(&mut self, uv: Option<Vec<[f32; 2]>>) {
917        self.prev_warp_uv = uv;
918    }
919
920    /// The image the last frame's warp pass sampled (previous `main` + this frame's motion vectors).
921    /// Valid until the next `render_frame`.
922    pub fn read_warp_source(&self) -> Result<(u32, u32, Vec<u8>), RenderError> {
923        self.read_texture(&self.main[1 - self.main_idx])
924    }
925
926    /// Compute at least `levels` (0..=3) blur levels every frame even if no shader samples them, so
927    /// `Stage::Blur1..3` can be read back.
928    pub fn set_min_blur_levels(&mut self, levels: u8) {
929        self.min_blur_levels = levels.min(3);
930    }
931
932    /// Per-preset random parameters (rotation matrices, hue offsets).
933    pub fn rot_params(&self) -> &RotParams {
934        &self.rot
935    }
936
937    /// Replace the per-preset random parameters (they otherwise stay as drawn from the seed).
938    pub fn set_rot_params(&mut self, p: RotParams) {
939        self.rot = p;
940    }
941
942    /// Upload a full-size RGBA8 image (row 0 = top) into `t`.
943    fn write_rgba8(&self, t: &Tex, rgba8: &[u8], what: &str) -> Result<(), RenderError> {
944        let need = t.w as usize * t.h as usize * 4;
945        if rgba8.len() != need {
946            return Err(RenderError::Invalid(format!(
947                "{what}: need {need} bytes, got {}",
948                rgba8.len()
949            )));
950        }
951        self.queue.write_texture(
952            wgpu::TexelCopyTextureInfo {
953                texture: &t.texture,
954                mip_level: 0,
955                origin: wgpu::Origin3d::ZERO,
956                aspect: wgpu::TextureAspect::All,
957            },
958            rgba8,
959            wgpu::TexelCopyBufferLayout {
960                offset: 0,
961                bytes_per_row: Some(t.w * 4),
962                rows_per_image: Some(t.h),
963            },
964            wgpu::Extent3d {
965                width: t.w,
966                height: t.h,
967                depth_or_array_layers: 1,
968            },
969        );
970        Ok(())
971    }
972}
973
974impl Renderer {
975    /// Create a renderer. Textures are cleared to black; noise textures are generated from
976    /// `cfg.seed` (MD2 algorithm). `device`/`queue` are cloned handles (cheap).
977    ///
978    /// # Errors
979    ///
980    /// [`RenderError::Invalid`] if the size is zero or the mesh is not an even grid of at least 2x2 cells.
981    pub fn new(
982        device: &wgpu::Device,
983        queue: &wgpu::Queue,
984        cfg: RenderConfig,
985    ) -> Result<Self, RenderError> {
986        let geom = checked_geometry(device, &cfg)?;
987        let pipes = std::sync::Arc::new(Pipelines::new(device, cfg.output_format));
988        Ok(Self::assemble(device, queue, cfg, geom, pipes, None))
989    }
990
991    /// A second renderer with the same configuration that shares this one's pipelines and
992    /// (immutable) noise textures but has its own images, shaders and user textures: what the
993    /// engine needs to run two presets at once while they transition. Cheaper than
994    /// [`Renderer::new`] (no pipeline compilation, no noise generation), but it still allocates the render targets.
995    pub fn sibling(&self) -> Self {
996        self.sibling_with_compat(self.cfg.compat)
997    }
998
999    /// [`Renderer::sibling`] that follows another compatibility mode: same size, mesh, stroke setting, shared
1000    /// pipelines and noise (neither depends on the mode), but its own images, shaders and textures, and the rules of
1001    /// `compat`. What the engine builds into when an automatically selected mode changes.
1002    pub fn sibling_with_compat(&self, compat: Compat) -> Self {
1003        let mut cfg = self.cfg.clone();
1004        cfg.compat = compat;
1005        let mut r = Self::assemble(
1006            &self.device,
1007            &self.queue,
1008            cfg,
1009            self.geom.clone(),
1010            std::sync::Arc::clone(&self.pipes),
1011            Some(self.noise.clone()),
1012        );
1013        #[cfg(feature = "diagnostics")]
1014        {
1015            r.min_blur_levels = self.min_blur_levels;
1016        }
1017        r.rot = self.rot.clone();
1018        r
1019    }
1020
1021    fn assemble(
1022        device: &wgpu::Device,
1023        queue: &wgpu::Queue,
1024        cfg: RenderConfig,
1025        geom: MeshGeometry,
1026        pipes: std::sync::Arc<Pipelines>,
1027        shared_noise: Option<Vec<Tex>>,
1028    ) -> Self {
1029        let rules = cfg.compat.rules();
1030
1031        let (w, h) = (cfg.width, cfg.height);
1032        let main = [
1033            create_target(device, w, h, "main0"),
1034            create_target(device, w, h, "main1"),
1035        ];
1036        let warped = create_target(device, w, h, "warped");
1037        let final_tex = create_target(device, w, h, "final");
1038        let blur = blur::blur_tex_sizes(w, h)
1039            .iter()
1040            .enumerate()
1041            .map(|(i, &(bw, bh))| create_target(device, bw, bh, &format!("blur{i}")))
1042            .collect();
1043
1044        let rng = Rng::new(cfg.seed);
1045        let noise_tex = match shared_noise {
1046            Some(n) => n,
1047            None => {
1048                let mut noise_rng = rng.fork(0x6E6F_6973);
1049                let mut noise_tex = Vec::new();
1050                for t in noise::ALL_NOISE {
1051                    let data = noise::generate(t, &mut noise_rng, &rules);
1052                    let (size, _, vol) = noise::noise_spec(t);
1053                    noise_tex.push(if vol {
1054                        upload_3d(device, queue, size, &data, "noise_vol")
1055                    } else {
1056                        upload_2d(device, queue, size, size, &data, true, "noise")
1057                    });
1058                }
1059                noise_tex
1060            }
1061        };
1062        let rot = RotParams::randomize(&mut rng.fork(0x7072_6573));
1063        let dummy_2d = upload_2d(device, queue, 1, 1, &[0, 0, 0, 255], false, "dummy2d");
1064        let dummy_3d = upload_3d(device, queue, 1, &[0, 0, 0, 255], "dummy3d");
1065        let (fft_w, fft_h) = if rules.md2_shader_inputs {
1066            (crate::BEATDROP_FFT_BINS, 2)
1067        } else {
1068            (FFT_BINS, 1)
1069        };
1070        let fft = create_r32f_tex(device, queue, "fft", fft_w, fft_h);
1071        let wave = rules
1072            .md2_shader_inputs
1073            .then(|| create_r32f_tex(device, queue, "wave", crate::BEATDROP_WAVE_SAMPLES, 2));
1074
1075        let warp_indices = warp_index_buffer(device, &geom, &rules);
1076        let r = Renderer {
1077            device: device.clone(),
1078            queue: queue.clone(),
1079            cfg,
1080            rules,
1081            geom,
1082            warp_indices,
1083            blit_bg: Default::default(),
1084            blur_bg: Default::default(),
1085            rot,
1086            pipes,
1087            main,
1088            main_idx: 0,
1089            warped,
1090            final_tex,
1091            blur,
1092            noise: noise_tex,
1093            user_tex: HashMap::new(),
1094            sprite_images: HashMap::new(),
1095            anim_time: 0.0,
1096            dummy_2d,
1097            dummy_3d,
1098            fft,
1099            wave,
1100            warp_sink: create_sink(device, w, h),
1101            warp_shader: None,
1102            comp_shader: None,
1103            old_shaders: None,
1104            prev_warp_uv: None,
1105            prev_warp_gpu: None,
1106            uv_readback: None,
1107            mv_state: MotionVectorState::default(),
1108            frames_since_resize: 0,
1109            main_wave_tail: Default::default(),
1110            scratch: FrameScratch::default(),
1111            last_blur_levels: 0,
1112            #[cfg(feature = "diagnostics")]
1113            min_blur_levels: 0,
1114            #[cfg(feature = "diagnostics")]
1115            comp_source_override: None,
1116        };
1117        r.clear_all();
1118        r
1119    }
1120
1121    // ---- configuration ----------------------------------------------------------------
1122
1123    /// The configuration in use (size and mesh follow [`Renderer::resize`] / [`Renderer::set_mesh_size`]).
1124    pub fn config(&self) -> &RenderConfig {
1125        &self.cfg
1126    }
1127
1128    /// The warp-mesh geometry (vertex positions, `rad`, `ang`) — what the engine needs to run per-pixel code.
1129    pub fn mesh_geometry(&self) -> &MeshGeometry {
1130        &self.geom
1131    }
1132
1133    /// The reference behaviour followed where MilkDrop 2 and projectM differ.
1134    pub fn compat(&self) -> Compat {
1135        self.cfg.compat
1136    }
1137
1138    /// The rasteriser actually used for lines and points: the configured one, except that
1139    /// `Compat::MilkDrop2` / `Compat::MilkDrop3` always draw D3D9-style thin quads.
1140    pub fn stroke_raster(&self) -> StrokeRaster {
1141        self.stroke_mode()
1142    }
1143
1144    fn stroke_mode(&self) -> StrokeRaster {
1145        if self.rules.gl_strokes {
1146            self.cfg.stroke
1147        } else {
1148            StrokeRaster::Quads
1149        }
1150    }
1151
1152    /// Switch the line / point rasteriser (see [`StrokeRaster`]); takes effect on the next frame.
1153    pub fn set_stroke_raster(&mut self, s: StrokeRaster) {
1154        self.cfg.stroke = s;
1155    }
1156
1157    /// Resize the internal image (and output). Clears every texture and forgets the previous
1158    /// frame (`m_nFramesSinceResize = 0`). Noise and user textures are kept.
1159    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RenderError> {
1160        check_size(&self.device, width, height)?;
1161        self.geom = MeshGeometry::new(self.cfg.mesh[0], self.cfg.mesh[1], width, height)?;
1162        self.cfg.width = width;
1163        self.cfg.height = height;
1164        let d = &self.device;
1165        self.main = [
1166            create_target(d, width, height, "main0"),
1167            create_target(d, width, height, "main1"),
1168        ];
1169        self.warped = create_target(d, width, height, "warped");
1170        self.warp_sink = create_sink(d, width, height);
1171        self.final_tex = create_target(d, width, height, "final");
1172        *self.blit_bg.borrow_mut() = None;
1173        self.blur_bg.borrow_mut().clear();
1174        self.blur = blur::blur_tex_sizes(width, height)
1175            .iter()
1176            .enumerate()
1177            .map(|(i, &(bw, bh))| create_target(d, bw, bh, &format!("blur{i}")))
1178            .collect();
1179        self.main_idx = 0;
1180        self.forget_prev_warp();
1181        self.mv_state.reset();
1182        self.frames_since_resize = 0;
1183        self.clear_all();
1184        Ok(())
1185    }
1186
1187    /// Change the warp-mesh resolution (cells per axis; the caller applies projectM's clamping, see
1188    /// `lactea::Engine::set_mesh_size`). The previous frame's warp grid and the motion-vector state
1189    /// belong to the old mesh and are forgotten; the images are kept.
1190    pub fn set_mesh_size(&mut self, mesh: [u32; 2]) -> Result<(), RenderError> {
1191        if self.cfg.mesh == mesh {
1192            return Ok(());
1193        }
1194        self.geom = MeshGeometry::new(mesh[0], mesh[1], self.cfg.width, self.cfg.height)?;
1195        self.cfg.mesh = mesh;
1196        self.warp_indices = warp_index_buffer(&self.device, &self.geom, &self.rules);
1197        self.forget_prev_warp();
1198        self.mv_state.reset();
1199        Ok(())
1200    }
1201
1202    /// Change the sub-texel offset added to warp UVs (`projectm_set_texel_offset`); takes effect on
1203    /// the next frame.
1204    pub fn set_texel_offset(&mut self, offset: [f32; 2]) {
1205        self.cfg.texel_offset = offset;
1206    }
1207
1208    /// Start a preset from a black frame (projectM `start_clean`): clears every image and
1209    /// forgets the previous frame's warp grid; drops all user textures (the next preset
1210    /// registers its own). Noise textures are kept.
1211    pub fn reset_images(&mut self) {
1212        self.main_idx = 0;
1213        self.forget_prev_warp();
1214        self.mv_state.reset();
1215        self.main_wave_tail = Default::default();
1216        self.frames_since_resize = 0;
1217        self.user_tex.clear();
1218        self.sprite_images.clear();
1219        self.old_shaders = None;
1220        self.clear_all();
1221    }
1222
1223    fn clear_all(&self) {
1224        let mut enc = self
1225            .device
1226            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1227                label: Some("clear"),
1228            });
1229        let mut all: Vec<&Tex> = vec![&self.main[0], &self.main[1], &self.warped, &self.final_tex];
1230        all.extend(self.blur.iter());
1231        for t in all {
1232            let _ = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1233                label: Some("clear"),
1234                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1235                    view: &t.view,
1236                    depth_slice: None,
1237                    resolve_target: None,
1238                    ops: wgpu::Operations {
1239                        load: wgpu::LoadOp::Clear(wgpu::Color {
1240                            r: 0.0,
1241                            g: 0.0,
1242                            b: 0.0,
1243                            a: if self.rules.main_alpha { 0.0 } else { 1.0 },
1244                        }),
1245                        store: wgpu::StoreOp::Store,
1246                    },
1247                })],
1248                ..Default::default()
1249            });
1250        }
1251        self.queue.submit(Some(enc.finish()));
1252    }
1253
1254    // ---- shaders ----------------------------------------------------------------------
1255
1256    /// Install (or remove, `None` = MD2 `WarpedBlit_NoShaders`) the warp shader.
1257    pub fn set_warp_shader(&mut self, shader: Option<CompiledShader>) -> Result<(), RenderError> {
1258        self.warp_shader = match shader {
1259            Some(s) => Some(self.build_shader_pass(&s, "warp")?),
1260            None => None,
1261        };
1262        Ok(())
1263    }
1264
1265    /// Install (or remove, `None` = MD2 `ShowToUser_NoShaders`) the composite shader.
1266    pub fn set_comp_shader(&mut self, shader: Option<CompiledShader>) -> Result<(), RenderError> {
1267        self.comp_shader = match shader {
1268            Some(s) => Some(self.build_shader_pass(&s, "comp")?),
1269            None => None,
1270        };
1271        Ok(())
1272    }
1273
1274    /// Detach the installed warp / composite shaders and the user textures (MD2's `m_shaders`), leaving the renderer
1275    /// without any. The engine uses this to build the next preset's shaders next to the running ones during a preset
1276    /// blend ([`Renderer::set_old_shader_state`]) and to put the old ones back when that load fails.
1277    pub fn take_shader_state(&mut self) -> ShaderState {
1278        ShaderState(ShaderSet {
1279            warp: self.warp_shader.take(),
1280            comp: self.comp_shader.take(),
1281            user_tex: std::mem::take(&mut self.user_tex),
1282        })
1283    }
1284
1285    /// Reinstall a state taken with [`Renderer::take_shader_state`] (replacing whatever is installed).
1286    pub fn restore_shader_state(&mut self, state: ShaderState) {
1287        let ShaderSet {
1288            warp,
1289            comp,
1290            user_tex,
1291        } = state.0;
1292        self.warp_shader = warp;
1293        self.comp_shader = comp;
1294        self.user_tex = user_tex;
1295    }
1296
1297    /// MD2's `m_OldShaders`: keep `state` (the outgoing preset's shaders and textures) alive for the old half of a
1298    /// preset blend; `None` releases them (`m_OldShaders.*.Clear()` when the blend ends).
1299    pub fn set_old_shader_state(&mut self, state: Option<ShaderState>) {
1300        self.old_shaders = state.map(|s| s.0);
1301    }
1302
1303    /// Whether old shaders are being kept for a preset blend.
1304    pub fn has_old_shaders(&self) -> bool {
1305        self.old_shaders.is_some()
1306    }
1307
1308    /// `(warp, composite)`: whether the installed shaders are user / default pixel shaders (`m_nWarpPSVersion > 0`
1309    /// style flags of the *new* preset and of the old one, if one is kept).
1310    pub fn shader_flags(&self) -> ((bool, bool), (bool, bool)) {
1311        let old = self
1312            .old_shaders
1313            .as_ref()
1314            .map_or((false, false), |o| (o.warp.is_some(), o.comp.is_some()));
1315        (
1316            (self.warp_shader.is_some(), self.comp_shader.is_some()),
1317            old,
1318        )
1319    }
1320
1321    fn build_shader_pass(
1322        &self,
1323        s: &CompiledShader,
1324        label: &str,
1325    ) -> Result<ShaderPass, RenderError> {
1326        if s.interface.textures.len() > lactea_abi::MAX_PASS_TEXTURES {
1327            return Err(RenderError::Invalid(format!(
1328                "{} textures > {}",
1329                s.interface.textures.len(),
1330                lactea_abi::MAX_PASS_TEXTURES
1331            )));
1332        }
1333        let device = &self.device;
1334        // group(1) layout from the interface
1335        // the fold functions read `pu` in the vertex stage
1336        let pass_ubo_stages = if s.folds.is_empty() {
1337            wgpu::ShaderStages::FRAGMENT
1338        } else {
1339            wgpu::ShaderStages::VERTEX_FRAGMENT
1340        };
1341        let mut entries = vec![ubo_entry(
1342            lactea_abi::BINDING_PASS_UNIFORMS,
1343            pass_ubo_stages,
1344        )];
1345        for (i, t) in s.interface.textures.iter().enumerate() {
1346            let dim = match t.dim {
1347                TexDim::D2 => wgpu::TextureViewDimension::D2,
1348                TexDim::D3 => wgpu::TextureViewDimension::D3,
1349            };
1350            // R32Float is not filterable: the translated shader only `textureLoad`s the FFT and BeatDrop's wave
1351            // textures (the sampler entry stays `Filtering` and is never paired with it in a `textureSample`)
1352            let filterable =
1353                !matches!(t.source, TexSource::Fft) && self.engine_wave(&t.source).is_none();
1354            entries.push(tex_entry(
1355                lactea_abi::texture_binding(i as u32),
1356                dim,
1357                filterable,
1358            ));
1359            entries.push(samp_entry(lactea_abi::sampler_binding(i as u32)));
1360        }
1361
1362        #[cfg(not(target_arch = "wasm32"))]
1363        let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
1364        let pass_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1365            label: Some(label),
1366            entries: &entries,
1367        });
1368        // projectM's user warp shader also writes the interpolated warp UV to a second attachment (`texCoords`,
1369        // read back by the motion-vector pass). That second use of `uv` keeps Mesa's NIR from folding constants
1370        // into the varying's plane equation (`uv - 0.5` becomes `plane(uv) - 0.5` instead of the folded
1371        // `plane(uv - 0.5)`, which rounds differently); projectM's driver compiles the shader unfolded, so ours must too.
1372        let (wgsl, uv_sink) = match (label == "warp").then(|| with_uv_output(&s.wgsl)).flatten() {
1373            Some(w) => (w, true),
1374            None => (s.wgsl.clone(), false), // not a recognisable entry: let the shader validation report it
1375        };
1376        let fs = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1377            label: Some(label),
1378            source: wgpu::ShaderSource::Wgsl(wgsl.as_str().into()),
1379        });
1380        let fold_vs = (!s.folds.is_empty()).then(|| {
1381            device.create_shader_module(wgpu::ShaderModuleDescriptor {
1382                label: Some(label),
1383                source: wgpu::ShaderSource::Wgsl(shaders::mesh_vs_folds(&s.folds).into()),
1384            })
1385        });
1386        let mesh_vs = fold_vs.as_ref().unwrap_or(&self.pipes.mesh_vs);
1387        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1388            label: Some(label),
1389            bind_group_layouts: &[Some(&self.pipes.bgl_mu), Some(&pass_bgl)],
1390            immediate_size: 0,
1391        });
1392        let make_pipeline = |layout: &wgpu::PipelineLayout,
1393                             vs: &wgpu::ShaderModule,
1394                             buffers: &[Option<wgpu::VertexBufferLayout>],
1395                             blend: Option<wgpu::BlendState>| {
1396            let color = Some(wgpu::ColorTargetState {
1397                format: INTERNAL_FORMAT,
1398                blend,
1399                write_mask: wgpu::ColorWrites::COLOR,
1400            });
1401            let sink = Some(wgpu::ColorTargetState {
1402                format: WARP_SINK_FORMAT,
1403                blend: None,
1404                write_mask: wgpu::ColorWrites::ALL,
1405            });
1406            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1407                label: Some(label),
1408                layout: Some(layout),
1409                vertex: wgpu::VertexState {
1410                    module: vs,
1411                    entry_point: Some("vs_main"),
1412                    compilation_options: Default::default(),
1413                    buffers,
1414                },
1415                primitive: wgpu::PrimitiveState::default(),
1416                depth_stencil: None,
1417                multisample: wgpu::MultisampleState::default(),
1418                fragment: Some(wgpu::FragmentState {
1419                    module: &fs,
1420                    entry_point: Some(FRAGMENT_ENTRY),
1421                    compilation_options: Default::default(),
1422                    targets: &[color, sink][..if uv_sink { 2 } else { 1 }],
1423                }),
1424                multiview_mask: None,
1425                cache: None,
1426            })
1427        };
1428        let pipeline = make_pipeline(&layout, mesh_vs, &[Some(mesh_layout())], None);
1429        // MD2's preset blend draws the second pass of a shader pair alpha-blended over the first
1430        let alpha_pipelines = self.rules.md2_preset_blend.then(|| {
1431            [Blend::SrcAlpha, Blend::InvSrcAlpha]
1432                .map(|b| make_pipeline(&layout, mesh_vs, &[Some(mesh_layout())], blend_state(b)))
1433        });
1434        let warp_pipeline = if label == "warp" {
1435            let warp_vs_sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1436                label: Some("warp_vs"),
1437                source: wgpu::ShaderSource::Wgsl(
1438                    if s.folds.is_empty() {
1439                        shaders::warp_vs(2)
1440                    } else {
1441                        shaders::warp_vs_folds(2, &s.folds)
1442                    }
1443                    .into(),
1444                ),
1445            });
1446            let warp_layout_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1447                label: Some("warp gpu"),
1448                bind_group_layouts: &[
1449                    Some(&self.pipes.bgl_mu),
1450                    Some(&pass_bgl),
1451                    Some(&self.pipes.bgl_warp_vs),
1452                ],
1453                immediate_size: 0,
1454            });
1455            Some(make_pipeline(
1456                &warp_layout_pl,
1457                &warp_vs_sm,
1458                &[Some(warp_layout())],
1459                None,
1460            ))
1461        } else {
1462            None
1463        };
1464        #[cfg(not(target_arch = "wasm32"))]
1465        if let Some(err) = pollster::block_on(scope.pop()) {
1466            return Err(RenderError::Shader(err.to_string()));
1467        }
1468        Ok(ShaderPass {
1469            pipeline,
1470            warp_pipeline,
1471            pass_bgl,
1472            interface: s.interface.clone(),
1473            uv_sink,
1474            alpha_pipelines,
1475        })
1476    }
1477
1478    // ---- textures ---------------------------------------------------------------------
1479
1480    /// Register a user texture (`sampler_<name>`): RGBA8, row 0 = top, with a CPU mip chain.
1481    /// `name` is matched case-insensitively against `TexSource::User`.
1482    pub fn set_user_texture(
1483        &mut self,
1484        name: &str,
1485        w: u32,
1486        h: u32,
1487        rgba8: &[u8],
1488    ) -> Result<(), RenderError> {
1489        check_frames(
1490            &format!("user texture {name}"),
1491            self.device.limits().max_texture_dimension_2d,
1492            w,
1493            h,
1494            &[rgba8],
1495        )?;
1496        let tex = upload_2d(&self.device, &self.queue, w, h, rgba8, true, name);
1497        self.user_tex
1498            .insert(name.to_ascii_lowercase(), UserTex { tex, anim: None });
1499        Ok(())
1500    }
1501
1502    /// Register an animated user texture (an animated GIF as `sampler_<name>`, `Compat::MilkDrop3`): `frames` are
1503    /// `w * h * 4` RGBA8 images (row 0 = top), `delays` their durations in seconds. Every draw shows the frame
1504    /// [`gif_frame_index`](crate::gif_frame_index) picks for the time of the frame being rendered. No mip chain.
1505    pub fn set_user_animation(
1506        &mut self,
1507        name: &str,
1508        w: u32,
1509        h: u32,
1510        frames: &[&[u8]],
1511        delays: &[f64],
1512    ) -> Result<(), RenderError> {
1513        check_frames(
1514            name,
1515            self.device.limits().max_texture_dimension_2d,
1516            w,
1517            h,
1518            frames,
1519        )?;
1520        if delays.len() != frames.len() {
1521            return Err(RenderError::Invalid(format!(
1522                "animated texture {name}: {} frames but {} delays",
1523                frames.len(),
1524                delays.len()
1525            )));
1526        }
1527        let tex: Vec<Tex> = frames
1528            .iter()
1529            .map(|f| upload_2d(&self.device, &self.queue, w, h, f, false, name))
1530            .collect();
1531        self.user_tex.insert(
1532            name.to_ascii_lowercase(),
1533            UserTex {
1534                tex: tex[0].clone(),
1535                anim: Some(UserAnim {
1536                    frames: tex,
1537                    delays: delays.to_vec(),
1538                }),
1539            },
1540        );
1541        Ok(())
1542    }
1543
1544    /// Register the image of an MD3 sprite under `id` ([`SpriteDraw::image`](crate::SpriteDraw::image)), replacing
1545    /// any image with that id. `frames` are `w * h * 4` RGBA8 images (row 0 = top, straight alpha, colour key already
1546    /// applied); a static image has one frame and `mips` (full chain, trilinear sampling), a GIF has no mips.
1547    pub fn set_sprite_image(
1548        &mut self,
1549        id: u32,
1550        w: u32,
1551        h: u32,
1552        frames: &[&[u8]],
1553        mips: bool,
1554    ) -> Result<(), RenderError> {
1555        check_frames(
1556            "sprite",
1557            self.device.limits().max_texture_dimension_2d,
1558            w,
1559            h,
1560            frames,
1561        )?;
1562        // a sprite is about to be drawn: build the pipelines now, not as a hitch in the first frame that draws one
1563        self.pipes.sprites(&self.device);
1564        let views = frames
1565            .iter()
1566            .map(|f| upload_2d(&self.device, &self.queue, w, h, f, mips, "sprite").view)
1567            .collect();
1568        self.sprite_images.insert(id, SpriteImage { frames: views });
1569        Ok(())
1570    }
1571
1572    /// Forget every sprite image.
1573    pub fn clear_sprite_images(&mut self) {
1574        self.sprite_images.clear();
1575    }
1576
1577    /// Forget every user texture (`set_user_texture` / `set_user_animation`); shaders sampling one see the
1578    /// placeholder until it is registered again.
1579    pub fn clear_user_textures(&mut self) {
1580        self.user_tex.clear();
1581    }
1582
1583    /// Whether an image is registered under `id`.
1584    pub fn has_sprite_image(&self, id: u32) -> bool {
1585        self.sprite_images.contains_key(&id)
1586    }
1587
1588    /// Forget the image registered under `id`, if any.
1589    pub fn remove_sprite_image(&mut self, id: u32) {
1590        self.sprite_images.remove(&id);
1591    }
1592    /// Draw sprites (any layer value) onto `target`, an `Rgba8Unorm` view: the sprite pass on its own, for hosts
1593    /// that composite themselves and for tests. Draws whose image or frame is not registered are skipped.
1594    pub fn draw_sprites(
1595        &self,
1596        encoder: &mut wgpu::CommandEncoder,
1597        target: &wgpu::TextureView,
1598        draws: &[SpriteDraw],
1599    ) {
1600        let refs: Vec<&SpriteDraw> = draws.iter().collect();
1601        self.sprite_pass(encoder, target, &refs);
1602    }
1603
1604    /// Draw `draws` into the image the next frame's warp reads (projectM's `burn`), the ones with `burn` set only:
1605    /// call after [`Renderer::render_frame_to_output`], when that image is the one just produced.
1606    pub fn burn_sprites(&self, encoder: &mut wgpu::CommandEncoder, draws: &[SpriteDraw]) {
1607        let burn: Vec<&SpriteDraw> = draws.iter().filter(|d| d.burn).collect();
1608        if !burn.is_empty() {
1609            self.sprite_pass(encoder, &self.main[self.main_idx].view, &burn);
1610        }
1611    }
1612
1613    /// Draw `draws` onto `target`, a view of the host's output (`RenderConfig::output_format`), loaded not cleared:
1614    /// sprites over a finished frame, e.g. over a soft cut's blend.
1615    pub fn draw_sprites_to_output(
1616        &self,
1617        encoder: &mut wgpu::CommandEncoder,
1618        target: &wgpu::TextureView,
1619        draws: &[SpriteDraw],
1620    ) {
1621        let refs: Vec<&SpriteDraw> = draws.iter().collect();
1622        self.pipes
1623            .sprites_for(&self.device, self.cfg.output_format)
1624            .draw(
1625                &self.device,
1626                encoder,
1627                target,
1628                &self.pipes.bgl_tex,
1629                self.pipes.sampler(Filter::Linear, Address::Wrap, false),
1630                &self.sprite_images,
1631                &refs,
1632            );
1633    }
1634
1635    /// Read a stage back as `(width, height, RGBA8)` (row 0 = top). The command buffers of the
1636    /// frame must have been submitted. `Stage::Main` is the image the next frame's warp samples;
1637    /// `Warped` the image right after the warp pass; `Blur1..3` the user-visible blur levels
1638    /// (blur textures 1, 3, 5); `Final` the composite output.
1639    pub fn read_stage(&self, stage: Stage) -> Result<(u32, u32, Vec<u8>), RenderError> {
1640        let t = match stage {
1641            Stage::Final => &self.final_tex,
1642            Stage::Main => &self.main[self.main_idx],
1643            Stage::Warped => &self.warped,
1644            Stage::Blur1 => &self.blur[1],
1645            Stage::Blur2 => &self.blur[3],
1646            Stage::Blur3 => &self.blur[5],
1647        };
1648        self.read_texture(t)
1649    }
1650
1651    fn read_texture(&self, t: &Tex) -> Result<(u32, u32, Vec<u8>), RenderError> {
1652        let data = readback_rgba8(&self.device, &self.queue, &t.texture, t.w, t.h)?;
1653        Ok((t.w, t.h, data))
1654    }
1655
1656    // ---- rendering --------------------------------------------------------------------
1657
1658    /// Blur levels forced on by a diagnostic request (0 without the `diagnostics` feature).
1659    fn diagnostic_blur_levels(&self) -> u8 {
1660        #[cfg(feature = "diagnostics")]
1661        {
1662            self.min_blur_levels.min(3)
1663        }
1664        #[cfg(not(feature = "diagnostics"))]
1665        {
1666            0
1667        }
1668    }
1669
1670    /// The image a composite pass reads as its `sampler_main`: `regular`, or the injected one.
1671    fn comp_source_view<'a>(&'a self, regular: &'a wgpu::TextureView) -> &'a wgpu::TextureView {
1672        #[cfg(feature = "diagnostics")]
1673        if let Some(t) = &self.comp_source_override {
1674            return &t.view;
1675        }
1676        regular
1677    }
1678
1679    /// Highest blur level (0..=3) the installed shaders require (including the old preset's while a preset blend
1680    /// keeps them: MD2's `ApplyShaderParams` counts every pass it applies, also `m_OldShaders`).
1681    pub fn blur_levels_required(&self) -> u8 {
1682        let level = |p: &Option<ShaderPass>| p.as_ref().map_or(0, |s| s.interface.max_blur_level);
1683        let mut m = level(&self.warp_shader).max(level(&self.comp_shader));
1684        if let Some(o) = &self.old_shaders {
1685            m = m.max(level(&o.warp)).max(level(&o.comp));
1686        }
1687        m.min(3)
1688    }
1689
1690    /// Forget the previous frame's warp grid, vertex inputs and their pending UV readback.
1691    fn forget_prev_warp(&mut self) {
1692        self.prev_warp_uv = None;
1693        self.prev_warp_gpu = None;
1694        if let Some(rb) = &mut self.uv_readback {
1695            rb.pending = None;
1696        }
1697    }
1698
1699    /// Submit the UV readback of `prev_warp_gpu` (the vertex inputs of the frame just recorded), or drop the pending
1700    /// one if there are none.
1701    fn submit_uv_readback(&mut self) {
1702        let Some(wg) = self.prev_warp_gpu.as_ref() else {
1703            if let Some(rb) = &mut self.uv_readback {
1704                rb.pending = None;
1705            }
1706            return;
1707        };
1708        let (w, h) = (self.geom.gx + 1, self.geom.gy + 1);
1709        let verts = geom::build_warp_gpu_vertices(&self.geom, &wg.vars);
1710        let toff = self.texel_offset_uv();
1711        let mut vu = self.warp_vs_uniforms(wg, toff, 1.0);
1712        vu.diffuse = [w as f32, h as f32, 0.0, 0.0];
1713        if !matches!(&self.uv_readback, Some(rb) if rb.w == w && rb.h == h) {
1714            self.uv_readback = Some(UvReadback::new(&self.device, &self.pipes, w, h));
1715        }
1716        if let Some(rb) = &mut self.uv_readback {
1717            rb.submit(&self.device, &self.queue, &self.pipes, &verts, &vu, toff);
1718        }
1719    }
1720
1721    /// The GPU's own per-vertex warp UVs of `prev_warp_gpu` (`warp_vs` evaluated on the device, lactea mesh index
1722    /// order). projectM's motion vector lookup reads the interpolation of *these* (`RG16F` UV map written by the warp
1723    /// pass), so the CPU port of the formula (`warp_mesh`) differs from it by the GPU's `pow` / `sin` / `cos`
1724    /// approximations and fusion.
1725    ///
1726    /// Normally the readback was submitted at the end of the previous frame ([`Renderer::submit_uv_readback`]); it
1727    /// is only recorded here (and waited for) when that frame did not draw motion vectors or the texel offset
1728    /// changed since.
1729    fn gpu_warp_vertex_uv(&mut self) -> Result<Vec<[f32; 2]>, RenderError> {
1730        let toff = self.texel_offset_uv();
1731        let submitted = self
1732            .uv_readback
1733            .as_ref()
1734            .and_then(|rb| rb.pending.as_ref())
1735            .is_some_and(|(_, t)| *t == toff);
1736        if !submitted {
1737            self.submit_uv_readback();
1738        }
1739        let Some(rb) = self.uv_readback.as_mut() else {
1740            return Err(RenderError::Readback(
1741                "no previous warp vertex inputs".to_owned(),
1742            ));
1743        };
1744        let uv = rb.collect(&self.device, &self.geom);
1745        if uv.is_err() {
1746            self.uv_readback = None;
1747        }
1748        uv
1749    }
1750
1751    fn texel_offset_uv(&self) -> [f32; 2] {
1752        warp_mesh::texel_offset_uv(self.cfg.texel_offset, self.cfg.width, self.cfg.height)
1753    }
1754
1755    /// Default warp UVs when the engine supplies none: identity motion.
1756    fn default_warp_uv(&self, f: &FrameInput) -> Vec<[f32; 2]> {
1757        let anim = WarpAnim::new(f.time as f32, 1.0, 1.0);
1758        let v = VertexVars {
1759            warp: 0.0,
1760            ..Default::default()
1761        };
1762        warp_mesh::warp_mesh_uniform(&self.geom, &v, &anim, self.texel_offset_uv())
1763    }
1764
1765    /// The CPU warp UV grid of `wg` (`warp_mesh`, as the engine computes it for a renderer without a GPU warp stage):
1766    /// the fallback of a motion vector lookup whose GPU readback failed.
1767    fn cpu_warp_uv(&self, wg: &crate::frame::WarpGpu) -> Vec<[f32; 2]> {
1768        let toff = self.texel_offset_uv();
1769        wg.vars
1770            .iter()
1771            .enumerate()
1772            .map(|(n, vv)| warp_mesh::warp_vertex_uv(&self.geom, n, vv, &wg.anim, toff))
1773            .collect()
1774    }
1775
1776    /// Record one frame into `encoder`, ending with the composite blitted to `target`.
1777    ///
1778    /// All per-frame GPU data is baked into buffers at record time, so frames may be recorded in
1779    /// any order, but the encoder must be submitted before [`Renderer::read_stage`] is called.
1780    /// `target` must be a view of a `cfg.width x cfg.height` texture of `cfg.output_format`.
1781    ///
1782    /// Fails with [`RenderError::Invalid`] (recording nothing) if `input.warp_uv` does not match the mesh or
1783    /// `input.md2_blend` is set without `Compat::MilkDrop2` / `Compat::MilkDrop3`.
1784    pub fn render_frame(
1785        &mut self,
1786        encoder: &mut wgpu::CommandEncoder,
1787        input: &FrameInput,
1788        target: &wgpu::TextureView,
1789    ) -> Result<(), RenderError> {
1790        self.render_frame_inner(encoder, input, Some(target))
1791    }
1792
1793    /// Like [`Renderer::render_frame`] but stops after the composite: the finished image stays in
1794    /// the renderer ([`Renderer::output_view`]) and nothing is written to a host target. Used for
1795    /// presets that are blended into the frame by a transition.
1796    pub fn render_frame_to_output(
1797        &mut self,
1798        encoder: &mut wgpu::CommandEncoder,
1799        input: &FrameInput,
1800    ) -> Result<(), RenderError> {
1801        self.render_frame_inner(encoder, input, None)
1802    }
1803
1804    /// The composited image of the last rendered frame (`Rgba8Unorm`, row 0 = top, the `final`
1805    /// stage): projectM's `Preset::OutputTexture()`.
1806    pub fn output_view(&self) -> &wgpu::TextureView {
1807        &self.final_tex.view
1808    }
1809
1810    /// Start this preset from `src`'s composited image instead of black (projectM
1811    /// `DrawInitialImage`, used when `start_clean` is off): the image the first warp samples.
1812    /// `src` must have the same size. Call after [`Renderer::reset_images`].
1813    ///
1814    /// Fails with [`RenderError::Invalid`] if the two renderers differ in size.
1815    pub fn draw_initial_image(
1816        &mut self,
1817        encoder: &mut wgpu::CommandEncoder,
1818        src: &Renderer,
1819    ) -> Result<(), RenderError> {
1820        if (self.cfg.width, self.cfg.height) != (src.cfg.width, src.cfg.height) {
1821            return Err(RenderError::Invalid(format!(
1822                "initial image size mismatch: {}x{} vs {}x{}",
1823                self.cfg.width, self.cfg.height, src.cfg.width, src.cfg.height
1824            )));
1825        }
1826        self.main_idx = 0;
1827        encoder.copy_texture_to_texture(
1828            wgpu::TexelCopyTextureInfo {
1829                texture: &src.final_tex.texture,
1830                mip_level: 0,
1831                origin: wgpu::Origin3d::ZERO,
1832                aspect: wgpu::TextureAspect::All,
1833            },
1834            wgpu::TexelCopyTextureInfo {
1835                texture: &self.main[0].texture,
1836                mip_level: 0,
1837                origin: wgpu::Origin3d::ZERO,
1838                aspect: wgpu::TextureAspect::All,
1839            },
1840            wgpu::Extent3d {
1841                width: self.cfg.width,
1842                height: self.cfg.height,
1843                depth_or_array_layers: 1,
1844            },
1845        );
1846        Ok(())
1847    }
1848
1849    /// Reject frame inputs the renderer cannot draw, before anything is recorded.
1850    fn check_input(&self, input: &FrameInput) -> Result<(), RenderError> {
1851        if let Some(u) = &input.warp_uv {
1852            let n = self.geom.vertex_count();
1853            if u.len() != n {
1854                return Err(RenderError::Invalid(format!(
1855                    "FrameInput.warp_uv has {} entries, the {}x{} mesh needs {n}",
1856                    u.len(),
1857                    self.geom.gx,
1858                    self.geom.gy
1859                )));
1860            }
1861        }
1862        if self.rules.warp_uv_on_gpu
1863            && let Some(wg) = &input.warp_gpu
1864            && wg.vars.len() != self.geom.vertex_count()
1865        {
1866            return Err(RenderError::Invalid(format!(
1867                "FrameInput.warp_gpu has {} vertices, the {}x{} mesh needs {}",
1868                wg.vars.len(),
1869                self.geom.gx,
1870                self.geom.gy,
1871                self.geom.vertex_count()
1872            )));
1873        }
1874        if input.md2_blend.is_some() && !self.rules.md2_preset_blend {
1875            return Err(RenderError::Invalid(
1876                "FrameInput.md2_blend needs Compat::MilkDrop2 or Compat::MilkDrop3".to_owned(),
1877            ));
1878        }
1879        Ok(())
1880    }
1881
1882    // ---- fixed-function content ---------------------------------------------------------
1883}
1884
1885const BLACK: wgpu::Color = wgpu::Color {
1886    r: 0.0,
1887    g: 0.0,
1888    b: 0.0,
1889    a: 1.0,
1890};
1891
1892/// Per-frame working buffers of the overlay / motion-vector builders, kept across frames so a frame
1893/// allocates nothing once they are warm. Contents are overwritten by every user.
1894#[derive(Default)]
1895struct FrameScratch {
1896    pm_wave: wavegen::PmWaveScratch,
1897    /// custom-wave source points / colours
1898    pts: Vec<[f32; 2]>,
1899    cols: Vec<[f32; 4]>,
1900    /// smoothed points / colours
1901    sp: Vec<[f32; 2]>,
1902    sc: Vec<[f32; 4]>,
1903    /// vertices handed to a `Batch` (dots, segments, motion vectors)
1904    verts: Vec<WfVertex>,
1905    /// one strip's segments before they are appended to `verts`
1906    seg: Vec<WfVertex>,
1907}
1908
1909/// `SmoothWave` carrying per-vertex colours (`vo[j+1].Diffuse = vi[i].Diffuse`), into reusable buffers.
1910fn smooth_with_colors_into(
1911    sp: &mut Vec<[f32; 2]>,
1912    sc: &mut Vec<[f32; 4]>,
1913    pts: &[[f32; 2]],
1914    cols: &[[f32; 4]],
1915) {
1916    wavegen::smooth_wave_into(sp, pts);
1917    let n = pts.len();
1918    sc.clear();
1919    sc.reserve(sp.len());
1920    for c in &cols[..n - 1] {
1921        sc.push(*c);
1922        sc.push(*c);
1923    }
1924    sc.push(cols[n - 1]);
1925}
1926
1927#[cfg(test)]
1928mod uv_output_tests {
1929    use super::with_uv_output;
1930
1931    /// Regression (`sin((uv.x - 0.5) * 100)` gave 15 480 wrong pixels in 13 frames): the warp shader's
1932    /// fragment entry gets projectM's second `texCoords` output so `uv` has two uses, like projectM's.
1933    #[test]
1934    fn warp_entry_gets_a_second_uv_output() {
1935        let src = "fn f() {}\n@fragment\nfn fs_main(in: VsOut) -> @location(0) vec4<f32> {\n    return in.diffuse;\n}\n";
1936        let out = with_uv_output(src).unwrap();
1937        assert!(with_uv_output("this is not wgsl").is_none());
1938        assert!(out.contains("fn fs_main_color(in: VsOut) -> vec4<f32> {"));
1939        assert!(out.contains("fn fs_main(in: VsOut) -> WarpFsOut"));
1940        assert!(out.contains("o.uv = in.uv.xy;"));
1941        assert_eq!(out.matches("@fragment").count(), 1);
1942    }
1943}