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