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/// Whether a GPU buffer can be mapped and waited for inside a call. WebGPU maps buffers only once control returns
695/// to the browser's event loop, so such a wait never completes there: the web build reads nothing back and the
696/// motion vector pass uses the CPU port of the warp formula (`cpu_warp_uv`) instead of the GPU's own UVs.
697pub(crate) const SYNC_READBACK: bool = cfg!(not(target_arch = "wasm32"));
698
699/// Read an `Rgba8Unorm`-sized (4 bytes per texel) `w` x `h` texture back as tightly packed RGBA8 (row 0 = top).
700/// Submits its own copy and waits for it, so the frame's command buffers must have been submitted. Always an error
701/// on the web ([`SYNC_READBACK`]).
702pub fn readback_rgba8(
703    device: &wgpu::Device,
704    queue: &wgpu::Queue,
705    texture: &wgpu::Texture,
706    w: u32,
707    h: u32,
708) -> Result<Vec<u8>, RenderError> {
709    if !SYNC_READBACK {
710        return Err(RenderError::Readback(
711            "synchronous GPU readback is not available on the web".to_owned(),
712        ));
713    }
714    let bpr = padded_bytes_per_row(w * 4);
715    let buf = device.create_buffer(&wgpu::BufferDescriptor {
716        label: Some("readback"),
717        size: u64::from(bpr) * u64::from(h),
718        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
719        mapped_at_creation: false,
720    });
721    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
722        label: Some("readback"),
723    });
724    enc.copy_texture_to_buffer(
725        wgpu::TexelCopyTextureInfo {
726            texture,
727            mip_level: 0,
728            origin: wgpu::Origin3d::ZERO,
729            aspect: wgpu::TextureAspect::All,
730        },
731        wgpu::TexelCopyBufferInfo {
732            buffer: &buf,
733            layout: wgpu::TexelCopyBufferLayout {
734                offset: 0,
735                bytes_per_row: Some(bpr),
736                rows_per_image: Some(h),
737            },
738        },
739        wgpu::Extent3d {
740            width: w,
741            height: h,
742            depth_or_array_layers: 1,
743        },
744    );
745    queue.submit(Some(enc.finish()));
746    let slice = buf.slice(..);
747    let (tx, rx) = std::sync::mpsc::channel();
748    slice.map_async(wgpu::MapMode::Read, move |r| {
749        let _ = tx.send(r);
750    });
751    device
752        .poll(wgpu::PollType::wait_indefinitely())
753        .map_err(|e| RenderError::Readback(format!("{e:?}")))?;
754    rx.recv()
755        .map_err(|e| RenderError::Readback(e.to_string()))?
756        .map_err(|e| RenderError::Readback(e.to_string()))?;
757    let data = slice
758        .get_mapped_range()
759        .map_err(|e| RenderError::Readback(e.to_string()))?;
760    let row = w as usize * 4;
761    let mut out = Vec::with_capacity(row * h as usize);
762    for y in 0..h {
763        let s = y as usize * bpr as usize;
764        out.extend_from_slice(&data[s..s + row]);
765    }
766    drop(data);
767    buf.unmap();
768    Ok(out)
769}
770
771/// Index buffer of the GPU warp mesh ([`geom::warp_gpu_indices`]) and its index count; only projectM's rules draw it.
772/// Constant for a mesh size, so built when the mesh changes rather than every frame.
773fn warp_index_buffer(
774    device: &wgpu::Device,
775    geom: &MeshGeometry,
776    rules: &CompatRules,
777) -> Option<(wgpu::Buffer, u32)> {
778    if !rules.warp_uv_on_gpu {
779        return None;
780    }
781    let idx = geom::warp_gpu_indices(geom, rules.warp_diag_flipped);
782    let buf = buffer_init(device, "warp indices", &idx, wgpu::BufferUsages::INDEX);
783    Some((buf, idx.len() as u32))
784}
785
786/// Check a render size against zero and the device's 2D texture limit.
787fn check_size(device: &wgpu::Device, width: u32, height: u32) -> Result<(), RenderError> {
788    if width == 0 || height == 0 {
789        return Err(RenderError::Invalid(format!(
790            "render size must be non-zero, got {width}x{height}"
791        )));
792    }
793    let max = device.limits().max_texture_dimension_2d;
794    if width > max || height > max {
795        return Err(RenderError::Invalid(format!(
796            "render size {width}x{height} exceeds the device texture limit of {max}"
797        )));
798    }
799    Ok(())
800}
801
802/// The mesh geometry of `cfg`, after checking that its size and mesh are usable.
803fn checked_geometry(
804    device: &wgpu::Device,
805    cfg: &RenderConfig,
806) -> Result<MeshGeometry, RenderError> {
807    check_size(device, cfg.width, cfg.height)?;
808    MeshGeometry::new(cfg.mesh[0], cfg.mesh[1], cfg.width, cfg.height)
809}
810
811// ---------------------------------------------------------------------------------------
812// Renderer
813// ---------------------------------------------------------------------------------------
814
815/// The MilkDrop 2 frame renderer. See the crate docs for the pass order.
816pub struct Renderer {
817    device: wgpu::Device,
818    queue: wgpu::Queue,
819    cfg: RenderConfig,
820    rules: CompatRules,
821    geom: MeshGeometry,
822    /// Triangles of the GPU warp mesh over the unique vertices of [`geom::build_warp_gpu_vertices`].
823    warp_indices: Option<(wgpu::Buffer, u32)>,
824    /// See [`Renderer::blit`].
825    blit_bg: std::cell::RefCell<Option<wgpu::BindGroup>>,
826    /// Bind groups of blur passes 1.. keyed by their uniform values (see `Renderer::run_blur`); dropped on `resize`.
827    blur_bg: std::cell::RefCell<Vec<Option<BlurBindGroup>>>,
828    rot: RotParams,
829    pipes: std::sync::Arc<Pipelines>,
830    /// `m_lpVS[0..2]` ping-pong; `main[main_idx]` holds the latest `main` image.
831    main: [Tex; 2],
832    main_idx: usize,
833    warped: Tex,
834    final_tex: Tex,
835    blur: Vec<Tex>,
836    noise: Vec<Tex>,
837    user_tex: HashMap<String, UserTex>,
838    /// MD3 sprite images by id ([`Renderer::set_sprite_image`]).
839    sprite_images: HashMap<u32, SpriteImage>,
840    /// Time of the frame being recorded: animated textures pick their frame from it.
841    anim_time: f64,
842    dummy_2d: Tex,
843    dummy_3d: Tex,
844    /// `sampler_fft` ([`TexSource::Fft`]): the smoothed MilkDrop 3 shader FFT (512 x 1), or under
845    /// `CompatRules::md2_shader_inputs` BeatDrop's `m_lpFFTTexture` (1024 x 2: spectrum, peak hold). Owned per renderer
846    /// (a [`Renderer::sibling`] has its own) and replaced whenever a frame carries `FrameInput::ext.fft` /
847    /// `FrameInput::ext.beatdrop`.
848    fft: Tex,
849    /// BeatDrop's `m_lpWaveTexture` (480 x 2: left, right), only under `CompatRules::md2_shader_inputs`. The
850    /// translator names it by the user texture `"wave"` (the frozen ABI has no source for it): see
851    /// [`Renderer::engine_wave`].
852    wave: Option<Tex>,
853    /// Scratch attachment for the user warp shader's second output ([`with_uv_output`]); never read.
854    warp_sink: Tex,
855    warp_shader: Option<ShaderPass>,
856    comp_shader: Option<ShaderPass>,
857    /// MD2's `m_OldShaders` (+ the old preset's textures): the old preset's shaders while a preset blend runs.
858    old_shaders: Option<ShaderSet>,
859    /// Warp UV grid of the previous frame (motion vector reverse propagation).
860    prev_warp_uv: Option<Vec<[f32; 2]>>,
861    /// The previous frame's warp vertex-shader inputs, to evaluate its UVs on the GPU (motion vector lookups).
862    prev_warp_gpu: Option<crate::frame::WarpGpu>,
863    /// Persistent readback of the GPU's warp UVs ([`Renderer::gpu_warp_vertex_uv`]).
864    uv_readback: Option<UvReadback>,
865    /// projectM's motion vector mesh (stale vertices, index count).
866    mv_state: MotionVectorState,
867    frames_since_resize: u32,
868    /// projectM's persistent main-wave buffer tail (see [`wavegen::PmWaveTail`]); zero at preset load.
869    main_wave_tail: wavegen::PmWaveTail,
870    /// Working buffers of the per-frame geometry builders.
871    scratch: FrameScratch,
872    /// Highest blur level used by the last rendered frame's shaders (for tests / diagnostics).
873    last_blur_levels: u8,
874    /// Minimum blur level computed every frame ([`Renderer::set_min_blur_levels`]).
875    #[cfg(feature = "diagnostics")]
876    min_blur_levels: u8,
877    /// One-shot override of the composite `sampler_main` ([`Renderer::inject_comp_source`]).
878    #[cfg(feature = "diagnostics")]
879    comp_source_override: Option<Tex>,
880}
881
882/// Hooks for comparing against a reference render (feature `diagnostics`): replacing internal images, forcing
883/// per-frame state and reading intermediate images back.
884#[cfg(feature = "diagnostics")]
885impl Renderer {
886    /// Replace a built-in noise texture (e.g. with a reference render's noise). 2D: `size*size*4` bytes,
887    /// row 0 first; volumes: `size^3*4`, slice-major. Sizes are MD2's (see [`crate::noise::noise_spec`]).
888    pub fn inject_noise(&mut self, which: NoiseTex, data: &[u8]) -> Result<(), RenderError> {
889        let (size, _, vol) = noise::noise_spec(which);
890        let expect = if vol {
891            (size * size * size * 4) as usize
892        } else {
893            (size * size * 4) as usize
894        };
895        if data.len() != expect {
896            return Err(RenderError::Invalid(format!(
897                "{which:?}: expected {expect} bytes, got {}",
898                data.len()
899            )));
900        }
901        self.noise[which.index()] = if vol {
902            upload_3d(&self.device, &self.queue, size, data, "noise_vol")
903        } else {
904            upload_2d(&self.device, &self.queue, size, size, data, true, "noise")
905        };
906        Ok(())
907    }
908
909    /// Replace the previous-frame image (`main`, what the next warp samples).
910    pub fn inject_main(&mut self, rgba8: &[u8]) -> Result<(), RenderError> {
911        let t = &self.main[self.main_idx];
912        self.write_rgba8(t, rgba8, "inject_main")
913    }
914
915    /// Use `rgba8` as the composite source (a comp shader's `sampler_main`, or the no-shader composite's
916    /// texture) for the next rendered frame only. Does not touch the stored `main` image, so the `main` stage
917    /// read-back stays the renderer's own.
918    pub fn inject_comp_source(&mut self, rgba8: &[u8]) -> Result<(), RenderError> {
919        let (w, h) = (self.cfg.width, self.cfg.height);
920        let t = create_target(&self.device, w, h, "comp source override");
921        self.write_rgba8(&t, rgba8, "inject_comp_source")?;
922        self.comp_source_override = Some(t);
923        Ok(())
924    }
925
926    /// Make the next frame's motion-vector pass use this warp UV grid (the previous frame's UVs).
927    pub fn inject_prev_warp_uv(&mut self, uv: Option<Vec<[f32; 2]>>) {
928        self.prev_warp_uv = uv;
929    }
930
931    /// The image the last frame's warp pass sampled (previous `main` + this frame's motion vectors).
932    /// Valid until the next `render_frame`.
933    pub fn read_warp_source(&self) -> Result<(u32, u32, Vec<u8>), RenderError> {
934        self.read_texture(&self.main[1 - self.main_idx])
935    }
936
937    /// Compute at least `levels` (0..=3) blur levels every frame even if no shader samples them, so
938    /// `Stage::Blur1..3` can be read back.
939    pub fn set_min_blur_levels(&mut self, levels: u8) {
940        self.min_blur_levels = levels.min(3);
941    }
942
943    /// Per-preset random parameters (rotation matrices, hue offsets).
944    pub fn rot_params(&self) -> &RotParams {
945        &self.rot
946    }
947
948    /// Replace the per-preset random parameters (they otherwise stay as drawn from the seed).
949    pub fn set_rot_params(&mut self, p: RotParams) {
950        self.rot = p;
951    }
952
953    /// Upload a full-size RGBA8 image (row 0 = top) into `t`.
954    fn write_rgba8(&self, t: &Tex, rgba8: &[u8], what: &str) -> Result<(), RenderError> {
955        let need = t.w as usize * t.h as usize * 4;
956        if rgba8.len() != need {
957            return Err(RenderError::Invalid(format!(
958                "{what}: need {need} bytes, got {}",
959                rgba8.len()
960            )));
961        }
962        self.queue.write_texture(
963            wgpu::TexelCopyTextureInfo {
964                texture: &t.texture,
965                mip_level: 0,
966                origin: wgpu::Origin3d::ZERO,
967                aspect: wgpu::TextureAspect::All,
968            },
969            rgba8,
970            wgpu::TexelCopyBufferLayout {
971                offset: 0,
972                bytes_per_row: Some(t.w * 4),
973                rows_per_image: Some(t.h),
974            },
975            wgpu::Extent3d {
976                width: t.w,
977                height: t.h,
978                depth_or_array_layers: 1,
979            },
980        );
981        Ok(())
982    }
983}
984
985impl Renderer {
986    /// Create a renderer. Textures are cleared to black; noise textures are generated from
987    /// `cfg.seed` (MD2 algorithm). `device`/`queue` are cloned handles (cheap).
988    ///
989    /// # Errors
990    ///
991    /// [`RenderError::Invalid`] if the size is zero or the mesh is not an even grid of at least 2x2 cells.
992    pub fn new(
993        device: &wgpu::Device,
994        queue: &wgpu::Queue,
995        cfg: RenderConfig,
996    ) -> Result<Self, RenderError> {
997        let geom = checked_geometry(device, &cfg)?;
998        let pipes = std::sync::Arc::new(Pipelines::new(device, cfg.output_format));
999        Ok(Self::assemble(device, queue, cfg, geom, pipes, None))
1000    }
1001
1002    /// A second renderer with the same configuration that shares this one's pipelines and
1003    /// (immutable) noise textures but has its own images, shaders and user textures: what the
1004    /// engine needs to run two presets at once while they transition. Cheaper than
1005    /// [`Renderer::new`] (no pipeline compilation, no noise generation), but it still allocates the render targets.
1006    pub fn sibling(&self) -> Self {
1007        self.sibling_with_compat(self.cfg.compat)
1008    }
1009
1010    /// [`Renderer::sibling`] that follows another compatibility mode: same size, mesh, stroke setting, shared
1011    /// pipelines and noise (neither depends on the mode), but its own images, shaders and textures, and the rules of
1012    /// `compat`. What the engine builds into when an automatically selected mode changes.
1013    pub fn sibling_with_compat(&self, compat: Compat) -> Self {
1014        let mut cfg = self.cfg.clone();
1015        cfg.compat = compat;
1016        let mut r = Self::assemble(
1017            &self.device,
1018            &self.queue,
1019            cfg,
1020            self.geom.clone(),
1021            std::sync::Arc::clone(&self.pipes),
1022            Some(self.noise.clone()),
1023        );
1024        #[cfg(feature = "diagnostics")]
1025        {
1026            r.min_blur_levels = self.min_blur_levels;
1027        }
1028        r.rot = self.rot.clone();
1029        r
1030    }
1031
1032    fn assemble(
1033        device: &wgpu::Device,
1034        queue: &wgpu::Queue,
1035        cfg: RenderConfig,
1036        geom: MeshGeometry,
1037        pipes: std::sync::Arc<Pipelines>,
1038        shared_noise: Option<Vec<Tex>>,
1039    ) -> Self {
1040        let rules = cfg.compat.rules();
1041
1042        let (w, h) = (cfg.width, cfg.height);
1043        let main = [
1044            create_target(device, w, h, "main0"),
1045            create_target(device, w, h, "main1"),
1046        ];
1047        let warped = create_target(device, w, h, "warped");
1048        let final_tex = create_target(device, w, h, "final");
1049        let blur = blur::blur_tex_sizes(w, h)
1050            .iter()
1051            .enumerate()
1052            .map(|(i, &(bw, bh))| create_target(device, bw, bh, &format!("blur{i}")))
1053            .collect();
1054
1055        let rng = Rng::new(cfg.seed);
1056        let noise_tex = match shared_noise {
1057            Some(n) => n,
1058            None => {
1059                let mut noise_rng = rng.fork(0x6E6F_6973);
1060                let mut noise_tex = Vec::new();
1061                for t in noise::ALL_NOISE {
1062                    let data = noise::generate(t, &mut noise_rng, &rules);
1063                    let (size, _, vol) = noise::noise_spec(t);
1064                    noise_tex.push(if vol {
1065                        upload_3d(device, queue, size, &data, "noise_vol")
1066                    } else {
1067                        upload_2d(device, queue, size, size, &data, true, "noise")
1068                    });
1069                }
1070                noise_tex
1071            }
1072        };
1073        let rot = RotParams::randomize(&mut rng.fork(0x7072_6573));
1074        let dummy_2d = upload_2d(device, queue, 1, 1, &[0, 0, 0, 255], false, "dummy2d");
1075        let dummy_3d = upload_3d(device, queue, 1, &[0, 0, 0, 255], "dummy3d");
1076        let (fft_w, fft_h) = if rules.md2_shader_inputs {
1077            (crate::BEATDROP_FFT_BINS, 2)
1078        } else {
1079            (FFT_BINS, 1)
1080        };
1081        let fft = create_r32f_tex(device, queue, "fft", fft_w, fft_h);
1082        let wave = rules
1083            .md2_shader_inputs
1084            .then(|| create_r32f_tex(device, queue, "wave", crate::BEATDROP_WAVE_SAMPLES, 2));
1085
1086        let warp_indices = warp_index_buffer(device, &geom, &rules);
1087        let r = Renderer {
1088            device: device.clone(),
1089            queue: queue.clone(),
1090            cfg,
1091            rules,
1092            geom,
1093            warp_indices,
1094            blit_bg: Default::default(),
1095            blur_bg: Default::default(),
1096            rot,
1097            pipes,
1098            main,
1099            main_idx: 0,
1100            warped,
1101            final_tex,
1102            blur,
1103            noise: noise_tex,
1104            user_tex: HashMap::new(),
1105            sprite_images: HashMap::new(),
1106            anim_time: 0.0,
1107            dummy_2d,
1108            dummy_3d,
1109            fft,
1110            wave,
1111            warp_sink: create_sink(device, w, h),
1112            warp_shader: None,
1113            comp_shader: None,
1114            old_shaders: None,
1115            prev_warp_uv: None,
1116            prev_warp_gpu: None,
1117            uv_readback: None,
1118            mv_state: MotionVectorState::default(),
1119            frames_since_resize: 0,
1120            main_wave_tail: Default::default(),
1121            scratch: FrameScratch::default(),
1122            last_blur_levels: 0,
1123            #[cfg(feature = "diagnostics")]
1124            min_blur_levels: 0,
1125            #[cfg(feature = "diagnostics")]
1126            comp_source_override: None,
1127        };
1128        r.clear_all();
1129        r
1130    }
1131
1132    // ---- configuration ----------------------------------------------------------------
1133
1134    /// The configuration in use (size and mesh follow [`Renderer::resize`] / [`Renderer::set_mesh_size`]).
1135    pub fn config(&self) -> &RenderConfig {
1136        &self.cfg
1137    }
1138
1139    /// The warp-mesh geometry (vertex positions, `rad`, `ang`) — what the engine needs to run per-pixel code.
1140    pub fn mesh_geometry(&self) -> &MeshGeometry {
1141        &self.geom
1142    }
1143
1144    /// The reference behaviour followed where MilkDrop 2 and projectM differ.
1145    pub fn compat(&self) -> Compat {
1146        self.cfg.compat
1147    }
1148
1149    /// The rasteriser actually used for lines and points: the configured one, except that
1150    /// `Compat::MilkDrop2` / `Compat::MilkDrop3` always draw D3D9-style thin quads.
1151    pub fn stroke_raster(&self) -> StrokeRaster {
1152        self.stroke_mode()
1153    }
1154
1155    fn stroke_mode(&self) -> StrokeRaster {
1156        if self.rules.gl_strokes {
1157            self.cfg.stroke
1158        } else {
1159            StrokeRaster::Quads
1160        }
1161    }
1162
1163    /// Switch the line / point rasteriser (see [`StrokeRaster`]); takes effect on the next frame.
1164    pub fn set_stroke_raster(&mut self, s: StrokeRaster) {
1165        self.cfg.stroke = s;
1166    }
1167
1168    /// Resize the internal image (and output). Clears every texture and forgets the previous
1169    /// frame (`m_nFramesSinceResize = 0`). Noise and user textures are kept.
1170    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RenderError> {
1171        check_size(&self.device, width, height)?;
1172        self.geom = MeshGeometry::new(self.cfg.mesh[0], self.cfg.mesh[1], width, height)?;
1173        self.cfg.width = width;
1174        self.cfg.height = height;
1175        let d = &self.device;
1176        self.main = [
1177            create_target(d, width, height, "main0"),
1178            create_target(d, width, height, "main1"),
1179        ];
1180        self.warped = create_target(d, width, height, "warped");
1181        self.warp_sink = create_sink(d, width, height);
1182        self.final_tex = create_target(d, width, height, "final");
1183        *self.blit_bg.borrow_mut() = None;
1184        self.blur_bg.borrow_mut().clear();
1185        self.blur = blur::blur_tex_sizes(width, height)
1186            .iter()
1187            .enumerate()
1188            .map(|(i, &(bw, bh))| create_target(d, bw, bh, &format!("blur{i}")))
1189            .collect();
1190        self.main_idx = 0;
1191        self.forget_prev_warp();
1192        self.mv_state.reset();
1193        self.frames_since_resize = 0;
1194        self.clear_all();
1195        Ok(())
1196    }
1197
1198    /// Change the warp-mesh resolution (cells per axis; the caller applies projectM's clamping, see
1199    /// `lactea::Engine::set_mesh_size`). The previous frame's warp grid and the motion-vector state
1200    /// belong to the old mesh and are forgotten; the images are kept.
1201    pub fn set_mesh_size(&mut self, mesh: [u32; 2]) -> Result<(), RenderError> {
1202        if self.cfg.mesh == mesh {
1203            return Ok(());
1204        }
1205        self.geom = MeshGeometry::new(mesh[0], mesh[1], self.cfg.width, self.cfg.height)?;
1206        self.cfg.mesh = mesh;
1207        self.warp_indices = warp_index_buffer(&self.device, &self.geom, &self.rules);
1208        self.forget_prev_warp();
1209        self.mv_state.reset();
1210        Ok(())
1211    }
1212
1213    /// Change the sub-texel offset added to warp UVs (`projectm_set_texel_offset`); takes effect on
1214    /// the next frame.
1215    pub fn set_texel_offset(&mut self, offset: [f32; 2]) {
1216        self.cfg.texel_offset = offset;
1217    }
1218
1219    /// Start a preset from a black frame (projectM `start_clean`): clears every image and
1220    /// forgets the previous frame's warp grid; drops all user textures (the next preset
1221    /// registers its own). Noise textures are kept.
1222    pub fn reset_images(&mut self) {
1223        self.main_idx = 0;
1224        self.forget_prev_warp();
1225        self.mv_state.reset();
1226        self.main_wave_tail = Default::default();
1227        self.frames_since_resize = 0;
1228        self.user_tex.clear();
1229        self.sprite_images.clear();
1230        self.old_shaders = None;
1231        self.clear_all();
1232    }
1233
1234    fn clear_all(&self) {
1235        let mut enc = self
1236            .device
1237            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1238                label: Some("clear"),
1239            });
1240        let mut all: Vec<&Tex> = vec![&self.main[0], &self.main[1], &self.warped, &self.final_tex];
1241        all.extend(self.blur.iter());
1242        for t in all {
1243            let _ = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1244                label: Some("clear"),
1245                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1246                    view: &t.view,
1247                    depth_slice: None,
1248                    resolve_target: None,
1249                    ops: wgpu::Operations {
1250                        load: wgpu::LoadOp::Clear(wgpu::Color {
1251                            r: 0.0,
1252                            g: 0.0,
1253                            b: 0.0,
1254                            a: if self.rules.main_alpha { 0.0 } else { 1.0 },
1255                        }),
1256                        store: wgpu::StoreOp::Store,
1257                    },
1258                })],
1259                ..Default::default()
1260            });
1261        }
1262        self.queue.submit(Some(enc.finish()));
1263    }
1264
1265    // ---- shaders ----------------------------------------------------------------------
1266
1267    /// Install (or remove, `None` = MD2 `WarpedBlit_NoShaders`) the warp shader.
1268    pub fn set_warp_shader(&mut self, shader: Option<CompiledShader>) -> Result<(), RenderError> {
1269        self.warp_shader = match shader {
1270            Some(s) => Some(self.build_shader_pass(&s, "warp")?),
1271            None => None,
1272        };
1273        Ok(())
1274    }
1275
1276    /// Install (or remove, `None` = MD2 `ShowToUser_NoShaders`) the composite shader.
1277    pub fn set_comp_shader(&mut self, shader: Option<CompiledShader>) -> Result<(), RenderError> {
1278        self.comp_shader = match shader {
1279            Some(s) => Some(self.build_shader_pass(&s, "comp")?),
1280            None => None,
1281        };
1282        Ok(())
1283    }
1284
1285    /// Detach the installed warp / composite shaders and the user textures (MD2's `m_shaders`), leaving the renderer
1286    /// without any. The engine uses this to build the next preset's shaders next to the running ones during a preset
1287    /// blend ([`Renderer::set_old_shader_state`]) and to put the old ones back when that load fails.
1288    pub fn take_shader_state(&mut self) -> ShaderState {
1289        ShaderState(ShaderSet {
1290            warp: self.warp_shader.take(),
1291            comp: self.comp_shader.take(),
1292            user_tex: std::mem::take(&mut self.user_tex),
1293        })
1294    }
1295
1296    /// Reinstall a state taken with [`Renderer::take_shader_state`] (replacing whatever is installed).
1297    pub fn restore_shader_state(&mut self, state: ShaderState) {
1298        let ShaderSet {
1299            warp,
1300            comp,
1301            user_tex,
1302        } = state.0;
1303        self.warp_shader = warp;
1304        self.comp_shader = comp;
1305        self.user_tex = user_tex;
1306    }
1307
1308    /// MD2's `m_OldShaders`: keep `state` (the outgoing preset's shaders and textures) alive for the old half of a
1309    /// preset blend; `None` releases them (`m_OldShaders.*.Clear()` when the blend ends).
1310    pub fn set_old_shader_state(&mut self, state: Option<ShaderState>) {
1311        self.old_shaders = state.map(|s| s.0);
1312    }
1313
1314    /// Whether old shaders are being kept for a preset blend.
1315    pub fn has_old_shaders(&self) -> bool {
1316        self.old_shaders.is_some()
1317    }
1318
1319    /// `(warp, composite)`: whether the installed shaders are user / default pixel shaders (`m_nWarpPSVersion > 0`
1320    /// style flags of the *new* preset and of the old one, if one is kept).
1321    pub fn shader_flags(&self) -> ((bool, bool), (bool, bool)) {
1322        let old = self
1323            .old_shaders
1324            .as_ref()
1325            .map_or((false, false), |o| (o.warp.is_some(), o.comp.is_some()));
1326        (
1327            (self.warp_shader.is_some(), self.comp_shader.is_some()),
1328            old,
1329        )
1330    }
1331
1332    fn build_shader_pass(
1333        &self,
1334        s: &CompiledShader,
1335        label: &str,
1336    ) -> Result<ShaderPass, RenderError> {
1337        if s.interface.textures.len() > lactea_abi::MAX_PASS_TEXTURES {
1338            return Err(RenderError::Invalid(format!(
1339                "{} textures > {}",
1340                s.interface.textures.len(),
1341                lactea_abi::MAX_PASS_TEXTURES
1342            )));
1343        }
1344        let device = &self.device;
1345        // group(1) layout from the interface
1346        // the fold functions read `pu` in the vertex stage
1347        let pass_ubo_stages = if s.folds.is_empty() {
1348            wgpu::ShaderStages::FRAGMENT
1349        } else {
1350            wgpu::ShaderStages::VERTEX_FRAGMENT
1351        };
1352        let mut entries = vec![ubo_entry(
1353            lactea_abi::BINDING_PASS_UNIFORMS,
1354            pass_ubo_stages,
1355        )];
1356        for (i, t) in s.interface.textures.iter().enumerate() {
1357            let dim = match t.dim {
1358                TexDim::D2 => wgpu::TextureViewDimension::D2,
1359                TexDim::D3 => wgpu::TextureViewDimension::D3,
1360            };
1361            // R32Float is not filterable: the translated shader only `textureLoad`s the FFT and BeatDrop's wave
1362            // textures (the sampler entry stays `Filtering` and is never paired with it in a `textureSample`)
1363            let filterable =
1364                !matches!(t.source, TexSource::Fft) && self.engine_wave(&t.source).is_none();
1365            entries.push(tex_entry(
1366                lactea_abi::texture_binding(i as u32),
1367                dim,
1368                filterable,
1369            ));
1370            entries.push(samp_entry(lactea_abi::sampler_binding(i as u32)));
1371        }
1372
1373        #[cfg(not(target_arch = "wasm32"))]
1374        let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
1375        let pass_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1376            label: Some(label),
1377            entries: &entries,
1378        });
1379        // projectM's user warp shader also writes the interpolated warp UV to a second attachment (`texCoords`,
1380        // read back by the motion-vector pass). That second use of `uv` keeps Mesa's NIR from folding constants
1381        // into the varying's plane equation (`uv - 0.5` becomes `plane(uv) - 0.5` instead of the folded
1382        // `plane(uv - 0.5)`, which rounds differently); projectM's driver compiles the shader unfolded, so ours must too.
1383        let (wgsl, uv_sink) = match (label == "warp").then(|| with_uv_output(&s.wgsl)).flatten() {
1384            Some(w) => (w, true),
1385            None => (s.wgsl.clone(), false), // not a recognisable entry: let the shader validation report it
1386        };
1387        let fs = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1388            label: Some(label),
1389            source: wgpu::ShaderSource::Wgsl(wgsl.as_str().into()),
1390        });
1391        let fold_vs = (!s.folds.is_empty()).then(|| {
1392            device.create_shader_module(wgpu::ShaderModuleDescriptor {
1393                label: Some(label),
1394                source: wgpu::ShaderSource::Wgsl(shaders::mesh_vs_folds(&s.folds).into()),
1395            })
1396        });
1397        let mesh_vs = fold_vs.as_ref().unwrap_or(&self.pipes.mesh_vs);
1398        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1399            label: Some(label),
1400            bind_group_layouts: &[Some(&self.pipes.bgl_mu), Some(&pass_bgl)],
1401            immediate_size: 0,
1402        });
1403        let make_pipeline = |layout: &wgpu::PipelineLayout,
1404                             vs: &wgpu::ShaderModule,
1405                             buffers: &[Option<wgpu::VertexBufferLayout>],
1406                             blend: Option<wgpu::BlendState>| {
1407            let color = Some(wgpu::ColorTargetState {
1408                format: INTERNAL_FORMAT,
1409                blend,
1410                write_mask: wgpu::ColorWrites::COLOR,
1411            });
1412            let sink = Some(wgpu::ColorTargetState {
1413                format: WARP_SINK_FORMAT,
1414                blend: None,
1415                write_mask: wgpu::ColorWrites::ALL,
1416            });
1417            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1418                label: Some(label),
1419                layout: Some(layout),
1420                vertex: wgpu::VertexState {
1421                    module: vs,
1422                    entry_point: Some("vs_main"),
1423                    compilation_options: Default::default(),
1424                    buffers,
1425                },
1426                primitive: wgpu::PrimitiveState::default(),
1427                depth_stencil: None,
1428                multisample: wgpu::MultisampleState::default(),
1429                fragment: Some(wgpu::FragmentState {
1430                    module: &fs,
1431                    entry_point: Some(FRAGMENT_ENTRY),
1432                    compilation_options: Default::default(),
1433                    targets: &[color, sink][..if uv_sink { 2 } else { 1 }],
1434                }),
1435                multiview_mask: None,
1436                cache: None,
1437            })
1438        };
1439        let pipeline = make_pipeline(&layout, mesh_vs, &[Some(mesh_layout())], None);
1440        // MD2's preset blend draws the second pass of a shader pair alpha-blended over the first
1441        let alpha_pipelines = self.rules.md2_preset_blend.then(|| {
1442            [Blend::SrcAlpha, Blend::InvSrcAlpha]
1443                .map(|b| make_pipeline(&layout, mesh_vs, &[Some(mesh_layout())], blend_state(b)))
1444        });
1445        let warp_pipeline = if label == "warp" {
1446            let warp_vs_sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1447                label: Some("warp_vs"),
1448                source: wgpu::ShaderSource::Wgsl(
1449                    if s.folds.is_empty() {
1450                        shaders::warp_vs(2)
1451                    } else {
1452                        shaders::warp_vs_folds(2, &s.folds)
1453                    }
1454                    .into(),
1455                ),
1456            });
1457            let warp_layout_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1458                label: Some("warp gpu"),
1459                bind_group_layouts: &[
1460                    Some(&self.pipes.bgl_mu),
1461                    Some(&pass_bgl),
1462                    Some(&self.pipes.bgl_warp_vs),
1463                ],
1464                immediate_size: 0,
1465            });
1466            Some(make_pipeline(
1467                &warp_layout_pl,
1468                &warp_vs_sm,
1469                &[Some(warp_layout())],
1470                None,
1471            ))
1472        } else {
1473            None
1474        };
1475        #[cfg(not(target_arch = "wasm32"))]
1476        if let Some(err) = pollster::block_on(scope.pop()) {
1477            return Err(RenderError::Shader(err.to_string()));
1478        }
1479        Ok(ShaderPass {
1480            pipeline,
1481            warp_pipeline,
1482            pass_bgl,
1483            interface: s.interface.clone(),
1484            uv_sink,
1485            alpha_pipelines,
1486        })
1487    }
1488
1489    // ---- textures ---------------------------------------------------------------------
1490
1491    /// Register a user texture (`sampler_<name>`): RGBA8, row 0 = top, with a CPU mip chain.
1492    /// `name` is matched case-insensitively against `TexSource::User`.
1493    pub fn set_user_texture(
1494        &mut self,
1495        name: &str,
1496        w: u32,
1497        h: u32,
1498        rgba8: &[u8],
1499    ) -> Result<(), RenderError> {
1500        check_frames(
1501            &format!("user texture {name}"),
1502            self.device.limits().max_texture_dimension_2d,
1503            w,
1504            h,
1505            &[rgba8],
1506        )?;
1507        let tex = upload_2d(&self.device, &self.queue, w, h, rgba8, true, name);
1508        self.user_tex
1509            .insert(name.to_ascii_lowercase(), UserTex { tex, anim: None });
1510        Ok(())
1511    }
1512
1513    /// Register an animated user texture (an animated GIF as `sampler_<name>`, `Compat::MilkDrop3`): `frames` are
1514    /// `w * h * 4` RGBA8 images (row 0 = top), `delays` their durations in seconds. Every draw shows the frame
1515    /// [`gif_frame_index`](crate::gif_frame_index) picks for the time of the frame being rendered. No mip chain.
1516    pub fn set_user_animation(
1517        &mut self,
1518        name: &str,
1519        w: u32,
1520        h: u32,
1521        frames: &[&[u8]],
1522        delays: &[f64],
1523    ) -> Result<(), RenderError> {
1524        check_frames(
1525            name,
1526            self.device.limits().max_texture_dimension_2d,
1527            w,
1528            h,
1529            frames,
1530        )?;
1531        if delays.len() != frames.len() {
1532            return Err(RenderError::Invalid(format!(
1533                "animated texture {name}: {} frames but {} delays",
1534                frames.len(),
1535                delays.len()
1536            )));
1537        }
1538        let tex: Vec<Tex> = frames
1539            .iter()
1540            .map(|f| upload_2d(&self.device, &self.queue, w, h, f, false, name))
1541            .collect();
1542        self.user_tex.insert(
1543            name.to_ascii_lowercase(),
1544            UserTex {
1545                tex: tex[0].clone(),
1546                anim: Some(UserAnim {
1547                    frames: tex,
1548                    delays: delays.to_vec(),
1549                }),
1550            },
1551        );
1552        Ok(())
1553    }
1554
1555    /// Register the image of an MD3 sprite under `id` ([`SpriteDraw::image`](crate::SpriteDraw::image)), replacing
1556    /// any image with that id. `frames` are `w * h * 4` RGBA8 images (row 0 = top, straight alpha, colour key already
1557    /// applied); a static image has one frame and `mips` (full chain, trilinear sampling), a GIF has no mips.
1558    pub fn set_sprite_image(
1559        &mut self,
1560        id: u32,
1561        w: u32,
1562        h: u32,
1563        frames: &[&[u8]],
1564        mips: bool,
1565    ) -> Result<(), RenderError> {
1566        check_frames(
1567            "sprite",
1568            self.device.limits().max_texture_dimension_2d,
1569            w,
1570            h,
1571            frames,
1572        )?;
1573        // a sprite is about to be drawn: build the pipelines now, not as a hitch in the first frame that draws one
1574        self.pipes.sprites(&self.device);
1575        let views = frames
1576            .iter()
1577            .map(|f| upload_2d(&self.device, &self.queue, w, h, f, mips, "sprite").view)
1578            .collect();
1579        self.sprite_images.insert(id, SpriteImage { frames: views });
1580        Ok(())
1581    }
1582
1583    /// Forget every sprite image.
1584    pub fn clear_sprite_images(&mut self) {
1585        self.sprite_images.clear();
1586    }
1587
1588    /// Forget every user texture (`set_user_texture` / `set_user_animation`); shaders sampling one see the
1589    /// placeholder until it is registered again.
1590    pub fn clear_user_textures(&mut self) {
1591        self.user_tex.clear();
1592    }
1593
1594    /// Whether an image is registered under `id`.
1595    pub fn has_sprite_image(&self, id: u32) -> bool {
1596        self.sprite_images.contains_key(&id)
1597    }
1598
1599    /// Forget the image registered under `id`, if any.
1600    pub fn remove_sprite_image(&mut self, id: u32) {
1601        self.sprite_images.remove(&id);
1602    }
1603    /// Draw sprites (any layer value) onto `target`, an `Rgba8Unorm` view: the sprite pass on its own, for hosts
1604    /// that composite themselves and for tests. Draws whose image or frame is not registered are skipped.
1605    pub fn draw_sprites(
1606        &self,
1607        encoder: &mut wgpu::CommandEncoder,
1608        target: &wgpu::TextureView,
1609        draws: &[SpriteDraw],
1610    ) {
1611        let refs: Vec<&SpriteDraw> = draws.iter().collect();
1612        self.sprite_pass(encoder, target, &refs);
1613    }
1614
1615    /// Draw `draws` into the image the next frame's warp reads (projectM's `burn`), the ones with `burn` set only:
1616    /// call after [`Renderer::render_frame_to_output`], when that image is the one just produced.
1617    pub fn burn_sprites(&self, encoder: &mut wgpu::CommandEncoder, draws: &[SpriteDraw]) {
1618        let burn: Vec<&SpriteDraw> = draws.iter().filter(|d| d.burn).collect();
1619        if !burn.is_empty() {
1620            self.sprite_pass(encoder, &self.main[self.main_idx].view, &burn);
1621        }
1622    }
1623
1624    /// Draw `draws` onto `target`, a view of the host's output (`RenderConfig::output_format`), loaded not cleared:
1625    /// sprites over a finished frame, e.g. over a soft cut's blend.
1626    pub fn draw_sprites_to_output(
1627        &self,
1628        encoder: &mut wgpu::CommandEncoder,
1629        target: &wgpu::TextureView,
1630        draws: &[SpriteDraw],
1631    ) {
1632        let refs: Vec<&SpriteDraw> = draws.iter().collect();
1633        self.pipes
1634            .sprites_for(&self.device, self.cfg.output_format)
1635            .draw(
1636                &self.device,
1637                encoder,
1638                target,
1639                &self.pipes.bgl_tex,
1640                self.pipes.sampler(Filter::Linear, Address::Wrap, false),
1641                &self.sprite_images,
1642                &refs,
1643            );
1644    }
1645
1646    /// Read a stage back as `(width, height, RGBA8)` (row 0 = top). The command buffers of the
1647    /// frame must have been submitted. `Stage::Main` is the image the next frame's warp samples;
1648    /// `Warped` the image right after the warp pass; `Blur1..3` the user-visible blur levels
1649    /// (blur textures 1, 3, 5); `Final` the composite output.
1650    pub fn read_stage(&self, stage: Stage) -> Result<(u32, u32, Vec<u8>), RenderError> {
1651        let t = match stage {
1652            Stage::Final => &self.final_tex,
1653            Stage::Main => &self.main[self.main_idx],
1654            Stage::Warped => &self.warped,
1655            Stage::Blur1 => &self.blur[1],
1656            Stage::Blur2 => &self.blur[3],
1657            Stage::Blur3 => &self.blur[5],
1658        };
1659        self.read_texture(t)
1660    }
1661
1662    fn read_texture(&self, t: &Tex) -> Result<(u32, u32, Vec<u8>), RenderError> {
1663        let data = readback_rgba8(&self.device, &self.queue, &t.texture, t.w, t.h)?;
1664        Ok((t.w, t.h, data))
1665    }
1666
1667    // ---- rendering --------------------------------------------------------------------
1668
1669    /// Blur levels forced on by a diagnostic request (0 without the `diagnostics` feature).
1670    fn diagnostic_blur_levels(&self) -> u8 {
1671        #[cfg(feature = "diagnostics")]
1672        {
1673            self.min_blur_levels.min(3)
1674        }
1675        #[cfg(not(feature = "diagnostics"))]
1676        {
1677            0
1678        }
1679    }
1680
1681    /// The image a composite pass reads as its `sampler_main`: `regular`, or the injected one.
1682    fn comp_source_view<'a>(&'a self, regular: &'a wgpu::TextureView) -> &'a wgpu::TextureView {
1683        #[cfg(feature = "diagnostics")]
1684        if let Some(t) = &self.comp_source_override {
1685            return &t.view;
1686        }
1687        regular
1688    }
1689
1690    /// Highest blur level (0..=3) the installed shaders require (including the old preset's while a preset blend
1691    /// keeps them: MD2's `ApplyShaderParams` counts every pass it applies, also `m_OldShaders`).
1692    pub fn blur_levels_required(&self) -> u8 {
1693        let level = |p: &Option<ShaderPass>| p.as_ref().map_or(0, |s| s.interface.max_blur_level);
1694        let mut m = level(&self.warp_shader).max(level(&self.comp_shader));
1695        if let Some(o) = &self.old_shaders {
1696            m = m.max(level(&o.warp)).max(level(&o.comp));
1697        }
1698        m.min(3)
1699    }
1700
1701    /// Forget the previous frame's warp grid, vertex inputs and their pending UV readback.
1702    fn forget_prev_warp(&mut self) {
1703        self.prev_warp_uv = None;
1704        self.prev_warp_gpu = None;
1705        if let Some(rb) = &mut self.uv_readback {
1706            rb.pending = None;
1707        }
1708    }
1709
1710    /// Submit the UV readback of `prev_warp_gpu` (the vertex inputs of the frame just recorded), or drop the pending
1711    /// one if there are none.
1712    fn submit_uv_readback(&mut self) {
1713        let Some(wg) = self.prev_warp_gpu.as_ref() else {
1714            if let Some(rb) = &mut self.uv_readback {
1715                rb.pending = None;
1716            }
1717            return;
1718        };
1719        let (w, h) = (self.geom.gx + 1, self.geom.gy + 1);
1720        let verts = geom::build_warp_gpu_vertices(&self.geom, &wg.vars);
1721        let toff = self.texel_offset_uv();
1722        let mut vu = self.warp_vs_uniforms(wg, toff, 1.0);
1723        vu.diffuse = [w as f32, h as f32, 0.0, 0.0];
1724        if !matches!(&self.uv_readback, Some(rb) if rb.w == w && rb.h == h) {
1725            self.uv_readback = Some(UvReadback::new(&self.device, &self.pipes, w, h));
1726        }
1727        if let Some(rb) = &mut self.uv_readback {
1728            rb.submit(&self.device, &self.queue, &self.pipes, &verts, &vu, toff);
1729        }
1730    }
1731
1732    /// The GPU's own per-vertex warp UVs of `prev_warp_gpu` (`warp_vs` evaluated on the device, lactea mesh index
1733    /// order). projectM's motion vector lookup reads the interpolation of *these* (`RG16F` UV map written by the warp
1734    /// pass), so the CPU port of the formula (`warp_mesh`) differs from it by the GPU's `pow` / `sin` / `cos`
1735    /// approximations and fusion.
1736    ///
1737    /// Normally the readback was submitted at the end of the previous frame ([`Renderer::submit_uv_readback`]); it
1738    /// is only recorded here (and waited for) when that frame did not draw motion vectors or the texel offset
1739    /// changed since.
1740    fn gpu_warp_vertex_uv(&mut self) -> Result<Vec<[f32; 2]>, RenderError> {
1741        let toff = self.texel_offset_uv();
1742        let submitted = self
1743            .uv_readback
1744            .as_ref()
1745            .and_then(|rb| rb.pending.as_ref())
1746            .is_some_and(|(_, t)| *t == toff);
1747        if !submitted {
1748            self.submit_uv_readback();
1749        }
1750        let Some(rb) = self.uv_readback.as_mut() else {
1751            return Err(RenderError::Readback(
1752                "no previous warp vertex inputs".to_owned(),
1753            ));
1754        };
1755        let uv = rb.collect(&self.device, &self.geom);
1756        if uv.is_err() {
1757            self.uv_readback = None;
1758        }
1759        uv
1760    }
1761
1762    fn texel_offset_uv(&self) -> [f32; 2] {
1763        warp_mesh::texel_offset_uv(self.cfg.texel_offset, self.cfg.width, self.cfg.height)
1764    }
1765
1766    /// Default warp UVs when the engine supplies none: identity motion.
1767    fn default_warp_uv(&self, f: &FrameInput) -> Vec<[f32; 2]> {
1768        let anim = WarpAnim::new(f.time as f32, 1.0, 1.0);
1769        let v = VertexVars {
1770            warp: 0.0,
1771            ..Default::default()
1772        };
1773        warp_mesh::warp_mesh_uniform(&self.geom, &v, &anim, self.texel_offset_uv())
1774    }
1775
1776    /// The CPU warp UV grid of `wg` (`warp_mesh`, as the engine computes it for a renderer without a GPU warp stage):
1777    /// the fallback of a motion vector lookup whose GPU readback failed.
1778    fn cpu_warp_uv(&self, wg: &crate::frame::WarpGpu) -> Vec<[f32; 2]> {
1779        let toff = self.texel_offset_uv();
1780        wg.vars
1781            .iter()
1782            .enumerate()
1783            .map(|(n, vv)| warp_mesh::warp_vertex_uv(&self.geom, n, vv, &wg.anim, toff))
1784            .collect()
1785    }
1786
1787    /// Record one frame into `encoder`, ending with the composite blitted to `target`.
1788    ///
1789    /// All per-frame GPU data is baked into buffers at record time, so frames may be recorded in
1790    /// any order, but the encoder must be submitted before [`Renderer::read_stage`] is called.
1791    /// `target` must be a view of a `cfg.width x cfg.height` texture of `cfg.output_format`.
1792    ///
1793    /// Fails with [`RenderError::Invalid`] (recording nothing) if `input.warp_uv` does not match the mesh or
1794    /// `input.md2_blend` is set without `Compat::MilkDrop2` / `Compat::MilkDrop3`.
1795    pub fn render_frame(
1796        &mut self,
1797        encoder: &mut wgpu::CommandEncoder,
1798        input: &FrameInput,
1799        target: &wgpu::TextureView,
1800    ) -> Result<(), RenderError> {
1801        self.render_frame_inner(encoder, input, Some(target))
1802    }
1803
1804    /// Like [`Renderer::render_frame`] but stops after the composite: the finished image stays in
1805    /// the renderer ([`Renderer::output_view`]) and nothing is written to a host target. Used for
1806    /// presets that are blended into the frame by a transition.
1807    pub fn render_frame_to_output(
1808        &mut self,
1809        encoder: &mut wgpu::CommandEncoder,
1810        input: &FrameInput,
1811    ) -> Result<(), RenderError> {
1812        self.render_frame_inner(encoder, input, None)
1813    }
1814
1815    /// The composited image of the last rendered frame (`Rgba8Unorm`, row 0 = top, the `final`
1816    /// stage): projectM's `Preset::OutputTexture()`.
1817    pub fn output_view(&self) -> &wgpu::TextureView {
1818        &self.final_tex.view
1819    }
1820
1821    /// Start this preset from `src`'s composited image instead of black (projectM
1822    /// `DrawInitialImage`, used when `start_clean` is off): the image the first warp samples.
1823    /// `src` must have the same size. Call after [`Renderer::reset_images`].
1824    ///
1825    /// Fails with [`RenderError::Invalid`] if the two renderers differ in size.
1826    pub fn draw_initial_image(
1827        &mut self,
1828        encoder: &mut wgpu::CommandEncoder,
1829        src: &Renderer,
1830    ) -> Result<(), RenderError> {
1831        if (self.cfg.width, self.cfg.height) != (src.cfg.width, src.cfg.height) {
1832            return Err(RenderError::Invalid(format!(
1833                "initial image size mismatch: {}x{} vs {}x{}",
1834                self.cfg.width, self.cfg.height, src.cfg.width, src.cfg.height
1835            )));
1836        }
1837        self.main_idx = 0;
1838        encoder.copy_texture_to_texture(
1839            wgpu::TexelCopyTextureInfo {
1840                texture: &src.final_tex.texture,
1841                mip_level: 0,
1842                origin: wgpu::Origin3d::ZERO,
1843                aspect: wgpu::TextureAspect::All,
1844            },
1845            wgpu::TexelCopyTextureInfo {
1846                texture: &self.main[0].texture,
1847                mip_level: 0,
1848                origin: wgpu::Origin3d::ZERO,
1849                aspect: wgpu::TextureAspect::All,
1850            },
1851            wgpu::Extent3d {
1852                width: self.cfg.width,
1853                height: self.cfg.height,
1854                depth_or_array_layers: 1,
1855            },
1856        );
1857        Ok(())
1858    }
1859
1860    /// Reject frame inputs the renderer cannot draw, before anything is recorded.
1861    fn check_input(&self, input: &FrameInput) -> Result<(), RenderError> {
1862        if let Some(u) = &input.warp_uv {
1863            let n = self.geom.vertex_count();
1864            if u.len() != n {
1865                return Err(RenderError::Invalid(format!(
1866                    "FrameInput.warp_uv has {} entries, the {}x{} mesh needs {n}",
1867                    u.len(),
1868                    self.geom.gx,
1869                    self.geom.gy
1870                )));
1871            }
1872        }
1873        if self.rules.warp_uv_on_gpu
1874            && let Some(wg) = &input.warp_gpu
1875            && wg.vars.len() != self.geom.vertex_count()
1876        {
1877            return Err(RenderError::Invalid(format!(
1878                "FrameInput.warp_gpu has {} vertices, the {}x{} mesh needs {}",
1879                wg.vars.len(),
1880                self.geom.gx,
1881                self.geom.gy,
1882                self.geom.vertex_count()
1883            )));
1884        }
1885        if input.md2_blend.is_some() && !self.rules.md2_preset_blend {
1886            return Err(RenderError::Invalid(
1887                "FrameInput.md2_blend needs Compat::MilkDrop2 or Compat::MilkDrop3".to_owned(),
1888            ));
1889        }
1890        Ok(())
1891    }
1892
1893    // ---- fixed-function content ---------------------------------------------------------
1894}
1895
1896const BLACK: wgpu::Color = wgpu::Color {
1897    r: 0.0,
1898    g: 0.0,
1899    b: 0.0,
1900    a: 1.0,
1901};
1902
1903/// Per-frame working buffers of the overlay / motion-vector builders, kept across frames so a frame
1904/// allocates nothing once they are warm. Contents are overwritten by every user.
1905#[derive(Default)]
1906struct FrameScratch {
1907    pm_wave: wavegen::PmWaveScratch,
1908    /// custom-wave source points / colours
1909    pts: Vec<[f32; 2]>,
1910    cols: Vec<[f32; 4]>,
1911    /// smoothed points / colours
1912    sp: Vec<[f32; 2]>,
1913    sc: Vec<[f32; 4]>,
1914    /// vertices handed to a `Batch` (dots, segments, motion vectors)
1915    verts: Vec<WfVertex>,
1916    /// one strip's segments before they are appended to `verts`
1917    seg: Vec<WfVertex>,
1918}
1919
1920/// `SmoothWave` carrying per-vertex colours (`vo[j+1].Diffuse = vi[i].Diffuse`), into reusable buffers.
1921fn smooth_with_colors_into(
1922    sp: &mut Vec<[f32; 2]>,
1923    sc: &mut Vec<[f32; 4]>,
1924    pts: &[[f32; 2]],
1925    cols: &[[f32; 4]],
1926) {
1927    wavegen::smooth_wave_into(sp, pts);
1928    let n = pts.len();
1929    sc.clear();
1930    sc.reserve(sp.len());
1931    for c in &cols[..n - 1] {
1932        sc.push(*c);
1933        sc.push(*c);
1934    }
1935    sc.push(cols[n - 1]);
1936}
1937
1938#[cfg(test)]
1939mod uv_output_tests {
1940    use super::with_uv_output;
1941
1942    /// Regression (`sin((uv.x - 0.5) * 100)` gave 15 480 wrong pixels in 13 frames): the warp shader's
1943    /// fragment entry gets projectM's second `texCoords` output so `uv` has two uses, like projectM's.
1944    #[test]
1945    fn warp_entry_gets_a_second_uv_output() {
1946        let src = "fn f() {}\n@fragment\nfn fs_main(in: VsOut) -> @location(0) vec4<f32> {\n    return in.diffuse;\n}\n";
1947        let out = with_uv_output(src).unwrap();
1948        assert!(with_uv_output("this is not wgsl").is_none());
1949        assert!(out.contains("fn fs_main_color(in: VsOut) -> vec4<f32> {"));
1950        assert!(out.contains("fn fs_main(in: VsOut) -> WarpFsOut"));
1951        assert!(out.contains("o.uv = in.uv.xy;"));
1952        assert_eq!(out.matches("@fragment").count(), 1);
1953    }
1954}